blob: e6f854f1a56b24db02f1bdf05c4ed4ce8b48e763 [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 Sands777d2302009-05-09 07:06:46 +00005205 uint64_t Size = TD.getTypeAllocSize(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 Sands777d2302009-05-09 07:06:46 +00005297 uint64_t Size = TD.getTypeAllocSize(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 Sands777d2302009-05-09 07:06:46 +00005313 uint64_t VariableScale = TD.getTypeAllocSize(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 Sands777d2302009-05-09 07:06:46 +00005327 uint64_t Size = TD.getTypeAllocSize(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.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005601 Constant *RHSInt = LHSUnsigned
5602 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5603 : ConstantExpr::getFPToSI(RHSC, IntTy);
5604 if (!RHS.isZero()) {
5605 bool Equal = LHSUnsigned
5606 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5607 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5608 if (!Equal) {
5609 // If we had a comparison against a fractional value, we have to adjust
5610 // the compare predicate and sometimes the value. RHSC is rounded towards
5611 // zero at this point.
5612 switch (Pred) {
5613 default: assert(0 && "Unexpected integer comparison!");
5614 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedman8b019c82008-11-30 22:48:49 +00005615 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005616 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5617 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5618 case ICmpInst::ICMP_ULE:
5619 // (float)int <= 4.4 --> int <= 4
5620 // (float)int <= -4.4 --> false
5621 if (RHS.isNegative())
5622 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5623 break;
5624 case ICmpInst::ICMP_SLE:
5625 // (float)int <= 4.4 --> int <= 4
5626 // (float)int <= -4.4 --> int < -4
5627 if (RHS.isNegative())
5628 Pred = ICmpInst::ICMP_SLT;
5629 break;
5630 case ICmpInst::ICMP_ULT:
5631 // (float)int < -4.4 --> false
5632 // (float)int < 4.4 --> int <= 4
5633 if (RHS.isNegative())
5634 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5635 Pred = ICmpInst::ICMP_ULE;
5636 break;
5637 case ICmpInst::ICMP_SLT:
5638 // (float)int < -4.4 --> int < -4
5639 // (float)int < 4.4 --> int <= 4
5640 if (!RHS.isNegative())
5641 Pred = ICmpInst::ICMP_SLE;
5642 break;
5643 case ICmpInst::ICMP_UGT:
5644 // (float)int > 4.4 --> int > 4
5645 // (float)int > -4.4 --> true
5646 if (RHS.isNegative())
5647 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5648 break;
5649 case ICmpInst::ICMP_SGT:
5650 // (float)int > 4.4 --> int > 4
5651 // (float)int > -4.4 --> int >= -4
5652 if (RHS.isNegative())
5653 Pred = ICmpInst::ICMP_SGE;
5654 break;
5655 case ICmpInst::ICMP_UGE:
5656 // (float)int >= -4.4 --> true
5657 // (float)int >= 4.4 --> int > 4
5658 if (!RHS.isNegative())
5659 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5660 Pred = ICmpInst::ICMP_UGT;
5661 break;
5662 case ICmpInst::ICMP_SGE:
5663 // (float)int >= -4.4 --> int >= -4
5664 // (float)int >= 4.4 --> int > 4
5665 if (!RHS.isNegative())
5666 Pred = ICmpInst::ICMP_SGT;
5667 break;
5668 }
Chris Lattnera5406232008-05-19 20:18:56 +00005669 }
5670 }
5671
5672 // Lower this FP comparison into an appropriate integer version of the
5673 // comparison.
5674 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5675}
5676
Reid Spencere4d87aa2006-12-23 06:05:41 +00005677Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5678 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005679 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005680
Chris Lattner58e97462007-01-14 19:42:17 +00005681 // Fold trivial predicates.
5682 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005683 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005684 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005685 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005686
5687 // Simplify 'fcmp pred X, X'
5688 if (Op0 == Op1) {
5689 switch (I.getPredicate()) {
5690 default: assert(0 && "Unknown predicate!");
5691 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5692 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5693 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedman8b019c82008-11-30 22:48:49 +00005694 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005695 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5696 case FCmpInst::FCMP_OLT: // True if ordered and less than
5697 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedman8b019c82008-11-30 22:48:49 +00005698 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005699
5700 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5701 case FCmpInst::FCMP_ULT: // True if unordered or less than
5702 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5703 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5704 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5705 I.setPredicate(FCmpInst::FCMP_UNO);
5706 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5707 return &I;
5708
5709 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5710 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5711 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5712 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5713 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5714 I.setPredicate(FCmpInst::FCMP_ORD);
5715 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5716 return &I;
5717 }
5718 }
5719
Reid Spencere4d87aa2006-12-23 06:05:41 +00005720 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005721 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005722
Reid Spencere4d87aa2006-12-23 06:05:41 +00005723 // Handle fcmp with constant RHS
5724 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005725 // If the constant is a nan, see if we can fold the comparison based on it.
5726 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5727 if (CFP->getValueAPF().isNaN()) {
5728 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedman8b019c82008-11-30 22:48:49 +00005729 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005730 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5731 "Comparison must be either ordered or unordered!");
5732 // True if unordered.
Eli Friedman8b019c82008-11-30 22:48:49 +00005733 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005734 }
5735 }
5736
Reid Spencere4d87aa2006-12-23 06:05:41 +00005737 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5738 switch (LHSI->getOpcode()) {
5739 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005740 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5741 // block. If in the same block, we're encouraging jump threading. If
5742 // not, we are just pessimizing the code by making an i1 phi.
5743 if (LHSI->getParent() == I.getParent())
5744 if (Instruction *NV = FoldOpIntoPhi(I))
5745 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005746 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005747 case Instruction::SIToFP:
5748 case Instruction::UIToFP:
5749 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5750 return NV;
5751 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005752 case Instruction::Select:
5753 // If either operand of the select is a constant, we can fold the
5754 // comparison into the select arms, which will cause one to be
5755 // constant folded and the select turned into a bitwise or.
5756 Value *Op1 = 0, *Op2 = 0;
5757 if (LHSI->hasOneUse()) {
5758 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5759 // Fold the known value into the constant operand.
5760 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5761 // Insert a new FCmp of the other select operand.
5762 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5763 LHSI->getOperand(2), RHSC,
5764 I.getName()), I);
5765 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5766 // Fold the known value into the constant operand.
5767 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5768 // Insert a new FCmp of the other select operand.
5769 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5770 LHSI->getOperand(1), RHSC,
5771 I.getName()), I);
5772 }
5773 }
5774
5775 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005776 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005777 break;
5778 }
5779 }
5780
5781 return Changed ? &I : 0;
5782}
5783
5784Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5785 bool Changed = SimplifyCompare(I);
5786 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5787 const Type *Ty = Op0->getType();
5788
5789 // icmp X, X
5790 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005791 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005792 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005793
5794 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005795 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005796
Reid Spencere4d87aa2006-12-23 06:05:41 +00005797 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005798 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005799 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5800 isa<ConstantPointerNull>(Op0)) &&
5801 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005802 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005803 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005804 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005805
Reid Spencere4d87aa2006-12-23 06:05:41 +00005806 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005807 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005808 switch (I.getPredicate()) {
5809 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005810 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005811 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005812 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005813 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005814 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005815 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005816 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005817
Reid Spencere4d87aa2006-12-23 06:05:41 +00005818 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005819 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005820 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005821 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005822 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005823 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005824 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005825 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005826 case ICmpInst::ICMP_SGT:
5827 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005828 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005829 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5830 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5831 InsertNewInstBefore(Not, I);
5832 return BinaryOperator::CreateAnd(Not, Op0);
5833 }
5834 case ICmpInst::ICMP_UGE:
5835 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5836 // FALL THROUGH
5837 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005838 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005839 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005840 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005841 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005842 case ICmpInst::ICMP_SGE:
5843 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5844 // FALL THROUGH
5845 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5846 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5847 InsertNewInstBefore(Not, I);
5848 return BinaryOperator::CreateOr(Not, Op0);
5849 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005850 }
Chris Lattner8b170942002-08-09 23:47:40 +00005851 }
5852
Dan Gohman1c8491e2009-04-25 17:12:48 +00005853 unsigned BitWidth = 0;
5854 if (TD)
5855 BitWidth = TD->getTypeSizeInBits(Ty);
5856 else if (isa<IntegerType>(Ty))
5857 BitWidth = Ty->getPrimitiveSizeInBits();
5858
5859 bool isSignBit = false;
5860
Dan Gohman81b28ce2008-09-16 18:46:06 +00005861 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005862 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005863 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005864
Chris Lattnerb6566012008-01-05 01:18:20 +00005865 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5866 if (I.isEquality() && CI->isNullValue() &&
5867 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5868 // (icmp cond A B) if cond is equality
5869 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005870 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005871
Dan Gohman81b28ce2008-09-16 18:46:06 +00005872 // If we have an icmp le or icmp ge instruction, turn it into the
5873 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5874 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005875 switch (I.getPredicate()) {
5876 default: break;
5877 case ICmpInst::ICMP_ULE:
5878 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5879 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5880 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5881 case ICmpInst::ICMP_SLE:
5882 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5883 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5884 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5885 case ICmpInst::ICMP_UGE:
5886 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5887 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5888 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5889 case ICmpInst::ICMP_SGE:
5890 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5891 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5892 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5893 }
5894
Chris Lattner183661e2008-07-11 05:40:05 +00005895 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005896 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005897 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00005898 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5899 }
5900
5901 // See if we can fold the comparison based on range information we can get
5902 // by checking whether bits are known to be zero or one in the input.
5903 if (BitWidth != 0) {
5904 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
5905 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
5906
5907 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00005908 isSignBit ? APInt::getSignBit(BitWidth)
5909 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00005910 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005911 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00005912 if (SimplifyDemandedBits(I.getOperandUse(1),
5913 APInt::getAllOnesValue(BitWidth),
5914 Op1KnownZero, Op1KnownOne, 0))
5915 return &I;
5916
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005917 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00005918 // in. Compute the Min, Max and RHS values based on the known bits. For the
5919 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00005920 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
5921 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
5922 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5923 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
5924 Op0Min, Op0Max);
5925 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
5926 Op1Min, Op1Max);
5927 } else {
5928 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
5929 Op0Min, Op0Max);
5930 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
5931 Op1Min, Op1Max);
5932 }
5933
Chris Lattner183661e2008-07-11 05:40:05 +00005934 // If Min and Max are known to be the same, then SimplifyDemandedBits
5935 // figured out that the LHS is a constant. Just constant fold this now so
5936 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00005937 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
5938 return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
5939 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
5940 return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
5941
Chris Lattner183661e2008-07-11 05:40:05 +00005942 // Based on the range information we know about the LHS, see if we can
5943 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00005944 switch (I.getPredicate()) {
Chris Lattner84dff672008-07-11 05:08:55 +00005945 default: assert(0 && "Unknown icmp opcode!");
5946 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005947 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner84dff672008-07-11 05:08:55 +00005948 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5949 break;
5950 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005951 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner84dff672008-07-11 05:08:55 +00005952 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5953 break;
5954 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005955 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Chris Lattner84dff672008-07-11 05:08:55 +00005956 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00005957 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00005958 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00005959 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Chris Lattner183661e2008-07-11 05:40:05 +00005960 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00005961 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5962 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
5963 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5964
5965 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5966 if (CI->isMinValue(true))
5967 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Chris Lattner183661e2008-07-11 05:40:05 +00005968 ConstantInt::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005969 }
Chris Lattner84dff672008-07-11 05:08:55 +00005970 break;
5971 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005972 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00005973 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00005974 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00005975 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00005976
5977 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Chris Lattner183661e2008-07-11 05:40:05 +00005978 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00005979 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5980 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
5981 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5982
5983 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5984 if (CI->isMaxValue(true))
5985 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5986 ConstantInt::getNullValue(Op0->getType()));
5987 }
Chris Lattner84dff672008-07-11 05:08:55 +00005988 break;
5989 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005990 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Chris Lattner84dff672008-07-11 05:08:55 +00005991 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00005992 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Chris Lattner84dff672008-07-11 05:08:55 +00005993 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00005994 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Chris Lattner183661e2008-07-11 05:40:05 +00005995 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00005996 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5997 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
5998 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5999 }
Chris Lattner84dff672008-07-11 05:08:55 +00006000 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006001 case ICmpInst::ICMP_SGT:
6002 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006003 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006004 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006005 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006006
6007 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Chris Lattner183661e2008-07-11 05:40:05 +00006008 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006009 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6010 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6011 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6012 }
6013 break;
6014 case ICmpInst::ICMP_SGE:
6015 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6016 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6017 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6018 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6019 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6020 break;
6021 case ICmpInst::ICMP_SLE:
6022 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6023 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6024 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6025 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6026 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6027 break;
6028 case ICmpInst::ICMP_UGE:
6029 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6030 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6031 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6032 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6033 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6034 break;
6035 case ICmpInst::ICMP_ULE:
6036 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6037 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6038 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6039 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6040 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006041 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006042 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006043
6044 // Turn a signed comparison into an unsigned one if both operands
6045 // are known to have the same sign.
6046 if (I.isSignedPredicate() &&
6047 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6048 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6049 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006050 }
6051
6052 // Test if the ICmpInst instruction is used exclusively by a select as
6053 // part of a minimum or maximum operation. If so, refrain from doing
6054 // any other folding. This helps out other analyses which understand
6055 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6056 // and CodeGen. And in this case, at least one of the comparison
6057 // operands has at least one user besides the compare (the select),
6058 // which would often largely negate the benefit of folding anyway.
6059 if (I.hasOneUse())
6060 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6061 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6062 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6063 return 0;
6064
6065 // See if we are doing a comparison between a constant and an instruction that
6066 // can be folded into the comparison.
6067 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006068 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006069 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006070 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006071 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006072 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6073 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006074 }
6075
Chris Lattner01deb9d2007-04-03 17:43:25 +00006076 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006077 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6078 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6079 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006080 case Instruction::GetElementPtr:
6081 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006082 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006083 bool isAllZeros = true;
6084 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6085 if (!isa<Constant>(LHSI->getOperand(i)) ||
6086 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6087 isAllZeros = false;
6088 break;
6089 }
6090 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006091 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00006092 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6093 }
6094 break;
6095
Chris Lattner6970b662005-04-23 15:31:55 +00006096 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006097 // Only fold icmp into the PHI if the phi and fcmp are in the same
6098 // block. If in the same block, we're encouraging jump threading. If
6099 // not, we are just pessimizing the code by making an i1 phi.
6100 if (LHSI->getParent() == I.getParent())
6101 if (Instruction *NV = FoldOpIntoPhi(I))
6102 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006103 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006104 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006105 // If either operand of the select is a constant, we can fold the
6106 // comparison into the select arms, which will cause one to be
6107 // constant folded and the select turned into a bitwise or.
6108 Value *Op1 = 0, *Op2 = 0;
6109 if (LHSI->hasOneUse()) {
6110 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6111 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006112 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6113 // Insert a new ICmp of the other select operand.
6114 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6115 LHSI->getOperand(2), RHSC,
6116 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006117 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6118 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006119 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6120 // Insert a new ICmp of the other select operand.
6121 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6122 LHSI->getOperand(1), RHSC,
6123 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006124 }
6125 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006126
Chris Lattner6970b662005-04-23 15:31:55 +00006127 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006128 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006129 break;
6130 }
Chris Lattner4802d902007-04-06 18:57:34 +00006131 case Instruction::Malloc:
6132 // If we have (malloc != null), and if the malloc has a single use, we
6133 // can assume it is successful and remove the malloc.
6134 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6135 AddToWorkList(LHSI);
6136 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006137 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006138 }
6139 break;
6140 }
Chris Lattner6970b662005-04-23 15:31:55 +00006141 }
6142
Reid Spencere4d87aa2006-12-23 06:05:41 +00006143 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006144 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006145 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006146 return NI;
6147 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006148 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6149 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006150 return NI;
6151
Reid Spencere4d87aa2006-12-23 06:05:41 +00006152 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006153 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6154 // now.
6155 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6156 if (isa<PointerType>(Op0->getType()) &&
6157 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006158 // We keep moving the cast from the left operand over to the right
6159 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006160 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006161
Chris Lattner57d86372007-01-06 01:45:59 +00006162 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6163 // so eliminate it as well.
6164 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6165 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006166
Chris Lattnerde90b762003-11-03 04:25:02 +00006167 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006168 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006169 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006170 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006171 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006172 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006173 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006174 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006175 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006176 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006177 }
Chris Lattner57d86372007-01-06 01:45:59 +00006178 }
6179
6180 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006181 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006182 // This comes up when you have code like
6183 // int X = A < B;
6184 // if (X) ...
6185 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006186 // with a constant or another cast from the same type.
6187 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006188 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006189 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006190 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006191
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006192 // See if it's the same type of instruction on the left and right.
6193 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6194 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006195 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006196 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006197 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006198 default: break;
6199 case Instruction::Add:
6200 case Instruction::Sub:
6201 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006202 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Nick Lewycky4333f492009-01-31 21:30:05 +00006203 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6204 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006205 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6206 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6207 if (CI->getValue().isSignBit()) {
6208 ICmpInst::Predicate Pred = I.isSignedPredicate()
6209 ? I.getUnsignedPredicate()
6210 : I.getSignedPredicate();
6211 return new ICmpInst(Pred, Op0I->getOperand(0),
6212 Op1I->getOperand(0));
6213 }
6214
6215 if (CI->getValue().isMaxSignedValue()) {
6216 ICmpInst::Predicate Pred = I.isSignedPredicate()
6217 ? I.getUnsignedPredicate()
6218 : I.getSignedPredicate();
6219 Pred = I.getSwappedPredicate(Pred);
6220 return new ICmpInst(Pred, Op0I->getOperand(0),
6221 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006222 }
6223 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006224 break;
6225 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006226 if (!I.isEquality())
6227 break;
6228
Nick Lewycky5d52c452008-08-21 05:56:10 +00006229 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6230 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6231 // Mask = -1 >> count-trailing-zeros(Cst).
6232 if (!CI->isZero() && !CI->isOne()) {
6233 const APInt &AP = CI->getValue();
6234 ConstantInt *Mask = ConstantInt::get(
6235 APInt::getLowBitsSet(AP.getBitWidth(),
6236 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006237 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006238 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6239 Mask);
6240 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6241 Mask);
6242 InsertNewInstBefore(And1, I);
6243 InsertNewInstBefore(And2, I);
6244 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006245 }
6246 }
6247 break;
6248 }
6249 }
6250 }
6251 }
6252
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006253 // ~x < ~y --> y < x
6254 { Value *A, *B;
6255 if (match(Op0, m_Not(m_Value(A))) &&
6256 match(Op1, m_Not(m_Value(B))))
6257 return new ICmpInst(I.getPredicate(), B, A);
6258 }
6259
Chris Lattner65b72ba2006-09-18 04:22:48 +00006260 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006261 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006262
6263 // -x == -y --> x == y
6264 if (match(Op0, m_Neg(m_Value(A))) &&
6265 match(Op1, m_Neg(m_Value(B))))
6266 return new ICmpInst(I.getPredicate(), A, B);
6267
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006268 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6269 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6270 Value *OtherVal = A == Op1 ? B : A;
6271 return new ICmpInst(I.getPredicate(), OtherVal,
6272 Constant::getNullValue(A->getType()));
6273 }
6274
6275 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6276 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006277 ConstantInt *C1, *C2;
6278 if (match(B, m_ConstantInt(C1)) &&
6279 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6280 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6281 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6282 return new ICmpInst(I.getPredicate(), A,
6283 InsertNewInstBefore(Xor, I));
6284 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006285
6286 // A^B == A^D -> B == D
6287 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6288 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6289 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6290 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6291 }
6292 }
6293
6294 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6295 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006296 // A == (A^B) -> B == 0
6297 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006298 return new ICmpInst(I.getPredicate(), OtherVal,
6299 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006300 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006301
6302 // (A-B) == A -> B == 0
6303 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6304 return new ICmpInst(I.getPredicate(), B,
6305 Constant::getNullValue(B->getType()));
6306
6307 // A == (A-B) -> B == 0
6308 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006309 return new ICmpInst(I.getPredicate(), B,
6310 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006311
Chris Lattner9c2328e2006-11-14 06:06:06 +00006312 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6313 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6314 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6315 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6316 Value *X = 0, *Y = 0, *Z = 0;
6317
6318 if (A == C) {
6319 X = B; Y = D; Z = A;
6320 } else if (A == D) {
6321 X = B; Y = C; Z = A;
6322 } else if (B == C) {
6323 X = A; Y = D; Z = B;
6324 } else if (B == D) {
6325 X = A; Y = C; Z = B;
6326 }
6327
6328 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006329 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6330 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006331 I.setOperand(0, Op1);
6332 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6333 return &I;
6334 }
6335 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006336 }
Chris Lattner7e708292002-06-25 16:13:24 +00006337 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006338}
6339
Chris Lattner562ef782007-06-20 23:46:26 +00006340
6341/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6342/// and CmpRHS are both known to be integer constants.
6343Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6344 ConstantInt *DivRHS) {
6345 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6346 const APInt &CmpRHSV = CmpRHS->getValue();
6347
6348 // FIXME: If the operand types don't match the type of the divide
6349 // then don't attempt this transform. The code below doesn't have the
6350 // logic to deal with a signed divide and an unsigned compare (and
6351 // vice versa). This is because (x /s C1) <s C2 produces different
6352 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6353 // (x /u C1) <u C2. Simply casting the operands and result won't
6354 // work. :( The if statement below tests that condition and bails
6355 // if it finds it.
6356 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6357 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6358 return 0;
6359 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006360 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006361 if (DivIsSigned && DivRHS->isAllOnesValue())
6362 return 0; // The overflow computation also screws up here
6363 if (DivRHS->isOne())
6364 return 0; // Not worth bothering, and eliminates some funny cases
6365 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006366
6367 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6368 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6369 // C2 (CI). By solving for X we can turn this into a range check
6370 // instead of computing a divide.
6371 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6372
6373 // Determine if the product overflows by seeing if the product is
6374 // not equal to the divide. Make sure we do the same kind of divide
6375 // as in the LHS instruction that we're folding.
6376 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6377 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6378
6379 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006380 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006381
Chris Lattner1dbfd482007-06-21 18:11:19 +00006382 // Figure out the interval that is being checked. For example, a comparison
6383 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6384 // Compute this interval based on the constants involved and the signedness of
6385 // the compare/divide. This computes a half-open interval, keeping track of
6386 // whether either value in the interval overflows. After analysis each
6387 // overflow variable is set to 0 if it's corresponding bound variable is valid
6388 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6389 int LoOverflow = 0, HiOverflow = 0;
6390 ConstantInt *LoBound = 0, *HiBound = 0;
6391
Chris Lattner562ef782007-06-20 23:46:26 +00006392 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006393 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006394 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006395 HiOverflow = LoOverflow = ProdOV;
6396 if (!HiOverflow)
6397 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006398 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006399 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006400 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006401 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6402 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006403 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006404 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6405 HiOverflow = LoOverflow = ProdOV;
6406 if (!HiOverflow)
6407 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006408 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006409 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006410 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006411 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6412 if (!LoOverflow) {
6413 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6414 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6415 true) ? -1 : 0;
6416 }
Chris Lattner562ef782007-06-20 23:46:26 +00006417 }
Dan Gohman76491272008-02-13 22:09:18 +00006418 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006419 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006420 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006421 LoBound = AddOne(DivRHS);
6422 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006423 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6424 HiOverflow = 1; // [INTMIN+1, overflow)
6425 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6426 }
Dan Gohman76491272008-02-13 22:09:18 +00006427 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006428 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnera6321b42008-10-11 22:55:00 +00006429 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006430 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006431 if (!LoOverflow)
Chris Lattnera6321b42008-10-11 22:55:00 +00006432 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006433 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006434 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6435 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006436 if (!HiOverflow)
6437 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006438 }
6439
Chris Lattner1dbfd482007-06-21 18:11:19 +00006440 // Dividing by a negative swaps the condition. LT <-> GT
6441 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006442 }
6443
6444 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006445 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006446 default: assert(0 && "Unhandled icmp opcode!");
6447 case ICmpInst::ICMP_EQ:
6448 if (LoOverflow && HiOverflow)
6449 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6450 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006451 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006452 ICmpInst::ICMP_UGE, X, LoBound);
6453 else if (LoOverflow)
6454 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6455 ICmpInst::ICMP_ULT, X, HiBound);
6456 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006457 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006458 case ICmpInst::ICMP_NE:
6459 if (LoOverflow && HiOverflow)
6460 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6461 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006462 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006463 ICmpInst::ICMP_ULT, X, LoBound);
6464 else if (LoOverflow)
6465 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6466 ICmpInst::ICMP_UGE, X, HiBound);
6467 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006468 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006469 case ICmpInst::ICMP_ULT:
6470 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006471 if (LoOverflow == +1) // Low bound is greater than input range.
6472 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6473 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006474 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006475 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006476 case ICmpInst::ICMP_UGT:
6477 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006478 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006479 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006480 else if (HiOverflow == -1) // High bound less than input range.
6481 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6482 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006483 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6484 else
6485 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6486 }
6487}
6488
6489
Chris Lattner01deb9d2007-04-03 17:43:25 +00006490/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6491///
6492Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6493 Instruction *LHSI,
6494 ConstantInt *RHS) {
6495 const APInt &RHSV = RHS->getValue();
6496
6497 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006498 case Instruction::Trunc:
6499 if (ICI.isEquality() && LHSI->hasOneUse()) {
6500 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6501 // of the high bits truncated out of x are known.
6502 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6503 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6504 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6505 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6506 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6507
6508 // If all the high bits are known, we can do this xform.
6509 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6510 // Pull in the high bits from known-ones set.
6511 APInt NewRHS(RHS->getValue());
6512 NewRHS.zext(SrcBits);
6513 NewRHS |= KnownOne;
6514 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6515 ConstantInt::get(NewRHS));
6516 }
6517 }
6518 break;
6519
Duncan Sands0091bf22007-04-04 06:42:45 +00006520 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006521 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6522 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6523 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006524 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6525 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006526 Value *CompareVal = LHSI->getOperand(0);
6527
6528 // If the sign bit of the XorCST is not set, there is no change to
6529 // the operation, just stop using the Xor.
6530 if (!XorCST->getValue().isNegative()) {
6531 ICI.setOperand(0, CompareVal);
6532 AddToWorkList(LHSI);
6533 return &ICI;
6534 }
6535
6536 // Was the old condition true if the operand is positive?
6537 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6538
6539 // If so, the new one isn't.
6540 isTrueIfPositive ^= true;
6541
6542 if (isTrueIfPositive)
6543 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6544 else
6545 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6546 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006547
6548 if (LHSI->hasOneUse()) {
6549 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6550 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6551 const APInt &SignBit = XorCST->getValue();
6552 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6553 ? ICI.getUnsignedPredicate()
6554 : ICI.getSignedPredicate();
6555 return new ICmpInst(Pred, LHSI->getOperand(0),
6556 ConstantInt::get(RHSV ^ SignBit));
6557 }
6558
6559 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006560 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006561 const APInt &NotSignBit = XorCST->getValue();
6562 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6563 ? ICI.getUnsignedPredicate()
6564 : ICI.getSignedPredicate();
6565 Pred = ICI.getSwappedPredicate(Pred);
6566 return new ICmpInst(Pred, LHSI->getOperand(0),
6567 ConstantInt::get(RHSV ^ NotSignBit));
6568 }
6569 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006570 }
6571 break;
6572 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6573 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6574 LHSI->getOperand(0)->hasOneUse()) {
6575 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6576
6577 // If the LHS is an AND of a truncating cast, we can widen the
6578 // and/compare to be the input width without changing the value
6579 // produced, eliminating a cast.
6580 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6581 // We can do this transformation if either the AND constant does not
6582 // have its sign bit set or if it is an equality comparison.
6583 // Extending a relational comparison when we're checking the sign
6584 // bit would not work.
6585 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006586 (ICI.isEquality() ||
6587 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006588 uint32_t BitWidth =
6589 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6590 APInt NewCST = AndCST->getValue();
6591 NewCST.zext(BitWidth);
6592 APInt NewCI = RHSV;
6593 NewCI.zext(BitWidth);
6594 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006595 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006596 ConstantInt::get(NewCST),LHSI->getName());
6597 InsertNewInstBefore(NewAnd, ICI);
6598 return new ICmpInst(ICI.getPredicate(), NewAnd,
6599 ConstantInt::get(NewCI));
6600 }
6601 }
6602
6603 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6604 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6605 // happens a LOT in code produced by the C front-end, for bitfield
6606 // access.
6607 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6608 if (Shift && !Shift->isShift())
6609 Shift = 0;
6610
6611 ConstantInt *ShAmt;
6612 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6613 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6614 const Type *AndTy = AndCST->getType(); // Type of the and.
6615
6616 // We can fold this as long as we can't shift unknown bits
6617 // into the mask. This can only happen with signed shift
6618 // rights, as they sign-extend.
6619 if (ShAmt) {
6620 bool CanFold = Shift->isLogicalShift();
6621 if (!CanFold) {
6622 // To test for the bad case of the signed shr, see if any
6623 // of the bits shifted in could be tested after the mask.
6624 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6625 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6626
6627 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6628 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6629 AndCST->getValue()) == 0)
6630 CanFold = true;
6631 }
6632
6633 if (CanFold) {
6634 Constant *NewCst;
6635 if (Shift->getOpcode() == Instruction::Shl)
6636 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6637 else
6638 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6639
6640 // Check to see if we are shifting out any of the bits being
6641 // compared.
6642 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6643 // If we shifted bits out, the fold is not going to work out.
6644 // As a special case, check to see if this means that the
6645 // result is always true or false now.
6646 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6647 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6648 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6649 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6650 } else {
6651 ICI.setOperand(1, NewCst);
6652 Constant *NewAndCST;
6653 if (Shift->getOpcode() == Instruction::Shl)
6654 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6655 else
6656 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6657 LHSI->setOperand(1, NewAndCST);
6658 LHSI->setOperand(0, Shift->getOperand(0));
6659 AddToWorkList(Shift); // Shift is dead.
6660 AddUsesToWorkList(ICI);
6661 return &ICI;
6662 }
6663 }
6664 }
6665
6666 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6667 // preferable because it allows the C<<Y expression to be hoisted out
6668 // of a loop if Y is invariant and X is not.
6669 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006670 ICI.isEquality() && !Shift->isArithmeticShift() &&
6671 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006672 // Compute C << Y.
6673 Value *NS;
6674 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006675 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006676 Shift->getOperand(1), "tmp");
6677 } else {
6678 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006679 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006680 Shift->getOperand(1), "tmp");
6681 }
6682 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6683
6684 // Compute X & (C << Y).
6685 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006686 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006687 InsertNewInstBefore(NewAnd, ICI);
6688
6689 ICI.setOperand(0, NewAnd);
6690 return &ICI;
6691 }
6692 }
6693 break;
6694
Chris Lattnera0141b92007-07-15 20:42:37 +00006695 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6696 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6697 if (!ShAmt) break;
6698
6699 uint32_t TypeBits = RHSV.getBitWidth();
6700
6701 // Check that the shift amount is in range. If not, don't perform
6702 // undefined shifts. When the shift is visited it will be
6703 // simplified.
6704 if (ShAmt->uge(TypeBits))
6705 break;
6706
6707 if (ICI.isEquality()) {
6708 // If we are comparing against bits always shifted out, the
6709 // comparison cannot succeed.
6710 Constant *Comp =
6711 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6712 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6713 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6714 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6715 return ReplaceInstUsesWith(ICI, Cst);
6716 }
6717
6718 if (LHSI->hasOneUse()) {
6719 // Otherwise strength reduce the shift into an and.
6720 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6721 Constant *Mask =
6722 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006723
Chris Lattnera0141b92007-07-15 20:42:37 +00006724 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006725 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006726 Mask, LHSI->getName()+".mask");
6727 Value *And = InsertNewInstBefore(AndI, ICI);
6728 return new ICmpInst(ICI.getPredicate(), And,
6729 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006730 }
6731 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006732
6733 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6734 bool TrueIfSigned = false;
6735 if (LHSI->hasOneUse() &&
6736 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6737 // (X << 31) <s 0 --> (X&1) != 0
6738 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6739 (TypeBits-ShAmt->getZExtValue()-1));
6740 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006741 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006742 Mask, LHSI->getName()+".mask");
6743 Value *And = InsertNewInstBefore(AndI, ICI);
6744
6745 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6746 And, Constant::getNullValue(And->getType()));
6747 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006748 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006749 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006750
6751 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006752 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006753 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006754 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006755 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006756
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006757 // Check that the shift amount is in range. If not, don't perform
6758 // undefined shifts. When the shift is visited it will be
6759 // simplified.
6760 uint32_t TypeBits = RHSV.getBitWidth();
6761 if (ShAmt->uge(TypeBits))
6762 break;
6763
6764 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006765
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006766 // If we are comparing against bits always shifted out, the
6767 // comparison cannot succeed.
6768 APInt Comp = RHSV << ShAmtVal;
6769 if (LHSI->getOpcode() == Instruction::LShr)
6770 Comp = Comp.lshr(ShAmtVal);
6771 else
6772 Comp = Comp.ashr(ShAmtVal);
6773
6774 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6775 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6776 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6777 return ReplaceInstUsesWith(ICI, Cst);
6778 }
6779
6780 // Otherwise, check to see if the bits shifted out are known to be zero.
6781 // If so, we can compare against the unshifted value:
6782 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006783 if (LHSI->hasOneUse() &&
6784 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006785 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6786 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6787 ConstantExpr::getShl(RHS, ShAmt));
6788 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006789
Evan Chengf30752c2008-04-23 00:38:06 +00006790 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006791 // Otherwise strength reduce the shift into an and.
6792 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6793 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006794
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006795 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006796 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006797 Mask, LHSI->getName()+".mask");
6798 Value *And = InsertNewInstBefore(AndI, ICI);
6799 return new ICmpInst(ICI.getPredicate(), And,
6800 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006801 }
6802 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006803 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006804
6805 case Instruction::SDiv:
6806 case Instruction::UDiv:
6807 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6808 // Fold this div into the comparison, producing a range check.
6809 // Determine, based on the divide type, what the range is being
6810 // checked. If there is an overflow on the low or high side, remember
6811 // it, otherwise compute the range [low, hi) bounding the new value.
6812 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006813 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6814 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6815 DivRHS))
6816 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006817 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006818
6819 case Instruction::Add:
6820 // Fold: icmp pred (add, X, C1), C2
6821
6822 if (!ICI.isEquality()) {
6823 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6824 if (!LHSC) break;
6825 const APInt &LHSV = LHSC->getValue();
6826
6827 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6828 .subtract(LHSV);
6829
6830 if (ICI.isSignedPredicate()) {
6831 if (CR.getLower().isSignBit()) {
6832 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6833 ConstantInt::get(CR.getUpper()));
6834 } else if (CR.getUpper().isSignBit()) {
6835 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6836 ConstantInt::get(CR.getLower()));
6837 }
6838 } else {
6839 if (CR.getLower().isMinValue()) {
6840 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6841 ConstantInt::get(CR.getUpper()));
6842 } else if (CR.getUpper().isMinValue()) {
6843 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6844 ConstantInt::get(CR.getLower()));
6845 }
6846 }
6847 }
6848 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006849 }
6850
6851 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6852 if (ICI.isEquality()) {
6853 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6854
6855 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6856 // the second operand is a constant, simplify a bit.
6857 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6858 switch (BO->getOpcode()) {
6859 case Instruction::SRem:
6860 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6861 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6862 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6863 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6864 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006865 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006866 BO->getName());
6867 InsertNewInstBefore(NewRem, ICI);
6868 return new ICmpInst(ICI.getPredicate(), NewRem,
6869 Constant::getNullValue(BO->getType()));
6870 }
6871 }
6872 break;
6873 case Instruction::Add:
6874 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6875 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6876 if (BO->hasOneUse())
6877 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6878 Subtract(RHS, BOp1C));
6879 } else if (RHSV == 0) {
6880 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6881 // efficiently invertible, or if the add has just this one use.
6882 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6883
6884 if (Value *NegVal = dyn_castNegVal(BOp1))
6885 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6886 else if (Value *NegVal = dyn_castNegVal(BOp0))
6887 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6888 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006889 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006890 InsertNewInstBefore(Neg, ICI);
6891 Neg->takeName(BO);
6892 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6893 }
6894 }
6895 break;
6896 case Instruction::Xor:
6897 // For the xor case, we can xor two constants together, eliminating
6898 // the explicit xor.
6899 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6900 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6901 ConstantExpr::getXor(RHS, BOC));
6902
6903 // FALLTHROUGH
6904 case Instruction::Sub:
6905 // Replace (([sub|xor] A, B) != 0) with (A != B)
6906 if (RHSV == 0)
6907 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6908 BO->getOperand(1));
6909 break;
6910
6911 case Instruction::Or:
6912 // If bits are being or'd in that are not present in the constant we
6913 // are comparing against, then the comparison could never succeed!
6914 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6915 Constant *NotCI = ConstantExpr::getNot(RHS);
6916 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6917 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6918 isICMP_NE));
6919 }
6920 break;
6921
6922 case Instruction::And:
6923 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6924 // If bits are being compared against that are and'd out, then the
6925 // comparison can never succeed!
6926 if ((RHSV & ~BOC->getValue()) != 0)
6927 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6928 isICMP_NE));
6929
6930 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6931 if (RHS == BOC && RHSV.isPowerOf2())
6932 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6933 ICmpInst::ICMP_NE, LHSI,
6934 Constant::getNullValue(RHS->getType()));
6935
6936 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006937 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006938 Value *X = BO->getOperand(0);
6939 Constant *Zero = Constant::getNullValue(X->getType());
6940 ICmpInst::Predicate pred = isICMP_NE ?
6941 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6942 return new ICmpInst(pred, X, Zero);
6943 }
6944
6945 // ((X & ~7) == 0) --> X < 8
6946 if (RHSV == 0 && isHighOnes(BOC)) {
6947 Value *X = BO->getOperand(0);
6948 Constant *NegX = ConstantExpr::getNeg(BOC);
6949 ICmpInst::Predicate pred = isICMP_NE ?
6950 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6951 return new ICmpInst(pred, X, NegX);
6952 }
6953 }
6954 default: break;
6955 }
6956 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6957 // Handle icmp {eq|ne} <intrinsic>, intcst.
6958 if (II->getIntrinsicID() == Intrinsic::bswap) {
6959 AddToWorkList(II);
6960 ICI.setOperand(0, II->getOperand(1));
6961 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6962 return &ICI;
6963 }
6964 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006965 }
6966 return 0;
6967}
6968
6969/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6970/// We only handle extending casts so far.
6971///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006972Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6973 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006974 Value *LHSCIOp = LHSCI->getOperand(0);
6975 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006976 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006977 Value *RHSCIOp;
6978
Chris Lattner8c756c12007-05-05 22:41:33 +00006979 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6980 // integer type is the same size as the pointer type.
6981 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6982 getTargetData().getPointerSizeInBits() ==
6983 cast<IntegerType>(DestTy)->getBitWidth()) {
6984 Value *RHSOp = 0;
6985 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006986 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006987 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6988 RHSOp = RHSC->getOperand(0);
6989 // If the pointer types don't match, insert a bitcast.
6990 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006991 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006992 }
6993
6994 if (RHSOp)
6995 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6996 }
6997
6998 // The code below only handles extension cast instructions, so far.
6999 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007000 if (LHSCI->getOpcode() != Instruction::ZExt &&
7001 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007002 return 0;
7003
Reid Spencere4d87aa2006-12-23 06:05:41 +00007004 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7005 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007006
Reid Spencere4d87aa2006-12-23 06:05:41 +00007007 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007008 // Not an extension from the same type?
7009 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007010 if (RHSCIOp->getType() != LHSCIOp->getType())
7011 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007012
Nick Lewycky4189a532008-01-28 03:48:02 +00007013 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007014 // and the other is a zext), then we can't handle this.
7015 if (CI->getOpcode() != LHSCI->getOpcode())
7016 return 0;
7017
Nick Lewycky4189a532008-01-28 03:48:02 +00007018 // Deal with equality cases early.
7019 if (ICI.isEquality())
7020 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7021
7022 // A signed comparison of sign extended values simplifies into a
7023 // signed comparison.
7024 if (isSignedCmp && isSignedExt)
7025 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7026
7027 // The other three cases all fold into an unsigned comparison.
7028 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007029 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007030
Reid Spencere4d87aa2006-12-23 06:05:41 +00007031 // If we aren't dealing with a constant on the RHS, exit early
7032 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7033 if (!CI)
7034 return 0;
7035
7036 // Compute the constant that would happen if we truncated to SrcTy then
7037 // reextended to DestTy.
7038 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7039 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7040
7041 // If the re-extended constant didn't change...
7042 if (Res2 == CI) {
7043 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7044 // For example, we might have:
7045 // %A = sext short %X to uint
7046 // %B = icmp ugt uint %A, 1330
7047 // It is incorrect to transform this into
7048 // %B = icmp ugt short %X, 1330
7049 // because %A may have negative value.
7050 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007051 // However, we allow this when the compare is EQ/NE, because they are
7052 // signless.
7053 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00007054 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007055 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007056 }
7057
7058 // The re-extended constant changed so the constant cannot be represented
7059 // in the shorter type. Consequently, we cannot emit a simple comparison.
7060
7061 // First, handle some easy cases. We know the result cannot be equal at this
7062 // point so handle the ICI.isEquality() cases
7063 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007064 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007065 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007066 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007067
7068 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7069 // should have been folded away previously and not enter in here.
7070 Value *Result;
7071 if (isSignedCmp) {
7072 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007073 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007074 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007075 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007076 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007077 } else {
7078 // We're performing an unsigned comparison.
7079 if (isSignedExt) {
7080 // We're performing an unsigned comp with a sign extended value.
7081 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007082 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007083 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7084 NegOne, ICI.getName()), ICI);
7085 } else {
7086 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007087 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007088 }
7089 }
7090
7091 // Finally, return the value computed.
7092 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007093 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007094 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007095
7096 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7097 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7098 "ICmp should be folded!");
7099 if (Constant *CI = dyn_cast<Constant>(Result))
7100 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7101 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007102}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007103
Reid Spencer832254e2007-02-02 02:16:23 +00007104Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7105 return commonShiftTransforms(I);
7106}
7107
7108Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7109 return commonShiftTransforms(I);
7110}
7111
7112Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007113 if (Instruction *R = commonShiftTransforms(I))
7114 return R;
7115
7116 Value *Op0 = I.getOperand(0);
7117
7118 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7119 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7120 if (CSI->isAllOnesValue())
7121 return ReplaceInstUsesWith(I, CSI);
7122
7123 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb44b3662009-03-18 16:32:19 +00007124 if (!isa<VectorType>(I.getType())) {
7125 if (MaskedValueIsZero(Op0,
Chris Lattner348f6652007-12-06 01:59:46 +00007126 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Chris Lattnerb44b3662009-03-18 16:32:19 +00007127 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Dan Gohman0001e562009-02-24 02:00:40 +00007128
Chris Lattnerb44b3662009-03-18 16:32:19 +00007129 // Arithmetic shifting an all-sign-bit value is a no-op.
7130 unsigned NumSignBits = ComputeNumSignBits(Op0);
7131 if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7132 return ReplaceInstUsesWith(I, Op0);
7133 }
Dan Gohman0001e562009-02-24 02:00:40 +00007134
Chris Lattner348f6652007-12-06 01:59:46 +00007135 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007136}
7137
7138Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7139 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007140 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007141
7142 // shl X, 0 == X and shr X, 0 == X
7143 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00007144 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00007145 Op0 == Constant::getNullValue(Op0->getType()))
7146 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007147
Reid Spencere4d87aa2006-12-23 06:05:41 +00007148 if (isa<UndefValue>(Op0)) {
7149 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007150 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007151 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007152 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7153 }
7154 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007155 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7156 return ReplaceInstUsesWith(I, Op0);
7157 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007158 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007159 }
7160
Dan Gohman9004c8a2009-05-21 02:28:33 +00007161 // See if we can fold away this shift.
7162 if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
7163 return &I;
7164
Chris Lattner2eefe512004-04-09 19:05:30 +00007165 // Try to fold constant and into select arguments.
7166 if (isa<Constant>(Op0))
7167 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007168 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007169 return R;
7170
Reid Spencerb83eb642006-10-20 07:07:24 +00007171 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007172 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7173 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007174 return 0;
7175}
7176
Reid Spencerb83eb642006-10-20 07:07:24 +00007177Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007178 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007179 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007180
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007181 // See if we can simplify any instructions used by the instruction whose sole
7182 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00007183 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007184
Chris Lattner4d5542c2006-01-06 07:12:35 +00007185 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7186 // of a signed value.
7187 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007188 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007189 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007190 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7191 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007192 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007193 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007194 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007195 }
7196
7197 // ((X*C1) << C2) == (X * (C1 << C2))
7198 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7199 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7200 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007201 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007202 ConstantExpr::getShl(BOOp, Op1));
7203
7204 // Try to fold constant and into select arguments.
7205 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7206 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7207 return R;
7208 if (isa<PHINode>(Op0))
7209 if (Instruction *NV = FoldOpIntoPhi(I))
7210 return NV;
7211
Chris Lattner8999dd32007-12-22 09:07:47 +00007212 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7213 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7214 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7215 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7216 // place. Don't try to do this transformation in this case. Also, we
7217 // require that the input operand is a shift-by-constant so that we have
7218 // confidence that the shifts will get folded together. We could do this
7219 // xform in more cases, but it is unlikely to be profitable.
7220 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7221 isa<ConstantInt>(TrOp->getOperand(1))) {
7222 // Okay, we'll do this xform. Make the shift of shift.
7223 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007224 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007225 I.getName());
7226 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7227
7228 // For logical shifts, the truncation has the effect of making the high
7229 // part of the register be zeros. Emulate this by inserting an AND to
7230 // clear the top bits as needed. This 'and' will usually be zapped by
7231 // other xforms later if dead.
7232 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7233 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7234 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7235
7236 // The mask we constructed says what the trunc would do if occurring
7237 // between the shifts. We want to know the effect *after* the second
7238 // shift. We know that it is a logical shift by a constant, so adjust the
7239 // mask as appropriate.
7240 if (I.getOpcode() == Instruction::Shl)
7241 MaskV <<= Op1->getZExtValue();
7242 else {
7243 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7244 MaskV = MaskV.lshr(Op1->getZExtValue());
7245 }
7246
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007247 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007248 TI->getName());
7249 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7250
7251 // Return the value truncated to the interesting size.
7252 return new TruncInst(And, I.getType());
7253 }
7254 }
7255
Chris Lattner4d5542c2006-01-06 07:12:35 +00007256 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007257 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7258 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7259 Value *V1, *V2;
7260 ConstantInt *CC;
7261 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007262 default: break;
7263 case Instruction::Add:
7264 case Instruction::And:
7265 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007266 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007267 // These operators commute.
7268 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007269 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007270 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007271 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007272 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007273 Op0BO->getName());
7274 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007275 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007276 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007277 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007278 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007279 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007280 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007281 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007282 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007283
Chris Lattner150f12a2005-09-18 06:30:59 +00007284 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007285 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007286 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007287 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007288 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7289 m_ConstantInt(CC))) &&
7290 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007291 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007292 Op0BO->getOperand(0), Op1,
7293 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007294 InsertNewInstBefore(YS, I); // (Y << C)
7295 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007296 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007297 V1->getName()+".mask");
7298 InsertNewInstBefore(XM, I); // X & (CC << C)
7299
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007300 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007301 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007302 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007303
Reid Spencera07cb7d2007-02-02 14:41:37 +00007304 // FALL THROUGH.
7305 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007306 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007307 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007308 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007309 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007310 Op0BO->getOperand(1), Op1,
7311 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007312 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007313 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007314 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007315 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007316 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007317 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007318 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007319 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007320 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007321
Chris Lattner13d4ab42006-05-31 21:14:00 +00007322 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007323 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7324 match(Op0BO->getOperand(0),
7325 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007326 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007327 cast<BinaryOperator>(Op0BO->getOperand(0))
7328 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007329 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007330 Op0BO->getOperand(1), Op1,
7331 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007332 InsertNewInstBefore(YS, I); // (Y << C)
7333 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007334 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007335 V1->getName()+".mask");
7336 InsertNewInstBefore(XM, I); // X & (CC << C)
7337
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007338 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007339 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007340
Chris Lattner11021cb2005-09-18 05:12:10 +00007341 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007342 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007343 }
7344
7345
7346 // If the operand is an bitwise operator with a constant RHS, and the
7347 // shift is the only use, we can pull it out of the shift.
7348 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7349 bool isValid = true; // Valid only for And, Or, Xor
7350 bool highBitSet = false; // Transform if high bit of constant set?
7351
7352 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007353 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007354 case Instruction::Add:
7355 isValid = isLeftShift;
7356 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007357 case Instruction::Or:
7358 case Instruction::Xor:
7359 highBitSet = false;
7360 break;
7361 case Instruction::And:
7362 highBitSet = true;
7363 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007364 }
7365
7366 // If this is a signed shift right, and the high bit is modified
7367 // by the logical operation, do not perform the transformation.
7368 // The highBitSet boolean indicates the value of the high bit of
7369 // the constant which would cause it to be modified for this
7370 // operation.
7371 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007372 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007373 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007374
7375 if (isValid) {
7376 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7377
7378 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007379 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007380 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007381 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007382
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007383 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007384 NewRHS);
7385 }
7386 }
7387 }
7388 }
7389
Chris Lattnerad0124c2006-01-06 07:52:12 +00007390 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007391 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7392 if (ShiftOp && !ShiftOp->isShift())
7393 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007394
Reid Spencerb83eb642006-10-20 07:07:24 +00007395 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007396 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007397 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7398 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007399 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7400 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7401 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007402
Zhou Sheng4351c642007-04-02 08:20:41 +00007403 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007404
7405 const IntegerType *Ty = cast<IntegerType>(I.getType());
7406
7407 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007408 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007409 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7410 // saturates.
7411 if (AmtSum >= TypeBits) {
7412 if (I.getOpcode() != Instruction::AShr)
7413 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7414 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7415 }
7416
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007417 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007418 ConstantInt::get(Ty, AmtSum));
7419 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7420 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007421 if (AmtSum >= TypeBits)
7422 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7423
Chris Lattnerb87056f2007-02-05 00:57:54 +00007424 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007425 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007426 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7427 I.getOpcode() == Instruction::LShr) {
7428 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007429 if (AmtSum >= TypeBits)
7430 AmtSum = TypeBits-1;
7431
Chris Lattnerb87056f2007-02-05 00:57:54 +00007432 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007433 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007434 InsertNewInstBefore(Shift, I);
7435
Zhou Shenge9e03f62007-03-28 15:02:20 +00007436 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007437 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007438 }
7439
Chris Lattnerb87056f2007-02-05 00:57:54 +00007440 // Okay, if we get here, one shift must be left, and the other shift must be
7441 // right. See if the amounts are equal.
7442 if (ShiftAmt1 == ShiftAmt2) {
7443 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7444 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007445 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007446 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007447 }
7448 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7449 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007450 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007451 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007452 }
7453 // We can simplify ((X << C) >>s C) into a trunc + sext.
7454 // NOTE: we could do this for any C, but that would make 'unusual' integer
7455 // types. For now, just stick to ones well-supported by the code
7456 // generators.
7457 const Type *SExtType = 0;
7458 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007459 case 1 :
7460 case 8 :
7461 case 16 :
7462 case 32 :
7463 case 64 :
7464 case 128:
7465 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7466 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007467 default: break;
7468 }
7469 if (SExtType) {
7470 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7471 InsertNewInstBefore(NewTrunc, I);
7472 return new SExtInst(NewTrunc, Ty);
7473 }
7474 // Otherwise, we can't handle it yet.
7475 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007476 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007477
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007478 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007479 if (I.getOpcode() == Instruction::Shl) {
7480 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7481 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007482 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007483 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007484 InsertNewInstBefore(Shift, I);
7485
Reid Spencer55702aa2007-03-25 21:11:44 +00007486 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007487 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007488 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007489
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007490 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007491 if (I.getOpcode() == Instruction::LShr) {
7492 assert(ShiftOp->getOpcode() == Instruction::Shl);
7493 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007494 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007495 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007496
Reid Spencerd5e30f02007-03-26 17:18:58 +00007497 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007498 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007499 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007500
7501 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7502 } else {
7503 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007504 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007505
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007506 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007507 if (I.getOpcode() == Instruction::Shl) {
7508 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7509 ShiftOp->getOpcode() == Instruction::AShr);
7510 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007511 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007512 ConstantInt::get(Ty, ShiftDiff));
7513 InsertNewInstBefore(Shift, I);
7514
Reid Spencer55702aa2007-03-25 21:11:44 +00007515 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007516 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007517 }
7518
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007519 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007520 if (I.getOpcode() == Instruction::LShr) {
7521 assert(ShiftOp->getOpcode() == Instruction::Shl);
7522 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007523 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007524 InsertNewInstBefore(Shift, I);
7525
Reid Spencer68d27cf2007-03-26 23:45:51 +00007526 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007527 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007528 }
7529
7530 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007531 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007532 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007533 return 0;
7534}
7535
Chris Lattnera1be5662002-05-02 17:06:02 +00007536
Chris Lattnercfd65102005-10-29 04:36:15 +00007537/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7538/// expression. If so, decompose it, returning some value X, such that Val is
7539/// X*Scale+Offset.
7540///
7541static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007542 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007543 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007544 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007545 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007546 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007547 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007548 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7549 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7550 if (I->getOpcode() == Instruction::Shl) {
7551 // This is a value scaled by '1 << the shift amt'.
7552 Scale = 1U << RHS->getZExtValue();
7553 Offset = 0;
7554 return I->getOperand(0);
7555 } else if (I->getOpcode() == Instruction::Mul) {
7556 // This value is scaled by 'RHS'.
7557 Scale = RHS->getZExtValue();
7558 Offset = 0;
7559 return I->getOperand(0);
7560 } else if (I->getOpcode() == Instruction::Add) {
7561 // We have X+C. Check to see if we really have (X*C2)+C1,
7562 // where C1 is divisible by C2.
7563 unsigned SubScale;
7564 Value *SubVal =
7565 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7566 Offset += RHS->getZExtValue();
7567 Scale = SubScale;
7568 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007569 }
7570 }
7571 }
7572
7573 // Otherwise, we can't look past this.
7574 Scale = 1;
7575 Offset = 0;
7576 return Val;
7577}
7578
7579
Chris Lattnerb3f83972005-10-24 06:03:58 +00007580/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7581/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007582Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007583 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007584 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007585
Chris Lattnerb53c2382005-10-24 06:22:12 +00007586 // Remove any uses of AI that are dead.
7587 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007588
Chris Lattnerb53c2382005-10-24 06:22:12 +00007589 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7590 Instruction *User = cast<Instruction>(*UI++);
7591 if (isInstructionTriviallyDead(User)) {
7592 while (UI != E && *UI == User)
7593 ++UI; // If this instruction uses AI more than once, don't break UI.
7594
Chris Lattnerb53c2382005-10-24 06:22:12 +00007595 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007596 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007597 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007598 }
7599 }
7600
Chris Lattnerb3f83972005-10-24 06:03:58 +00007601 // Get the type really allocated and the type casted to.
7602 const Type *AllocElTy = AI.getAllocatedType();
7603 const Type *CastElTy = PTy->getElementType();
7604 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007605
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007606 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7607 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007608 if (CastElTyAlign < AllocElTyAlign) return 0;
7609
Chris Lattner39387a52005-10-24 06:35:18 +00007610 // If the allocation has multiple uses, only promote it if we are strictly
7611 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007612 // same, we open the door to infinite loops of various kinds. (A reference
7613 // from a dbg.declare doesn't count as a use for this purpose.)
7614 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7615 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007616
Duncan Sands777d2302009-05-09 07:06:46 +00007617 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7618 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007619 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007620
Chris Lattner455fcc82005-10-29 03:19:53 +00007621 // See if we can satisfy the modulus by pulling a scale out of the array
7622 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007623 unsigned ArraySizeScale;
7624 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007625 Value *NumElements = // See if the array size is a decomposable linear expr.
7626 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7627
Chris Lattner455fcc82005-10-29 03:19:53 +00007628 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7629 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007630 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7631 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007632
Chris Lattner455fcc82005-10-29 03:19:53 +00007633 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7634 Value *Amt = 0;
7635 if (Scale == 1) {
7636 Amt = NumElements;
7637 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007638 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007639 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7640 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007641 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007642 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007643 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007644 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007645 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007646 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007647 }
7648
Jeff Cohen86796be2007-04-04 16:58:57 +00007649 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7650 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007651 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007652 Amt = InsertNewInstBefore(Tmp, AI);
7653 }
7654
Chris Lattnerb3f83972005-10-24 06:03:58 +00007655 AllocationInst *New;
7656 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007657 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007658 else
Chris Lattner6934a042007-02-11 01:23:03 +00007659 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007660 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007661 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007662
Dale Johannesena0a66372009-03-05 00:39:02 +00007663 // If the allocation has one real use plus a dbg.declare, just remove the
7664 // declare.
7665 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7666 EraseInstFromFunction(*DI);
7667 }
7668 // If the allocation has multiple real uses, insert a cast and change all
7669 // things that used it to use the new cast. This will also hack on CI, but it
7670 // will die soon.
7671 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007672 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007673 // New is the allocation instruction, pointer typed. AI is the original
7674 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7675 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007676 InsertNewInstBefore(NewCast, AI);
7677 AI.replaceAllUsesWith(NewCast);
7678 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007679 return ReplaceInstUsesWith(CI, New);
7680}
7681
Chris Lattner70074e02006-05-13 02:06:03 +00007682/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007683/// and return it as type Ty without inserting any new casts and without
7684/// changing the computed value. This is used by code that tries to decide
7685/// whether promoting or shrinking integer operations to wider or smaller types
7686/// will allow us to eliminate a truncate or extend.
7687///
7688/// This is a truncation operation if Ty is smaller than V->getType(), or an
7689/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007690///
7691/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7692/// should return true if trunc(V) can be computed by computing V in the smaller
7693/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7694/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7695/// efficiently truncated.
7696///
7697/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7698/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7699/// the final result.
Evan Cheng4e56ab22009-01-16 02:11:43 +00007700bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7701 unsigned CastOpc,
7702 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007703 // We can always evaluate constants in another type.
7704 if (isa<ConstantInt>(V))
7705 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007706
7707 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007708 if (!I) return false;
7709
7710 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007711
Chris Lattner951626b2007-08-02 06:11:14 +00007712 // If this is an extension or truncate, we can often eliminate it.
7713 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7714 // If this is a cast from the destination type, we can trivially eliminate
7715 // it, and this will remove a cast overall.
7716 if (I->getOperand(0)->getType() == Ty) {
7717 // If the first operand is itself a cast, and is eliminable, do not count
7718 // this as an eliminable cast. We would prefer to eliminate those two
7719 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007720 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007721 ++NumCastsRemoved;
7722 return true;
7723 }
7724 }
7725
7726 // We can't extend or shrink something that has multiple uses: doing so would
7727 // require duplicating the instruction in general, which isn't profitable.
7728 if (!I->hasOneUse()) return false;
7729
Evan Chengf35fd542009-01-15 17:01:23 +00007730 unsigned Opc = I->getOpcode();
7731 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007732 case Instruction::Add:
7733 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007734 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007735 case Instruction::And:
7736 case Instruction::Or:
7737 case Instruction::Xor:
7738 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007739 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007740 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007741 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007742 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007743
Chris Lattner46b96052006-11-29 07:18:39 +00007744 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007745 // If we are truncating the result of this SHL, and if it's a shift of a
7746 // constant amount, we can always perform a SHL in a smaller type.
7747 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007748 uint32_t BitWidth = Ty->getBitWidth();
7749 if (BitWidth < OrigTy->getBitWidth() &&
7750 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007751 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007752 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007753 }
7754 break;
7755 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007756 // If this is a truncate of a logical shr, we can truncate it to a smaller
7757 // lshr iff we know that the bits we would otherwise be shifting in are
7758 // already zeros.
7759 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007760 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7761 uint32_t BitWidth = Ty->getBitWidth();
7762 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007763 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007764 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7765 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007766 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007767 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007768 }
7769 }
Chris Lattner46b96052006-11-29 07:18:39 +00007770 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007771 case Instruction::ZExt:
7772 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007773 case Instruction::Trunc:
7774 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007775 // can safely replace it. Note that replacing it does not reduce the number
7776 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007777 if (Opc == CastOpc)
7778 return true;
7779
7780 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007781 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007782 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007783 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007784 case Instruction::Select: {
7785 SelectInst *SI = cast<SelectInst>(I);
7786 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007787 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007788 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007789 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007790 }
Chris Lattner8114b712008-06-18 04:00:49 +00007791 case Instruction::PHI: {
7792 // We can change a phi if we can change all operands.
7793 PHINode *PN = cast<PHINode>(I);
7794 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7795 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007796 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007797 return false;
7798 return true;
7799 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007800 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007801 // TODO: Can handle more cases here.
7802 break;
7803 }
7804
7805 return false;
7806}
7807
7808/// EvaluateInDifferentType - Given an expression that
7809/// CanEvaluateInDifferentType returns true for, actually insert the code to
7810/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007811Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007812 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007813 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007814 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007815
7816 // Otherwise, it must be an instruction.
7817 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007818 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007819 unsigned Opc = I->getOpcode();
7820 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007821 case Instruction::Add:
7822 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007823 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007824 case Instruction::And:
7825 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007826 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007827 case Instruction::AShr:
7828 case Instruction::LShr:
7829 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007830 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007831 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007832 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007833 break;
7834 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007835 case Instruction::Trunc:
7836 case Instruction::ZExt:
7837 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007838 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007839 // just return the source. There's no need to insert it because it is not
7840 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007841 if (I->getOperand(0)->getType() == Ty)
7842 return I->getOperand(0);
7843
Chris Lattner8114b712008-06-18 04:00:49 +00007844 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007845 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007846 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007847 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007848 case Instruction::Select: {
7849 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7850 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7851 Res = SelectInst::Create(I->getOperand(0), True, False);
7852 break;
7853 }
Chris Lattner8114b712008-06-18 04:00:49 +00007854 case Instruction::PHI: {
7855 PHINode *OPN = cast<PHINode>(I);
7856 PHINode *NPN = PHINode::Create(Ty);
7857 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7858 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7859 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7860 }
7861 Res = NPN;
7862 break;
7863 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007864 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007865 // TODO: Can handle more cases here.
7866 assert(0 && "Unreachable!");
7867 break;
7868 }
7869
Chris Lattner8114b712008-06-18 04:00:49 +00007870 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007871 return InsertNewInstBefore(Res, *I);
7872}
7873
Reid Spencer3da59db2006-11-27 01:05:10 +00007874/// @brief Implement the transforms common to all CastInst visitors.
7875Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007876 Value *Src = CI.getOperand(0);
7877
Dan Gohman23d9d272007-05-11 21:10:54 +00007878 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007879 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007880 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007881 if (Instruction::CastOps opc =
7882 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7883 // The first cast (CSrc) is eliminable so we need to fix up or replace
7884 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007885 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007886 }
7887 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007888
Reid Spencer3da59db2006-11-27 01:05:10 +00007889 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007890 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7891 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7892 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007893
7894 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007895 if (isa<PHINode>(Src))
7896 if (Instruction *NV = FoldOpIntoPhi(CI))
7897 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007898
Reid Spencer3da59db2006-11-27 01:05:10 +00007899 return 0;
7900}
7901
Chris Lattner46cd5a12009-01-09 05:44:56 +00007902/// FindElementAtOffset - Given a type and a constant offset, determine whether
7903/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00007904/// the specified offset. If so, fill them into NewIndices and return the
7905/// resultant element type, otherwise return null.
7906static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7907 SmallVectorImpl<Value*> &NewIndices,
7908 const TargetData *TD) {
7909 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007910
7911 // Start with the index over the outer type. Note that the type size
7912 // might be zero (even if the offset isn't zero) if the indexed type
7913 // is something like [0 x {int, int}]
7914 const Type *IntPtrTy = TD->getIntPtrType();
7915 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00007916 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00007917 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00007918 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007919
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007920 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00007921 if (Offset < 0) {
7922 --FirstIdx;
7923 Offset += TySize;
7924 assert(Offset >= 0);
7925 }
7926 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7927 }
7928
7929 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7930
7931 // Index into the types. If we fail, set OrigBase to null.
7932 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007933 // Indexing into tail padding between struct/array elements.
7934 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00007935 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007936
Chris Lattner46cd5a12009-01-09 05:44:56 +00007937 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7938 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007939 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7940 "Offset must stay within the indexed type");
7941
Chris Lattner46cd5a12009-01-09 05:44:56 +00007942 unsigned Elt = SL->getElementContainingOffset(Offset);
7943 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7944
7945 Offset -= SL->getElementOffset(Elt);
7946 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00007947 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00007948 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007949 assert(EltSize && "Cannot index into a zero-sized array");
7950 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7951 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00007952 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007953 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007954 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00007955 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007956 }
7957 }
7958
Chris Lattner3914f722009-01-24 01:00:13 +00007959 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007960}
7961
Chris Lattnerd3e28342007-04-27 17:44:50 +00007962/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7963Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7964 Value *Src = CI.getOperand(0);
7965
Chris Lattnerd3e28342007-04-27 17:44:50 +00007966 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007967 // If casting the result of a getelementptr instruction with no offset, turn
7968 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007969 if (GEP->hasAllZeroIndices()) {
7970 // Changing the cast operand is usually not a good idea but it is safe
7971 // here because the pointer operand is being replaced with another
7972 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007973 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007974 CI.setOperand(0, GEP->getOperand(0));
7975 return &CI;
7976 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007977
7978 // If the GEP has a single use, and the base pointer is a bitcast, and the
7979 // GEP computes a constant offset, see if we can convert these three
7980 // instructions into fewer. This typically happens with unions and other
7981 // non-type-safe code.
7982 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7983 if (GEP->hasAllConstantIndices()) {
7984 // We are guaranteed to get a constant from EmitGEPOffset.
7985 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7986 int64_t Offset = OffsetV->getSExtValue();
7987
7988 // Get the base pointer input of the bitcast, and the type it points to.
7989 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7990 const Type *GEPIdxTy =
7991 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007992 SmallVector<Value*, 8> NewIndices;
7993 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7994 // If we were able to index down into an element, create the GEP
7995 // and bitcast the result. This eliminates one bitcast, potentially
7996 // two.
7997 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7998 NewIndices.begin(),
7999 NewIndices.end(), "");
8000 InsertNewInstBefore(NGEP, CI);
8001 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008002
Chris Lattner46cd5a12009-01-09 05:44:56 +00008003 if (isa<BitCastInst>(CI))
8004 return new BitCastInst(NGEP, CI.getType());
8005 assert(isa<PtrToIntInst>(CI));
8006 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008007 }
8008 }
8009 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008010 }
8011
8012 return commonCastTransforms(CI);
8013}
8014
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008015/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8016/// type like i42. We don't want to introduce operations on random non-legal
8017/// integer types where they don't already exist in the code. In the future,
8018/// we should consider making this based off target-data, so that 32-bit targets
8019/// won't get i64 operations etc.
8020static bool isSafeIntegerType(const Type *Ty) {
8021 switch (Ty->getPrimitiveSizeInBits()) {
8022 case 8:
8023 case 16:
8024 case 32:
8025 case 64:
8026 return true;
8027 default:
8028 return false;
8029 }
8030}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008031
Chris Lattnerc739cd62007-03-03 05:27:34 +00008032/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8033/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00008034/// cases.
8035/// @brief Implement the transforms common to CastInst with integer operands
8036Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8037 if (Instruction *Result = commonCastTransforms(CI))
8038 return Result;
8039
8040 Value *Src = CI.getOperand(0);
8041 const Type *SrcTy = Src->getType();
8042 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00008043 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
8044 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008045
Reid Spencer3da59db2006-11-27 01:05:10 +00008046 // See if we can simplify any instructions used by the LHS whose sole
8047 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008048 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008049 return &CI;
8050
8051 // If the source isn't an instruction or has more than one use then we
8052 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008053 Instruction *SrcI = dyn_cast<Instruction>(Src);
8054 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008055 return 0;
8056
Chris Lattnerc739cd62007-03-03 05:27:34 +00008057 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008058 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008059 if (!isa<BitCastInst>(CI) &&
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008060 // Only do this if the dest type is a simple type, don't convert the
8061 // expression tree to something weird like i93 unless the source is also
8062 // strange.
8063 (isSafeIntegerType(DestTy) || !isSafeIntegerType(SrcI->getType())) &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008064 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Evan Cheng4e56ab22009-01-16 02:11:43 +00008065 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008066 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008067 // eliminates the cast, so it is always a win. If this is a zero-extension,
8068 // we need to do an AND to maintain the clear top-part of the computation,
8069 // so we require that the input have eliminated at least one cast. If this
8070 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008071 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008072 bool DoXForm = false;
8073 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008074 switch (CI.getOpcode()) {
8075 default:
8076 // All the others use floating point so we shouldn't actually
8077 // get here because of the check above.
8078 assert(0 && "Unknown cast type");
8079 case Instruction::Trunc:
8080 DoXForm = true;
8081 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008082 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008083 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008084 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008085 // If it's unnecessary to issue an AND to clear the high bits, it's
8086 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008087 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008088 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8089 if (MaskedValueIsZero(TryRes, Mask))
8090 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008091
8092 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008093 if (TryI->use_empty())
8094 EraseInstFromFunction(*TryI);
8095 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008096 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008097 }
Evan Chengf35fd542009-01-15 17:01:23 +00008098 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008099 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008100 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008101 // If we do not have to emit the truncate + sext pair, then it's always
8102 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008103 //
8104 // It's not safe to eliminate the trunc + sext pair if one of the
8105 // eliminated cast is a truncate. e.g.
8106 // t2 = trunc i32 t1 to i16
8107 // t3 = sext i16 t2 to i32
8108 // !=
8109 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008110 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008111 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8112 if (NumSignBits > (DestBitSize - SrcBitSize))
8113 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008114
8115 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008116 if (TryI->use_empty())
8117 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008118 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008119 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008120 }
Evan Chengf35fd542009-01-15 17:01:23 +00008121 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008122
8123 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008124 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8125 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008126 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8127 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008128 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008129 // Just replace this cast with the result.
8130 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008131
Reid Spencer3da59db2006-11-27 01:05:10 +00008132 assert(Res->getType() == DestTy);
8133 switch (CI.getOpcode()) {
8134 default: assert(0 && "Unknown cast type!");
8135 case Instruction::Trunc:
8136 case Instruction::BitCast:
8137 // Just replace this cast with the result.
8138 return ReplaceInstUsesWith(CI, Res);
8139 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008140 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008141
8142 // If the high bits are already zero, just replace this cast with the
8143 // result.
8144 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8145 if (MaskedValueIsZero(Res, Mask))
8146 return ReplaceInstUsesWith(CI, Res);
8147
8148 // We need to emit an AND to clear the high bits.
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008149 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8150 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008151 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008152 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008153 case Instruction::SExt: {
8154 // If the high bits are already filled with sign bit, just replace this
8155 // cast with the result.
8156 unsigned NumSignBits = ComputeNumSignBits(Res);
8157 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008158 return ReplaceInstUsesWith(CI, Res);
8159
Reid Spencer3da59db2006-11-27 01:05:10 +00008160 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008161 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008162 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8163 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008164 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008165 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008166 }
8167 }
8168
8169 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8170 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8171
8172 switch (SrcI->getOpcode()) {
8173 case Instruction::Add:
8174 case Instruction::Mul:
8175 case Instruction::And:
8176 case Instruction::Or:
8177 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008178 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00008179 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8180 // Don't insert two casts if they cannot be eliminated. We allow
8181 // two casts to be inserted if the sizes are the same. This could
8182 // only be converting signedness, which is a noop.
8183 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008184 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8185 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00008186 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008187 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8188 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008189 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008190 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008191 }
8192 }
8193
8194 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8195 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8196 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008197 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008198 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008199 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008200 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008201 }
8202 break;
8203 case Instruction::SDiv:
8204 case Instruction::UDiv:
8205 case Instruction::SRem:
8206 case Instruction::URem:
8207 // If we are just changing the sign, rewrite.
8208 if (DestBitSize == SrcBitSize) {
8209 // Don't insert two casts if they cannot be eliminated. We allow
8210 // two casts to be inserted if the sizes are the same. This could
8211 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008212 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8213 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008214 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8215 Op0, DestTy, *SrcI);
8216 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8217 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008218 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00008219 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8220 }
8221 }
8222 break;
8223
8224 case Instruction::Shl:
8225 // Allow changing the sign of the source operand. Do not allow
8226 // changing the size of the shift, UNLESS the shift amount is a
8227 // constant. We must not change variable sized shifts to a smaller
8228 // size, because it is undefined to shift more bits out than exist
8229 // in the value.
8230 if (DestBitSize == SrcBitSize ||
8231 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00008232 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8233 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008234 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8235 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008236 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008237 }
8238 break;
8239 case Instruction::AShr:
8240 // If this is a signed shr, and if all bits shifted in are about to be
8241 // truncated off, turn it into an unsigned shr to allow greater
8242 // simplifications.
8243 if (DestBitSize < SrcBitSize &&
8244 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008245 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00008246 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8247 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008248 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008249 }
8250 }
8251 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008252 }
8253 return 0;
8254}
8255
Chris Lattner8a9f5712007-04-11 06:57:46 +00008256Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008257 if (Instruction *Result = commonIntCastTransforms(CI))
8258 return Result;
8259
8260 Value *Src = CI.getOperand(0);
8261 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00008262 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8263 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008264
8265 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8266 if (DestBitWidth == 1) {
8267 Constant *One = ConstantInt::get(Src->getType(), 1);
8268 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8269 Value *Zero = Constant::getNullValue(Src->getType());
8270 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8271 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008272
Chris Lattner4f9797d2009-03-24 18:15:30 +00008273 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8274 ConstantInt *ShAmtV = 0;
8275 Value *ShiftOp = 0;
8276 if (Src->hasOneUse() &&
8277 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8278 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8279
8280 // Get a mask for the bits shifting in.
8281 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8282 if (MaskedValueIsZero(ShiftOp, Mask)) {
8283 if (ShAmt >= DestBitWidth) // All zeros.
8284 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8285
8286 // Okay, we can shrink this. Truncate the input, then return a new
8287 // shift.
8288 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8289 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8290 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008291 }
8292 }
8293
8294 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008295}
8296
Evan Chengb98a10e2008-03-24 00:21:34 +00008297/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8298/// in order to eliminate the icmp.
8299Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8300 bool DoXform) {
8301 // If we are just checking for a icmp eq of a single bit and zext'ing it
8302 // to an integer, then shift the bit to the appropriate place and then
8303 // cast to integer to avoid the comparison.
8304 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8305 const APInt &Op1CV = Op1C->getValue();
8306
8307 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8308 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8309 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8310 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8311 if (!DoXform) return ICI;
8312
8313 Value *In = ICI->getOperand(0);
8314 Value *Sh = ConstantInt::get(In->getType(),
8315 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008316 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008317 In->getName()+".lobit"),
8318 CI);
8319 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008320 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008321 false/*ZExt*/, "tmp", &CI);
8322
8323 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8324 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008325 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008326 In->getName()+".not"),
8327 CI);
8328 }
8329
8330 return ReplaceInstUsesWith(CI, In);
8331 }
8332
8333
8334
8335 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8336 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8337 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8338 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8339 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8340 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8341 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8342 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8343 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8344 // This only works for EQ and NE
8345 ICI->isEquality()) {
8346 // If Op1C some other power of two, convert:
8347 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8348 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8349 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8350 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8351
8352 APInt KnownZeroMask(~KnownZero);
8353 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8354 if (!DoXform) return ICI;
8355
8356 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8357 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8358 // (X&4) == 2 --> false
8359 // (X&4) != 2 --> true
8360 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8361 Res = ConstantExpr::getZExt(Res, CI.getType());
8362 return ReplaceInstUsesWith(CI, Res);
8363 }
8364
8365 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8366 Value *In = ICI->getOperand(0);
8367 if (ShiftAmt) {
8368 // Perform a logical shr by shiftamt.
8369 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008370 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008371 ConstantInt::get(In->getType(), ShiftAmt),
8372 In->getName()+".lobit"), CI);
8373 }
8374
8375 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8376 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008377 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008378 InsertNewInstBefore(cast<Instruction>(In), CI);
8379 }
8380
8381 if (CI.getType() == In->getType())
8382 return ReplaceInstUsesWith(CI, In);
8383 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008384 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008385 }
8386 }
8387 }
8388
8389 return 0;
8390}
8391
Chris Lattner8a9f5712007-04-11 06:57:46 +00008392Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008393 // If one of the common conversion will work ..
8394 if (Instruction *Result = commonIntCastTransforms(CI))
8395 return Result;
8396
8397 Value *Src = CI.getOperand(0);
8398
Chris Lattnera84f47c2009-02-17 20:47:23 +00008399 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8400 // types and if the sizes are just right we can convert this into a logical
8401 // 'and' which will be much cheaper than the pair of casts.
8402 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8403 // Get the sizes of the types involved. We know that the intermediate type
8404 // will be smaller than A or C, but don't know the relation between A and C.
8405 Value *A = CSrc->getOperand(0);
8406 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8407 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8408 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8409 // If we're actually extending zero bits, then if
8410 // SrcSize < DstSize: zext(a & mask)
8411 // SrcSize == DstSize: a & mask
8412 // SrcSize > DstSize: trunc(a) & mask
8413 if (SrcSize < DstSize) {
8414 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8415 Constant *AndConst = ConstantInt::get(AndValue);
8416 Instruction *And =
8417 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8418 InsertNewInstBefore(And, CI);
8419 return new ZExtInst(And, CI.getType());
8420 } else if (SrcSize == DstSize) {
8421 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8422 return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8423 } else if (SrcSize > DstSize) {
8424 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8425 InsertNewInstBefore(Trunc, CI);
8426 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8427 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008428 }
8429 }
8430
Evan Chengb98a10e2008-03-24 00:21:34 +00008431 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8432 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008433
Evan Chengb98a10e2008-03-24 00:21:34 +00008434 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8435 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8436 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8437 // of the (zext icmp) will be transformed.
8438 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8439 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8440 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8441 (transformZExtICmp(LHS, CI, false) ||
8442 transformZExtICmp(RHS, CI, false))) {
8443 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8444 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008445 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008446 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008447 }
8448
Reid Spencer3da59db2006-11-27 01:05:10 +00008449 return 0;
8450}
8451
Chris Lattner8a9f5712007-04-11 06:57:46 +00008452Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008453 if (Instruction *I = commonIntCastTransforms(CI))
8454 return I;
8455
Chris Lattner8a9f5712007-04-11 06:57:46 +00008456 Value *Src = CI.getOperand(0);
8457
Dan Gohman1975d032008-10-30 20:40:10 +00008458 // Canonicalize sign-extend from i1 to a select.
8459 if (Src->getType() == Type::Int1Ty)
8460 return SelectInst::Create(Src,
8461 ConstantInt::getAllOnesValue(CI.getType()),
8462 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008463
8464 // See if the value being truncated is already sign extended. If so, just
8465 // eliminate the trunc/sext pair.
8466 if (getOpcode(Src) == Instruction::Trunc) {
8467 Value *Op = cast<User>(Src)->getOperand(0);
8468 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8469 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8470 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8471 unsigned NumSignBits = ComputeNumSignBits(Op);
8472
8473 if (OpBits == DestBits) {
8474 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8475 // bits, it is already ready.
8476 if (NumSignBits > DestBits-MidBits)
8477 return ReplaceInstUsesWith(CI, Op);
8478 } else if (OpBits < DestBits) {
8479 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8480 // bits, just sext from i32.
8481 if (NumSignBits > OpBits-MidBits)
8482 return new SExtInst(Op, CI.getType(), "tmp");
8483 } else {
8484 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8485 // bits, just truncate to i32.
8486 if (NumSignBits > OpBits-MidBits)
8487 return new TruncInst(Op, CI.getType(), "tmp");
8488 }
8489 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008490
8491 // If the input is a shl/ashr pair of a same constant, then this is a sign
8492 // extension from a smaller value. If we could trust arbitrary bitwidth
8493 // integers, we could turn this into a truncate to the smaller bit and then
8494 // use a sext for the whole extension. Since we don't, look deeper and check
8495 // for a truncate. If the source and dest are the same type, eliminate the
8496 // trunc and extend and just do shifts. For example, turn:
8497 // %a = trunc i32 %i to i8
8498 // %b = shl i8 %a, 6
8499 // %c = ashr i8 %b, 6
8500 // %d = sext i8 %c to i32
8501 // into:
8502 // %a = shl i32 %i, 30
8503 // %d = ashr i32 %a, 30
8504 Value *A = 0;
8505 ConstantInt *BA = 0, *CA = 0;
8506 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8507 m_ConstantInt(CA))) &&
8508 BA == CA && isa<TruncInst>(A)) {
8509 Value *I = cast<TruncInst>(A)->getOperand(0);
8510 if (I->getType() == CI.getType()) {
8511 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8512 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8513 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8514 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8515 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8516 CI.getName()), CI);
8517 return BinaryOperator::CreateAShr(I, ShAmtV);
8518 }
8519 }
8520
Chris Lattnerba417832007-04-11 06:12:58 +00008521 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008522}
8523
Chris Lattnerb7530652008-01-27 05:29:54 +00008524/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8525/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008526static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008527 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008528 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008529 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8530 if (!losesInfo)
Chris Lattner02a260a2008-04-20 00:41:09 +00008531 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008532 return 0;
8533}
8534
8535/// LookThroughFPExtensions - If this is an fp extension instruction, look
8536/// through it until we get the source value.
8537static Value *LookThroughFPExtensions(Value *V) {
8538 if (Instruction *I = dyn_cast<Instruction>(V))
8539 if (I->getOpcode() == Instruction::FPExt)
8540 return LookThroughFPExtensions(I->getOperand(0));
8541
8542 // If this value is a constant, return the constant in the smallest FP type
8543 // that can accurately represent it. This allows us to turn
8544 // (float)((double)X+2.0) into x+2.0f.
8545 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8546 if (CFP->getType() == Type::PPC_FP128Ty)
8547 return V; // No constant folding of this.
8548 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008549 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008550 return V;
8551 if (CFP->getType() == Type::DoubleTy)
8552 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008553 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008554 return V;
8555 // Don't try to shrink to various long double types.
8556 }
8557
8558 return V;
8559}
8560
8561Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8562 if (Instruction *I = commonCastTransforms(CI))
8563 return I;
8564
8565 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8566 // smaller than the destination type, we can eliminate the truncate by doing
8567 // the add as the smaller type. This applies to add/sub/mul/div as well as
8568 // many builtins (sqrt, etc).
8569 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8570 if (OpI && OpI->hasOneUse()) {
8571 switch (OpI->getOpcode()) {
8572 default: break;
8573 case Instruction::Add:
8574 case Instruction::Sub:
8575 case Instruction::Mul:
8576 case Instruction::FDiv:
8577 case Instruction::FRem:
8578 const Type *SrcTy = OpI->getType();
8579 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8580 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8581 if (LHSTrunc->getType() != SrcTy &&
8582 RHSTrunc->getType() != SrcTy) {
8583 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8584 // If the source types were both smaller than the destination type of
8585 // the cast, do this xform.
8586 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8587 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8588 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8589 CI.getType(), CI);
8590 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8591 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008592 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008593 }
8594 }
8595 break;
8596 }
8597 }
8598 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008599}
8600
8601Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8602 return commonCastTransforms(CI);
8603}
8604
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008605Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008606 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8607 if (OpI == 0)
8608 return commonCastTransforms(FI);
8609
8610 // fptoui(uitofp(X)) --> X
8611 // fptoui(sitofp(X)) --> X
8612 // This is safe if the intermediate type has enough bits in its mantissa to
8613 // accurately represent all values of X. For example, do not do this with
8614 // i64->float->i64. This is also safe for sitofp case, because any negative
8615 // 'X' value would cause an undefined result for the fptoui.
8616 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8617 OpI->getOperand(0)->getType() == FI.getType() &&
8618 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8619 OpI->getType()->getFPMantissaWidth())
8620 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008621
8622 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008623}
8624
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008625Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008626 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8627 if (OpI == 0)
8628 return commonCastTransforms(FI);
8629
8630 // fptosi(sitofp(X)) --> X
8631 // fptosi(uitofp(X)) --> X
8632 // This is safe if the intermediate type has enough bits in its mantissa to
8633 // accurately represent all values of X. For example, do not do this with
8634 // i64->float->i64. This is also safe for sitofp case, because any negative
8635 // 'X' value would cause an undefined result for the fptoui.
8636 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8637 OpI->getOperand(0)->getType() == FI.getType() &&
8638 (int)FI.getType()->getPrimitiveSizeInBits() <=
8639 OpI->getType()->getFPMantissaWidth())
8640 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008641
8642 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008643}
8644
8645Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8646 return commonCastTransforms(CI);
8647}
8648
8649Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8650 return commonCastTransforms(CI);
8651}
8652
Chris Lattnera0e69692009-03-24 18:35:40 +00008653Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8654 // If the destination integer type is smaller than the intptr_t type for
8655 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8656 // trunc to be exposed to other transforms. Don't do this for extending
8657 // ptrtoint's, because we don't know if the target sign or zero extends its
8658 // pointers.
8659 if (CI.getType()->getPrimitiveSizeInBits() < TD->getPointerSizeInBits()) {
8660 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8661 TD->getIntPtrType(),
8662 "tmp"), CI);
8663 return new TruncInst(P, CI.getType());
8664 }
8665
Chris Lattnerd3e28342007-04-27 17:44:50 +00008666 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008667}
8668
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008669Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008670 // If the source integer type is larger than the intptr_t type for
8671 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8672 // allows the trunc to be exposed to other transforms. Don't do this for
8673 // extending inttoptr's, because we don't know if the target sign or zero
8674 // extends to pointers.
8675 if (CI.getOperand(0)->getType()->getPrimitiveSizeInBits() >
8676 TD->getPointerSizeInBits()) {
8677 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8678 TD->getIntPtrType(),
8679 "tmp"), CI);
8680 return new IntToPtrInst(P, CI.getType());
8681 }
8682
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008683 if (Instruction *I = commonCastTransforms(CI))
8684 return I;
8685
8686 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8687 if (!DestPointee->isSized()) return 0;
8688
8689 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8690 ConstantInt *Cst;
8691 Value *X;
8692 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8693 m_ConstantInt(Cst)))) {
8694 // If the source and destination operands have the same type, see if this
8695 // is a single-index GEP.
8696 if (X->getType() == CI.getType()) {
8697 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008698 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008699
8700 // Convert the constant to intptr type.
8701 APInt Offset = Cst->getValue();
8702 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8703
8704 // If Offset is evenly divisible by Size, we can do this xform.
8705 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8706 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008707 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008708 }
8709 }
8710 // TODO: Could handle other cases, e.g. where add is indexing into field of
8711 // struct etc.
8712 } else if (CI.getOperand(0)->hasOneUse() &&
8713 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8714 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8715 // "inttoptr+GEP" instead of "add+intptr".
8716
8717 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008718 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008719
8720 // Convert the constant to intptr type.
8721 APInt Offset = Cst->getValue();
8722 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8723
8724 // If Offset is evenly divisible by Size, we can do this xform.
8725 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8726 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8727
8728 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8729 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008730 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008731 }
8732 }
8733 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008734}
8735
Chris Lattnerd3e28342007-04-27 17:44:50 +00008736Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008737 // If the operands are integer typed then apply the integer transforms,
8738 // otherwise just apply the common ones.
8739 Value *Src = CI.getOperand(0);
8740 const Type *SrcTy = Src->getType();
8741 const Type *DestTy = CI.getType();
8742
Chris Lattner42a75512007-01-15 02:27:26 +00008743 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008744 if (Instruction *Result = commonIntCastTransforms(CI))
8745 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008746 } else if (isa<PointerType>(SrcTy)) {
8747 if (Instruction *I = commonPointerCastTransforms(CI))
8748 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008749 } else {
8750 if (Instruction *Result = commonCastTransforms(CI))
8751 return Result;
8752 }
8753
8754
8755 // Get rid of casts from one type to the same type. These are useless and can
8756 // be replaced by the operand.
8757 if (DestTy == Src->getType())
8758 return ReplaceInstUsesWith(CI, Src);
8759
Reid Spencer3da59db2006-11-27 01:05:10 +00008760 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008761 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8762 const Type *DstElTy = DstPTy->getElementType();
8763 const Type *SrcElTy = SrcPTy->getElementType();
8764
Nate Begeman83ad90a2008-03-31 00:22:16 +00008765 // If the address spaces don't match, don't eliminate the bitcast, which is
8766 // required for changing types.
8767 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8768 return 0;
8769
Chris Lattnerd3e28342007-04-27 17:44:50 +00008770 // If we are casting a malloc or alloca to a pointer to a type of the same
8771 // size, rewrite the allocation instruction to allocate the "right" type.
8772 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8773 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8774 return V;
8775
Chris Lattnerd717c182007-05-05 22:32:24 +00008776 // If the source and destination are pointers, and this cast is equivalent
8777 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008778 // This can enhance SROA and other transforms that want type-safe pointers.
8779 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8780 unsigned NumZeros = 0;
8781 while (SrcElTy != DstElTy &&
8782 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8783 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8784 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8785 ++NumZeros;
8786 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008787
Chris Lattnerd3e28342007-04-27 17:44:50 +00008788 // If we found a path from the src to dest, create the getelementptr now.
8789 if (SrcElTy == DstElTy) {
8790 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008791 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8792 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008793 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008794 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008795
Reid Spencer3da59db2006-11-27 01:05:10 +00008796 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8797 if (SVI->hasOneUse()) {
8798 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8799 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008800 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008801 cast<VectorType>(DestTy)->getNumElements() ==
8802 SVI->getType()->getNumElements() &&
8803 SVI->getType()->getNumElements() ==
8804 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008805 CastInst *Tmp;
8806 // If either of the operands is a cast from CI.getType(), then
8807 // evaluating the shuffle in the casted destination's type will allow
8808 // us to eliminate at least one cast.
8809 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8810 Tmp->getOperand(0)->getType() == DestTy) ||
8811 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8812 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008813 Value *LHS = InsertCastBefore(Instruction::BitCast,
8814 SVI->getOperand(0), DestTy, CI);
8815 Value *RHS = InsertCastBefore(Instruction::BitCast,
8816 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008817 // Return a new shuffle vector. Use the same element ID's, as we
8818 // know the vector types match #elts.
8819 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008820 }
8821 }
8822 }
8823 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008824 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008825}
8826
Chris Lattnere576b912004-04-09 23:46:01 +00008827/// GetSelectFoldableOperands - We want to turn code that looks like this:
8828/// %C = or %A, %B
8829/// %D = select %cond, %C, %A
8830/// into:
8831/// %C = select %cond, %B, 0
8832/// %D = or %A, %C
8833///
8834/// Assuming that the specified instruction is an operand to the select, return
8835/// a bitmask indicating which operands of this instruction are foldable if they
8836/// equal the other incoming value of the select.
8837///
8838static unsigned GetSelectFoldableOperands(Instruction *I) {
8839 switch (I->getOpcode()) {
8840 case Instruction::Add:
8841 case Instruction::Mul:
8842 case Instruction::And:
8843 case Instruction::Or:
8844 case Instruction::Xor:
8845 return 3; // Can fold through either operand.
8846 case Instruction::Sub: // Can only fold on the amount subtracted.
8847 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008848 case Instruction::LShr:
8849 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008850 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008851 default:
8852 return 0; // Cannot fold
8853 }
8854}
8855
8856/// GetSelectFoldableConstant - For the same transformation as the previous
8857/// function, return the identity constant that goes into the select.
8858static Constant *GetSelectFoldableConstant(Instruction *I) {
8859 switch (I->getOpcode()) {
8860 default: assert(0 && "This cannot happen!"); abort();
8861 case Instruction::Add:
8862 case Instruction::Sub:
8863 case Instruction::Or:
8864 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008865 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008866 case Instruction::LShr:
8867 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008868 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008869 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008870 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008871 case Instruction::Mul:
8872 return ConstantInt::get(I->getType(), 1);
8873 }
8874}
8875
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008876/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8877/// have the same opcode and only one use each. Try to simplify this.
8878Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8879 Instruction *FI) {
8880 if (TI->getNumOperands() == 1) {
8881 // If this is a non-volatile load or a cast from the same type,
8882 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008883 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008884 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8885 return 0;
8886 } else {
8887 return 0; // unknown unary op.
8888 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008889
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008890 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008891 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8892 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008893 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008894 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008895 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008896 }
8897
Reid Spencer832254e2007-02-02 02:16:23 +00008898 // Only handle binary operators here.
8899 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008900 return 0;
8901
8902 // Figure out if the operations have any operands in common.
8903 Value *MatchOp, *OtherOpT, *OtherOpF;
8904 bool MatchIsOpZero;
8905 if (TI->getOperand(0) == FI->getOperand(0)) {
8906 MatchOp = TI->getOperand(0);
8907 OtherOpT = TI->getOperand(1);
8908 OtherOpF = FI->getOperand(1);
8909 MatchIsOpZero = true;
8910 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8911 MatchOp = TI->getOperand(1);
8912 OtherOpT = TI->getOperand(0);
8913 OtherOpF = FI->getOperand(0);
8914 MatchIsOpZero = false;
8915 } else if (!TI->isCommutative()) {
8916 return 0;
8917 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8918 MatchOp = TI->getOperand(0);
8919 OtherOpT = TI->getOperand(1);
8920 OtherOpF = FI->getOperand(0);
8921 MatchIsOpZero = true;
8922 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8923 MatchOp = TI->getOperand(1);
8924 OtherOpT = TI->getOperand(0);
8925 OtherOpF = FI->getOperand(1);
8926 MatchIsOpZero = true;
8927 } else {
8928 return 0;
8929 }
8930
8931 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008932 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8933 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008934 InsertNewInstBefore(NewSI, SI);
8935
8936 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8937 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008938 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008939 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008940 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008941 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008942 assert(0 && "Shouldn't get here");
8943 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008944}
8945
Evan Chengde621922009-03-31 20:42:45 +00008946static bool isSelect01(Constant *C1, Constant *C2) {
8947 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8948 if (!C1I)
8949 return false;
8950 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8951 if (!C2I)
8952 return false;
8953 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8954}
8955
8956/// FoldSelectIntoOp - Try fold the select into one of the operands to
8957/// facilitate further optimization.
8958Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
8959 Value *FalseVal) {
8960 // See the comment above GetSelectFoldableOperands for a description of the
8961 // transformation we are doing here.
8962 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
8963 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8964 !isa<Constant>(FalseVal)) {
8965 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8966 unsigned OpToFold = 0;
8967 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8968 OpToFold = 1;
8969 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8970 OpToFold = 2;
8971 }
8972
8973 if (OpToFold) {
8974 Constant *C = GetSelectFoldableConstant(TVI);
8975 Value *OOp = TVI->getOperand(2-OpToFold);
8976 // Avoid creating select between 2 constants unless it's selecting
8977 // between 0 and 1.
8978 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
8979 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
8980 InsertNewInstBefore(NewSel, SI);
8981 NewSel->takeName(TVI);
8982 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8983 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8984 assert(0 && "Unknown instruction!!");
8985 }
8986 }
8987 }
8988 }
8989 }
8990
8991 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
8992 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8993 !isa<Constant>(TrueVal)) {
8994 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8995 unsigned OpToFold = 0;
8996 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8997 OpToFold = 1;
8998 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8999 OpToFold = 2;
9000 }
9001
9002 if (OpToFold) {
9003 Constant *C = GetSelectFoldableConstant(FVI);
9004 Value *OOp = FVI->getOperand(2-OpToFold);
9005 // Avoid creating select between 2 constants unless it's selecting
9006 // between 0 and 1.
9007 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9008 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9009 InsertNewInstBefore(NewSel, SI);
9010 NewSel->takeName(FVI);
9011 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9012 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9013 assert(0 && "Unknown instruction!!");
9014 }
9015 }
9016 }
9017 }
9018 }
9019
9020 return 0;
9021}
9022
Dan Gohman81b28ce2008-09-16 18:46:06 +00009023/// visitSelectInstWithICmp - Visit a SelectInst that has an
9024/// ICmpInst as its first operand.
9025///
9026Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9027 ICmpInst *ICI) {
9028 bool Changed = false;
9029 ICmpInst::Predicate Pred = ICI->getPredicate();
9030 Value *CmpLHS = ICI->getOperand(0);
9031 Value *CmpRHS = ICI->getOperand(1);
9032 Value *TrueVal = SI.getTrueValue();
9033 Value *FalseVal = SI.getFalseValue();
9034
9035 // Check cases where the comparison is with a constant that
9036 // can be adjusted to fit the min/max idiom. We may edit ICI in
9037 // place here, so make sure the select is the only user.
9038 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009039 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009040 switch (Pred) {
9041 default: break;
9042 case ICmpInst::ICMP_ULT:
9043 case ICmpInst::ICMP_SLT: {
9044 // X < MIN ? T : F --> F
9045 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9046 return ReplaceInstUsesWith(SI, FalseVal);
9047 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9048 Constant *AdjustedRHS = SubOne(CI);
9049 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9050 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9051 Pred = ICmpInst::getSwappedPredicate(Pred);
9052 CmpRHS = AdjustedRHS;
9053 std::swap(FalseVal, TrueVal);
9054 ICI->setPredicate(Pred);
9055 ICI->setOperand(1, CmpRHS);
9056 SI.setOperand(1, TrueVal);
9057 SI.setOperand(2, FalseVal);
9058 Changed = true;
9059 }
9060 break;
9061 }
9062 case ICmpInst::ICMP_UGT:
9063 case ICmpInst::ICMP_SGT: {
9064 // X > MAX ? T : F --> F
9065 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9066 return ReplaceInstUsesWith(SI, FalseVal);
9067 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9068 Constant *AdjustedRHS = AddOne(CI);
9069 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9070 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9071 Pred = ICmpInst::getSwappedPredicate(Pred);
9072 CmpRHS = AdjustedRHS;
9073 std::swap(FalseVal, TrueVal);
9074 ICI->setPredicate(Pred);
9075 ICI->setOperand(1, CmpRHS);
9076 SI.setOperand(1, TrueVal);
9077 SI.setOperand(2, FalseVal);
9078 Changed = true;
9079 }
9080 break;
9081 }
9082 }
9083
Dan Gohman1975d032008-10-30 20:40:10 +00009084 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9085 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009086 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner159c35b2009-01-05 23:53:12 +00009087 if (match(TrueVal, m_ConstantInt<-1>()) &&
9088 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009089 Pred = ICI->getPredicate();
Chris Lattner159c35b2009-01-05 23:53:12 +00009090 else if (match(TrueVal, m_ConstantInt<0>()) &&
9091 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009092 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9093
Dan Gohman1975d032008-10-30 20:40:10 +00009094 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9095 // If we are just checking for a icmp eq of a single bit and zext'ing it
9096 // to an integer, then shift the bit to the appropriate place and then
9097 // cast to integer to avoid the comparison.
9098 const APInt &Op1CV = CI->getValue();
9099
9100 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9101 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9102 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009103 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009104 Value *In = ICI->getOperand(0);
9105 Value *Sh = ConstantInt::get(In->getType(),
9106 In->getType()->getPrimitiveSizeInBits()-1);
9107 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9108 In->getName()+".lobit"),
9109 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009110 if (In->getType() != SI.getType())
9111 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009112 true/*SExt*/, "tmp", ICI);
9113
9114 if (Pred == ICmpInst::ICMP_SGT)
9115 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9116 In->getName()+".not"), *ICI);
9117
9118 return ReplaceInstUsesWith(SI, In);
9119 }
9120 }
9121 }
9122
Dan Gohman81b28ce2008-09-16 18:46:06 +00009123 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9124 // Transform (X == Y) ? X : Y -> Y
9125 if (Pred == ICmpInst::ICMP_EQ)
9126 return ReplaceInstUsesWith(SI, FalseVal);
9127 // Transform (X != Y) ? X : Y -> X
9128 if (Pred == ICmpInst::ICMP_NE)
9129 return ReplaceInstUsesWith(SI, TrueVal);
9130 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9131
9132 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9133 // Transform (X == Y) ? Y : X -> X
9134 if (Pred == ICmpInst::ICMP_EQ)
9135 return ReplaceInstUsesWith(SI, FalseVal);
9136 // Transform (X != Y) ? Y : X -> Y
9137 if (Pred == ICmpInst::ICMP_NE)
9138 return ReplaceInstUsesWith(SI, TrueVal);
9139 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9140 }
9141
9142 /// NOTE: if we wanted to, this is where to detect integer ABS
9143
9144 return Changed ? &SI : 0;
9145}
9146
Chris Lattner3d69f462004-03-12 05:52:32 +00009147Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009148 Value *CondVal = SI.getCondition();
9149 Value *TrueVal = SI.getTrueValue();
9150 Value *FalseVal = SI.getFalseValue();
9151
9152 // select true, X, Y -> X
9153 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009154 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009155 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009156
9157 // select C, X, X -> X
9158 if (TrueVal == FalseVal)
9159 return ReplaceInstUsesWith(SI, TrueVal);
9160
Chris Lattnere87597f2004-10-16 18:11:37 +00009161 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9162 return ReplaceInstUsesWith(SI, FalseVal);
9163 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9164 return ReplaceInstUsesWith(SI, TrueVal);
9165 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9166 if (isa<Constant>(TrueVal))
9167 return ReplaceInstUsesWith(SI, TrueVal);
9168 else
9169 return ReplaceInstUsesWith(SI, FalseVal);
9170 }
9171
Reid Spencer4fe16d62007-01-11 18:21:29 +00009172 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009173 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009174 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009175 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009176 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009177 } else {
9178 // Change: A = select B, false, C --> A = and !B, C
9179 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009180 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009181 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009182 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009183 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009184 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009185 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009186 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009187 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009188 } else {
9189 // Change: A = select B, C, true --> A = or !B, C
9190 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009191 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009192 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009193 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009194 }
9195 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009196
9197 // select a, b, a -> a&b
9198 // select a, a, b -> a|b
9199 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009200 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009201 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009202 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009203 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009204
Chris Lattner2eefe512004-04-09 19:05:30 +00009205 // Selecting between two integer constants?
9206 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9207 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009208 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009209 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009210 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009211 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009212 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009213 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009214 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009215 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009216 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009217 }
Chris Lattner457dd822004-06-09 07:59:58 +00009218
Reid Spencere4d87aa2006-12-23 06:05:41 +00009219 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009220
Reid Spencere4d87aa2006-12-23 06:05:41 +00009221 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00009222 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00009223 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00009224 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009225 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00009226 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00009227 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00009228 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00009229 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009230 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00009231 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00009232 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009233
9234 // Then cast to the appropriate width.
9235 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00009236 }
9237 }
9238
9239
9240 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009241 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009242 // non-constant value, eliminate this whole mess. This corresponds to
9243 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009244 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009245 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009246 cast<Constant>(IC->getOperand(1))->isNullValue())
9247 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9248 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009249 isa<ConstantInt>(ICA->getOperand(1)) &&
9250 (ICA->getOperand(1) == TrueValC ||
9251 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009252 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9253 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009254 // know whether we have a icmp_ne or icmp_eq and whether the
9255 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009256 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009257 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009258 Value *V = ICA;
9259 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009260 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009261 Instruction::Xor, V, ICA->getOperand(1)), SI);
9262 return ReplaceInstUsesWith(SI, V);
9263 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009264 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009265 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009266
9267 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009268 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9269 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009270 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009271 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9272 // This is not safe in general for floating point:
9273 // consider X== -0, Y== +0.
9274 // It becomes safe if either operand is a nonzero constant.
9275 ConstantFP *CFPt, *CFPf;
9276 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9277 !CFPt->getValueAPF().isZero()) ||
9278 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9279 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009280 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009281 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009282 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009283 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009284 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009285 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009286
Reid Spencere4d87aa2006-12-23 06:05:41 +00009287 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009288 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009289 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9290 // This is not safe in general for floating point:
9291 // consider X== -0, Y== +0.
9292 // It becomes safe if either operand is a nonzero constant.
9293 ConstantFP *CFPt, *CFPf;
9294 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9295 !CFPt->getValueAPF().isZero()) ||
9296 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9297 !CFPf->getValueAPF().isZero()))
9298 return ReplaceInstUsesWith(SI, FalseVal);
9299 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009300 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009301 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9302 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009303 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009304 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009305 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009306 }
9307
9308 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009309 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9310 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9311 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009312
Chris Lattner87875da2005-01-13 22:52:24 +00009313 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9314 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9315 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009316 Instruction *AddOp = 0, *SubOp = 0;
9317
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009318 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9319 if (TI->getOpcode() == FI->getOpcode())
9320 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9321 return IV;
9322
9323 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9324 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00009325 if (TI->getOpcode() == Instruction::Sub &&
9326 FI->getOpcode() == Instruction::Add) {
9327 AddOp = FI; SubOp = TI;
9328 } else if (FI->getOpcode() == Instruction::Sub &&
9329 TI->getOpcode() == Instruction::Add) {
9330 AddOp = TI; SubOp = FI;
9331 }
9332
9333 if (AddOp) {
9334 Value *OtherAddOp = 0;
9335 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9336 OtherAddOp = AddOp->getOperand(1);
9337 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9338 OtherAddOp = AddOp->getOperand(0);
9339 }
9340
9341 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009342 // So at this point we know we have (Y -> OtherAddOp):
9343 // select C, (add X, Y), (sub X, Z)
9344 Value *NegVal; // Compute -Z
9345 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9346 NegVal = ConstantExpr::getNeg(C);
9347 } else {
9348 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009349 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009350 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009351
9352 Value *NewTrueOp = OtherAddOp;
9353 Value *NewFalseOp = NegVal;
9354 if (AddOp != TI)
9355 std::swap(NewTrueOp, NewFalseOp);
9356 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009357 SelectInst::Create(CondVal, NewTrueOp,
9358 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009359
9360 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009361 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009362 }
9363 }
9364 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009365
Chris Lattnere576b912004-04-09 23:46:01 +00009366 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009367 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009368 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9369 if (FoldI)
9370 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009371 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009372
9373 if (BinaryOperator::isNot(CondVal)) {
9374 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9375 SI.setOperand(1, FalseVal);
9376 SI.setOperand(2, TrueVal);
9377 return &SI;
9378 }
9379
Chris Lattner3d69f462004-03-12 05:52:32 +00009380 return 0;
9381}
9382
Dan Gohmaneee962e2008-04-10 18:43:06 +00009383/// EnforceKnownAlignment - If the specified pointer points to an object that
9384/// we control, modify the object's alignment to PrefAlign. This isn't
9385/// often possible though. If alignment is important, a more reliable approach
9386/// is to simply align all global variables and allocation instructions to
9387/// their preferred alignment from the beginning.
9388///
9389static unsigned EnforceKnownAlignment(Value *V,
9390 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009391
Dan Gohmaneee962e2008-04-10 18:43:06 +00009392 User *U = dyn_cast<User>(V);
9393 if (!U) return Align;
9394
9395 switch (getOpcode(U)) {
9396 default: break;
9397 case Instruction::BitCast:
9398 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9399 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009400 // If all indexes are zero, it is just the alignment of the base pointer.
9401 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009402 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009403 if (!isa<Constant>(*i) ||
9404 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009405 AllZeroOperands = false;
9406 break;
9407 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009408
9409 if (AllZeroOperands) {
9410 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009411 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009412 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009413 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009414 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009415 }
9416
9417 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9418 // If there is a large requested alignment and we can, bump up the alignment
9419 // of the global.
9420 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009421 if (GV->getAlignment() >= PrefAlign)
9422 Align = GV->getAlignment();
9423 else {
9424 GV->setAlignment(PrefAlign);
9425 Align = PrefAlign;
9426 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009427 }
9428 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9429 // If there is a requested alignment and if this is an alloca, round up. We
9430 // don't do this for malloc, because some systems can't respect the request.
9431 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009432 if (AI->getAlignment() >= PrefAlign)
9433 Align = AI->getAlignment();
9434 else {
9435 AI->setAlignment(PrefAlign);
9436 Align = PrefAlign;
9437 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009438 }
9439 }
9440
9441 return Align;
9442}
9443
9444/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9445/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9446/// and it is more than the alignment of the ultimate object, see if we can
9447/// increase the alignment of the ultimate object, making this check succeed.
9448unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9449 unsigned PrefAlign) {
9450 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9451 sizeof(PrefAlign) * CHAR_BIT;
9452 APInt Mask = APInt::getAllOnesValue(BitWidth);
9453 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9454 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9455 unsigned TrailZ = KnownZero.countTrailingOnes();
9456 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9457
9458 if (PrefAlign > Align)
9459 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9460
9461 // We don't need to make any adjustment.
9462 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009463}
9464
Chris Lattnerf497b022008-01-13 23:50:23 +00009465Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009466 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009467 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009468 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009469 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009470
9471 if (CopyAlign < MinAlign) {
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009472 MI->setAlignment(MinAlign);
Chris Lattnerf497b022008-01-13 23:50:23 +00009473 return MI;
9474 }
9475
9476 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9477 // load/store.
9478 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9479 if (MemOpLength == 0) return 0;
9480
Chris Lattner37ac6082008-01-14 00:28:35 +00009481 // Source and destination pointer types are always "i8*" for intrinsic. See
9482 // if the size is something we can handle with a single primitive load/store.
9483 // A single load+store correctly handles overlapping memory in the memmove
9484 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009485 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009486 if (Size == 0) return MI; // Delete this mem transfer.
9487
9488 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009489 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009490
Chris Lattner37ac6082008-01-14 00:28:35 +00009491 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009492 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009493
9494 // Memcpy forces the use of i8* for the source and destination. That means
9495 // that if you're using memcpy to move one double around, you'll get a cast
9496 // from double* to i8*. We'd much rather use a double load+store rather than
9497 // an i64 load+store, here because this improves the odds that the source or
9498 // dest address will be promotable. See if we can find a better type than the
9499 // integer datatype.
9500 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9501 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9502 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9503 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9504 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009505 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009506 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9507 if (STy->getNumElements() == 1)
9508 SrcETy = STy->getElementType(0);
9509 else
9510 break;
9511 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9512 if (ATy->getNumElements() == 1)
9513 SrcETy = ATy->getElementType();
9514 else
9515 break;
9516 } else
9517 break;
9518 }
9519
Dan Gohman8f8e2692008-05-23 01:52:21 +00009520 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009521 NewPtrTy = PointerType::getUnqual(SrcETy);
9522 }
9523 }
9524
9525
Chris Lattnerf497b022008-01-13 23:50:23 +00009526 // If the memcpy/memmove provides better alignment info than we can
9527 // infer, use it.
9528 SrcAlign = std::max(SrcAlign, CopyAlign);
9529 DstAlign = std::max(DstAlign, CopyAlign);
9530
9531 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9532 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009533 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9534 InsertNewInstBefore(L, *MI);
9535 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9536
9537 // Set the size of the copy to 0, it will be deleted on the next iteration.
9538 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9539 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009540}
Chris Lattner3d69f462004-03-12 05:52:32 +00009541
Chris Lattner69ea9d22008-04-30 06:39:11 +00009542Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9543 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009544 if (MI->getAlignment() < Alignment) {
9545 MI->setAlignment(Alignment);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009546 return MI;
9547 }
9548
9549 // Extract the length and alignment and fill if they are constant.
9550 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9551 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9552 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9553 return 0;
9554 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009555 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009556
9557 // If the length is zero, this is a no-op
9558 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9559
9560 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9561 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9562 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9563
9564 Value *Dest = MI->getDest();
9565 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9566
9567 // Alignment 0 is identity for alignment 1 for memset, but not store.
9568 if (Alignment == 0) Alignment = 1;
9569
9570 // Extract the fill value and store.
9571 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9572 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9573 Alignment), *MI);
9574
9575 // Set the size of the copy to 0, it will be deleted on the next iteration.
9576 MI->setLength(Constant::getNullValue(LenC->getType()));
9577 return MI;
9578 }
9579
9580 return 0;
9581}
9582
9583
Chris Lattner8b0ea312006-01-13 20:11:04 +00009584/// visitCallInst - CallInst simplification. This mostly only handles folding
9585/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9586/// the heavy lifting.
9587///
Chris Lattner9fe38862003-06-19 17:00:31 +00009588Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009589 // If the caller function is nounwind, mark the call as nounwind, even if the
9590 // callee isn't.
9591 if (CI.getParent()->getParent()->doesNotThrow() &&
9592 !CI.doesNotThrow()) {
9593 CI.setDoesNotThrow();
9594 return &CI;
9595 }
9596
9597
9598
Chris Lattner8b0ea312006-01-13 20:11:04 +00009599 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9600 if (!II) return visitCallSite(&CI);
9601
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009602 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9603 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009604 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009605 bool Changed = false;
9606
9607 // memmove/cpy/set of zero bytes is a noop.
9608 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9609 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9610
Chris Lattner35b9e482004-10-12 04:52:52 +00009611 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009612 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009613 // Replace the instruction with just byte operations. We would
9614 // transform other cases to loads/stores, but we don't know if
9615 // alignment is sufficient.
9616 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009617 }
9618
Chris Lattner35b9e482004-10-12 04:52:52 +00009619 // If we have a memmove and the source operation is a constant global,
9620 // then the source and dest pointers can't alias, so we can change this
9621 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009622 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009623 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9624 if (GVSrc->isConstant()) {
9625 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009626 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9627 const Type *Tys[1];
9628 Tys[0] = CI.getOperand(3)->getType();
9629 CI.setOperand(0,
9630 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009631 Changed = true;
9632 }
Chris Lattnera935db82008-05-28 05:30:41 +00009633
9634 // memmove(x,x,size) -> noop.
9635 if (MMI->getSource() == MMI->getDest())
9636 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009637 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009638
Chris Lattner95a959d2006-03-06 20:18:44 +00009639 // If we can determine a pointer alignment that is bigger than currently
9640 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009641 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009642 if (Instruction *I = SimplifyMemTransfer(MI))
9643 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009644 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9645 if (Instruction *I = SimplifyMemSet(MSI))
9646 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009647 }
9648
Chris Lattner8b0ea312006-01-13 20:11:04 +00009649 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009650 }
9651
9652 switch (II->getIntrinsicID()) {
9653 default: break;
9654 case Intrinsic::bswap:
9655 // bswap(bswap(x)) -> x
9656 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9657 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9658 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9659 break;
9660 case Intrinsic::ppc_altivec_lvx:
9661 case Intrinsic::ppc_altivec_lvxl:
9662 case Intrinsic::x86_sse_loadu_ps:
9663 case Intrinsic::x86_sse2_loadu_pd:
9664 case Intrinsic::x86_sse2_loadu_dq:
9665 // Turn PPC lvx -> load if the pointer is known aligned.
9666 // Turn X86 loadups -> load if the pointer is known aligned.
9667 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9668 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9669 PointerType::getUnqual(II->getType()),
9670 CI);
9671 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009672 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009673 break;
9674 case Intrinsic::ppc_altivec_stvx:
9675 case Intrinsic::ppc_altivec_stvxl:
9676 // Turn stvx -> store if the pointer is known aligned.
9677 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9678 const Type *OpPtrTy =
9679 PointerType::getUnqual(II->getOperand(1)->getType());
9680 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9681 return new StoreInst(II->getOperand(1), Ptr);
9682 }
9683 break;
9684 case Intrinsic::x86_sse_storeu_ps:
9685 case Intrinsic::x86_sse2_storeu_pd:
9686 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009687 // Turn X86 storeu -> store if the pointer is known aligned.
9688 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9689 const Type *OpPtrTy =
9690 PointerType::getUnqual(II->getOperand(2)->getType());
9691 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9692 return new StoreInst(II->getOperand(2), Ptr);
9693 }
9694 break;
9695
9696 case Intrinsic::x86_sse_cvttss2si: {
9697 // These intrinsics only demands the 0th element of its input vector. If
9698 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009699 unsigned VWidth =
9700 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9701 APInt DemandedElts(VWidth, 1);
9702 APInt UndefElts(VWidth, 0);
9703 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009704 UndefElts)) {
9705 II->setOperand(1, V);
9706 return II;
9707 }
9708 break;
9709 }
9710
9711 case Intrinsic::ppc_altivec_vperm:
9712 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9713 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9714 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009715
Chris Lattner0521e3c2008-06-18 04:33:20 +00009716 // Check that all of the elements are integer constants or undefs.
9717 bool AllEltsOk = true;
9718 for (unsigned i = 0; i != 16; ++i) {
9719 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9720 !isa<UndefValue>(Mask->getOperand(i))) {
9721 AllEltsOk = false;
9722 break;
9723 }
9724 }
9725
9726 if (AllEltsOk) {
9727 // Cast the input vectors to byte vectors.
9728 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9729 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9730 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009731
Chris Lattner0521e3c2008-06-18 04:33:20 +00009732 // Only extract each element once.
9733 Value *ExtractedElts[32];
9734 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9735
Chris Lattnere2ed0572006-04-06 19:19:17 +00009736 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009737 if (isa<UndefValue>(Mask->getOperand(i)))
9738 continue;
9739 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9740 Idx &= 31; // Match the hardware behavior.
9741
9742 if (ExtractedElts[Idx] == 0) {
9743 Instruction *Elt =
9744 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9745 InsertNewInstBefore(Elt, CI);
9746 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009747 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009748
Chris Lattner0521e3c2008-06-18 04:33:20 +00009749 // Insert this value into the result vector.
9750 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9751 i, "tmp");
9752 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009753 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009754 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009755 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009756 }
9757 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009758
Chris Lattner0521e3c2008-06-18 04:33:20 +00009759 case Intrinsic::stackrestore: {
9760 // If the save is right next to the restore, remove the restore. This can
9761 // happen when variable allocas are DCE'd.
9762 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9763 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9764 BasicBlock::iterator BI = SS;
9765 if (&*++BI == II)
9766 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009767 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009768 }
9769
9770 // Scan down this block to see if there is another stack restore in the
9771 // same block without an intervening call/alloca.
9772 BasicBlock::iterator BI = II;
9773 TerminatorInst *TI = II->getParent()->getTerminator();
9774 bool CannotRemove = false;
9775 for (++BI; &*BI != TI; ++BI) {
9776 if (isa<AllocaInst>(BI)) {
9777 CannotRemove = true;
9778 break;
9779 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009780 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9781 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9782 // If there is a stackrestore below this one, remove this one.
9783 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9784 return EraseInstFromFunction(CI);
9785 // Otherwise, ignore the intrinsic.
9786 } else {
9787 // If we found a non-intrinsic call, we can't remove the stack
9788 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009789 CannotRemove = true;
9790 break;
9791 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009792 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009793 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009794
9795 // If the stack restore is in a return/unwind block and if there are no
9796 // allocas or calls between the restore and the return, nuke the restore.
9797 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9798 return EraseInstFromFunction(CI);
9799 break;
9800 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009801 }
9802
Chris Lattner8b0ea312006-01-13 20:11:04 +00009803 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009804}
9805
9806// InvokeInst simplification
9807//
9808Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009809 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009810}
9811
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009812/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9813/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009814static bool isSafeToEliminateVarargsCast(const CallSite CS,
9815 const CastInst * const CI,
9816 const TargetData * const TD,
9817 const int ix) {
9818 if (!CI->isLosslessCast())
9819 return false;
9820
9821 // The size of ByVal arguments is derived from the type, so we
9822 // can't change to a type with a different size. If the size were
9823 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009824 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009825 return true;
9826
9827 const Type* SrcTy =
9828 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9829 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9830 if (!SrcTy->isSized() || !DstTy->isSized())
9831 return false;
Duncan Sands777d2302009-05-09 07:06:46 +00009832 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009833 return false;
9834 return true;
9835}
9836
Chris Lattnera44d8a22003-10-07 22:32:43 +00009837// visitCallSite - Improvements for call and invoke instructions.
9838//
9839Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009840 bool Changed = false;
9841
9842 // If the callee is a constexpr cast of a function, attempt to move the cast
9843 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009844 if (transformConstExprCastCall(CS)) return 0;
9845
Chris Lattner6c266db2003-10-07 22:54:13 +00009846 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009847
Chris Lattner08b22ec2005-05-13 07:09:09 +00009848 if (Function *CalleeF = dyn_cast<Function>(Callee))
9849 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9850 Instruction *OldCall = CS.getInstruction();
9851 // If the call and callee calling conventions don't match, this call must
9852 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009853 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009854 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9855 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009856 if (!OldCall->use_empty())
9857 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9858 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9859 return EraseInstFromFunction(*OldCall);
9860 return 0;
9861 }
9862
Chris Lattner17be6352004-10-18 02:59:09 +00009863 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9864 // This instruction is not reachable, just remove it. We insert a store to
9865 // undef so that we know that this code is not reachable, despite the fact
9866 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009867 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009868 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009869 CS.getInstruction());
9870
9871 if (!CS.getInstruction()->use_empty())
9872 CS.getInstruction()->
9873 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9874
9875 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9876 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009877 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9878 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009879 }
Chris Lattner17be6352004-10-18 02:59:09 +00009880 return EraseInstFromFunction(*CS.getInstruction());
9881 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009882
Duncan Sandscdb6d922007-09-17 10:26:40 +00009883 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9884 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9885 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9886 return transformCallThroughTrampoline(CS);
9887
Chris Lattner6c266db2003-10-07 22:54:13 +00009888 const PointerType *PTy = cast<PointerType>(Callee->getType());
9889 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9890 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009891 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009892 // See if we can optimize any arguments passed through the varargs area of
9893 // the call.
9894 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009895 E = CS.arg_end(); I != E; ++I, ++ix) {
9896 CastInst *CI = dyn_cast<CastInst>(*I);
9897 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9898 *I = CI->getOperand(0);
9899 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009900 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009901 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009902 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009903
Duncan Sandsf0c33542007-12-19 21:13:37 +00009904 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009905 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009906 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009907 Changed = true;
9908 }
9909
Chris Lattner6c266db2003-10-07 22:54:13 +00009910 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009911}
9912
Chris Lattner9fe38862003-06-19 17:00:31 +00009913// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9914// attempt to move the cast to the arguments of the call/invoke.
9915//
9916bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9917 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9918 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009919 if (CE->getOpcode() != Instruction::BitCast ||
9920 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009921 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009922 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009923 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009924 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009925
9926 // Okay, this is a cast from a function to a different type. Unless doing so
9927 // would cause a type conversion of one of our arguments, change this call to
9928 // be a direct call with arguments casted to the appropriate types.
9929 //
9930 const FunctionType *FT = Callee->getFunctionType();
9931 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009932 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009933
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009934 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009935 return false; // TODO: Handle multiple return values.
9936
Chris Lattnerf78616b2004-01-14 06:06:08 +00009937 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009938 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009939 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009940 // Conversion is ok if changing from one pointer type to another or from
9941 // a pointer to an integer of the same size.
9942 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00009943 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00009944 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009945
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009946 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009947 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009948 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009949 return false; // Cannot transform this return value.
9950
Chris Lattner58d74912008-03-12 17:45:29 +00009951 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009952 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009953 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009954 return false; // Attribute not compatible with transformed value.
9955 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009956
Chris Lattnerf78616b2004-01-14 06:06:08 +00009957 // If the callsite is an invoke instruction, and the return value is used by
9958 // a PHI node in a successor, we cannot change the return type of the call
9959 // because there is no place to put the cast instruction (without breaking
9960 // the critical edge). Bail out in this case.
9961 if (!Caller->use_empty())
9962 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9963 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9964 UI != E; ++UI)
9965 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9966 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009967 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009968 return false;
9969 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009970
9971 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9972 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009973
Chris Lattner9fe38862003-06-19 17:00:31 +00009974 CallSite::arg_iterator AI = CS.arg_begin();
9975 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9976 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009977 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009978
9979 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009980 return false; // Cannot transform this parameter value.
9981
Devang Patel19c87462008-09-26 22:53:05 +00009982 if (CallerPAL.getParamAttributes(i + 1)
9983 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00009984 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009985
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009986 // Converting from one pointer type to another or between a pointer and an
9987 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00009988 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009989 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9990 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00009991 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009992 }
9993
9994 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009995 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009996 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009997
Chris Lattner58d74912008-03-12 17:45:29 +00009998 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9999 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010000 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010001 // won't be dropping them. Check that these extra arguments have attributes
10002 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010003 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10004 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010005 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010006 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010007 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010008 return false;
10009 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010010
Chris Lattner9fe38862003-06-19 17:00:31 +000010011 // Okay, we decided that this is a safe thing to do: go ahead and start
10012 // inserting cast instructions as necessary...
10013 std::vector<Value*> Args;
10014 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010015 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010016 attrVec.reserve(NumCommonArgs);
10017
10018 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010019 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010020
10021 // If the return value is not being used, the type may not be compatible
10022 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010023 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010024
10025 // Add the new return attributes.
10026 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010027 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010028
10029 AI = CS.arg_begin();
10030 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10031 const Type *ParamTy = FT->getParamType(i);
10032 if ((*AI)->getType() == ParamTy) {
10033 Args.push_back(*AI);
10034 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010035 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010036 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010037 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010038 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010039 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010040
10041 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010042 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010043 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010044 }
10045
10046 // If the function takes more arguments than the call was taking, add them
10047 // now...
10048 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10049 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10050
10051 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010052 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010053 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010054 cerr << "WARNING: While resolving call to function '"
10055 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010056 } else {
10057 // Add all of the arguments in their promoted form to the arg list...
10058 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10059 const Type *PTy = getPromotedType((*AI)->getType());
10060 if (PTy != (*AI)->getType()) {
10061 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010062 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10063 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010064 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010065 InsertNewInstBefore(Cast, *Caller);
10066 Args.push_back(Cast);
10067 } else {
10068 Args.push_back(*AI);
10069 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010070
Duncan Sandse1e520f2008-01-13 08:02:44 +000010071 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010072 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010073 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010074 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010075 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010076 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010077
Devang Patel19c87462008-09-26 22:53:05 +000010078 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10079 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10080
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010081 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010082 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010083
Devang Patel05988662008-09-25 21:00:45 +000010084 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010085
Chris Lattner9fe38862003-06-19 17:00:31 +000010086 Instruction *NC;
10087 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010088 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010089 Args.begin(), Args.end(),
10090 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010091 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010092 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010093 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010094 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10095 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010096 CallInst *CI = cast<CallInst>(Caller);
10097 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010098 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010099 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010100 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010101 }
10102
Chris Lattner6934a042007-02-11 01:23:03 +000010103 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010104 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010105 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010106 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010107 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010108 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010109 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010110
10111 // If this is an invoke instruction, we should insert it after the first
10112 // non-phi, instruction in the normal successor block.
10113 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010114 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010115 InsertNewInstBefore(NC, *I);
10116 } else {
10117 // Otherwise, it's a call, just insert cast right after the call instr
10118 InsertNewInstBefore(NC, *Caller);
10119 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010120 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010121 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +000010122 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010123 }
10124 }
10125
10126 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10127 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010128 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010129 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010130 return true;
10131}
10132
Duncan Sandscdb6d922007-09-17 10:26:40 +000010133// transformCallThroughTrampoline - Turn a call to a function created by the
10134// init_trampoline intrinsic into a direct call to the underlying function.
10135//
10136Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10137 Value *Callee = CS.getCalledValue();
10138 const PointerType *PTy = cast<PointerType>(Callee->getType());
10139 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010140 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010141
10142 // If the call already has the 'nest' attribute somewhere then give up -
10143 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010144 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010145 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010146
10147 IntrinsicInst *Tramp =
10148 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10149
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010150 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010151 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10152 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10153
Devang Patel05988662008-09-25 21:00:45 +000010154 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010155 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010156 unsigned NestIdx = 1;
10157 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010158 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010159
10160 // Look for a parameter marked with the 'nest' attribute.
10161 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10162 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010163 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010164 // Record the parameter type and any other attributes.
10165 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010166 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010167 break;
10168 }
10169
10170 if (NestTy) {
10171 Instruction *Caller = CS.getInstruction();
10172 std::vector<Value*> NewArgs;
10173 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10174
Devang Patel05988662008-09-25 21:00:45 +000010175 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010176 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010177
Duncan Sandscdb6d922007-09-17 10:26:40 +000010178 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010179 // mean appending it. Likewise for attributes.
10180
Devang Patel19c87462008-09-26 22:53:05 +000010181 // Add any result attributes.
10182 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010183 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010184
Duncan Sandscdb6d922007-09-17 10:26:40 +000010185 {
10186 unsigned Idx = 1;
10187 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10188 do {
10189 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010190 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010191 Value *NestVal = Tramp->getOperand(3);
10192 if (NestVal->getType() != NestTy)
10193 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10194 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010195 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010196 }
10197
10198 if (I == E)
10199 break;
10200
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010201 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010202 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010203 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010204 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010205 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010206
10207 ++Idx, ++I;
10208 } while (1);
10209 }
10210
Devang Patel19c87462008-09-26 22:53:05 +000010211 // Add any function attributes.
10212 if (Attributes Attr = Attrs.getFnAttributes())
10213 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10214
Duncan Sandscdb6d922007-09-17 10:26:40 +000010215 // The trampoline may have been bitcast to a bogus type (FTy).
10216 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010217 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010218
Duncan Sandscdb6d922007-09-17 10:26:40 +000010219 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010220 NewTypes.reserve(FTy->getNumParams()+1);
10221
Duncan Sandscdb6d922007-09-17 10:26:40 +000010222 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010223 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010224 {
10225 unsigned Idx = 1;
10226 FunctionType::param_iterator I = FTy->param_begin(),
10227 E = FTy->param_end();
10228
10229 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010230 if (Idx == NestIdx)
10231 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010232 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010233
10234 if (I == E)
10235 break;
10236
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010237 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010238 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010239
10240 ++Idx, ++I;
10241 } while (1);
10242 }
10243
10244 // Replace the trampoline call with a direct call. Let the generic
10245 // code sort out any function type mismatches.
10246 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +000010247 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010248 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10249 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010250 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010251
10252 Instruction *NewCaller;
10253 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010254 NewCaller = InvokeInst::Create(NewCallee,
10255 II->getNormalDest(), II->getUnwindDest(),
10256 NewArgs.begin(), NewArgs.end(),
10257 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010258 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010259 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010260 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010261 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10262 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010263 if (cast<CallInst>(Caller)->isTailCall())
10264 cast<CallInst>(NewCaller)->setTailCall();
10265 cast<CallInst>(NewCaller)->
10266 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010267 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010268 }
10269 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10270 Caller->replaceAllUsesWith(NewCaller);
10271 Caller->eraseFromParent();
10272 RemoveFromWorkList(Caller);
10273 return 0;
10274 }
10275 }
10276
10277 // Replace the trampoline call with a direct call. Since there is no 'nest'
10278 // parameter, there is no need to adjust the argument list. Let the generic
10279 // code sort out any function type mismatches.
10280 Constant *NewCallee =
10281 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10282 CS.setCalledFunction(NewCallee);
10283 return CS.getInstruction();
10284}
10285
Chris Lattner7da52b22006-11-01 04:51:18 +000010286/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10287/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10288/// and a single binop.
10289Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10290 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010291 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010292 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010293 Value *LHSVal = FirstInst->getOperand(0);
10294 Value *RHSVal = FirstInst->getOperand(1);
10295
10296 const Type *LHSType = LHSVal->getType();
10297 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010298
10299 // Scan to see if all operands are the same opcode, all have one use, and all
10300 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010301 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010302 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010303 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010304 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010305 // types or GEP's with different index types.
10306 I->getOperand(0)->getType() != LHSType ||
10307 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010308 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010309
10310 // If they are CmpInst instructions, check their predicates
10311 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10312 if (cast<CmpInst>(I)->getPredicate() !=
10313 cast<CmpInst>(FirstInst)->getPredicate())
10314 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010315
10316 // Keep track of which operand needs a phi node.
10317 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10318 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010319 }
10320
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010321 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010322
Chris Lattner7da52b22006-11-01 04:51:18 +000010323 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010324 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010325 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010326 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010327 NewLHS = PHINode::Create(LHSType,
10328 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010329 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10330 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010331 InsertNewInstBefore(NewLHS, PN);
10332 LHSVal = NewLHS;
10333 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010334
10335 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010336 NewRHS = PHINode::Create(RHSType,
10337 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010338 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10339 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010340 InsertNewInstBefore(NewRHS, PN);
10341 RHSVal = NewRHS;
10342 }
10343
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010344 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010345 if (NewLHS || NewRHS) {
10346 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10347 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10348 if (NewLHS) {
10349 Value *NewInLHS = InInst->getOperand(0);
10350 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10351 }
10352 if (NewRHS) {
10353 Value *NewInRHS = InInst->getOperand(1);
10354 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10355 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010356 }
10357 }
10358
Chris Lattner7da52b22006-11-01 04:51:18 +000010359 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010360 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010361 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10362 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10363 RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010364}
10365
Chris Lattner05f18922008-12-01 02:34:36 +000010366Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10367 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10368
10369 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10370 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010371 // This is true if all GEP bases are allocas and if all indices into them are
10372 // constants.
10373 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010374
10375 // Scan to see if all operands are the same opcode, all have one use, and all
10376 // kill their operands (i.e. the operands have one use).
10377 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10378 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10379 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10380 GEP->getNumOperands() != FirstInst->getNumOperands())
10381 return 0;
10382
Chris Lattner36d3e322009-02-21 00:46:50 +000010383 // Keep track of whether or not all GEPs are of alloca pointers.
10384 if (AllBasePointersAreAllocas &&
10385 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10386 !GEP->hasAllConstantIndices()))
10387 AllBasePointersAreAllocas = false;
10388
Chris Lattner05f18922008-12-01 02:34:36 +000010389 // Compare the operand lists.
10390 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10391 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10392 continue;
10393
10394 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10395 // if one of the PHIs has a constant for the index. The index may be
10396 // substantially cheaper to compute for the constants, so making it a
10397 // variable index could pessimize the path. This also handles the case
10398 // for struct indices, which must always be constant.
10399 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10400 isa<ConstantInt>(GEP->getOperand(op)))
10401 return 0;
10402
10403 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10404 return 0;
10405 FixedOperands[op] = 0; // Needs a PHI.
10406 }
10407 }
10408
Chris Lattner36d3e322009-02-21 00:46:50 +000010409 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010410 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010411 // offset calculation, but all the predecessors will have to materialize the
10412 // stack address into a register anyway. We'd actually rather *clone* the
10413 // load up into the predecessors so that we have a load of a gep of an alloca,
10414 // which can usually all be folded into the load.
10415 if (AllBasePointersAreAllocas)
10416 return 0;
10417
Chris Lattner05f18922008-12-01 02:34:36 +000010418 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10419 // that is variable.
10420 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10421
10422 bool HasAnyPHIs = false;
10423 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10424 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10425 Value *FirstOp = FirstInst->getOperand(i);
10426 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10427 FirstOp->getName()+".pn");
10428 InsertNewInstBefore(NewPN, PN);
10429
10430 NewPN->reserveOperandSpace(e);
10431 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10432 OperandPhis[i] = NewPN;
10433 FixedOperands[i] = NewPN;
10434 HasAnyPHIs = true;
10435 }
10436
10437
10438 // Add all operands to the new PHIs.
10439 if (HasAnyPHIs) {
10440 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10441 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10442 BasicBlock *InBB = PN.getIncomingBlock(i);
10443
10444 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10445 if (PHINode *OpPhi = OperandPhis[op])
10446 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10447 }
10448 }
10449
10450 Value *Base = FixedOperands[0];
10451 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10452 FixedOperands.end());
10453}
10454
10455
Chris Lattner21550882009-02-23 05:56:17 +000010456/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10457/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010458/// obvious the value of the load is not changed from the point of the load to
10459/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010460///
10461/// Finally, it is safe, but not profitable, to sink a load targetting a
10462/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10463/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010464static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010465 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10466
10467 for (++BBI; BBI != E; ++BBI)
10468 if (BBI->mayWriteToMemory())
10469 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010470
10471 // Check for non-address taken alloca. If not address-taken already, it isn't
10472 // profitable to do this xform.
10473 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10474 bool isAddressTaken = false;
10475 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10476 UI != E; ++UI) {
10477 if (isa<LoadInst>(UI)) continue;
10478 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10479 // If storing TO the alloca, then the address isn't taken.
10480 if (SI->getOperand(1) == AI) continue;
10481 }
10482 isAddressTaken = true;
10483 break;
10484 }
10485
Chris Lattner36d3e322009-02-21 00:46:50 +000010486 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010487 return false;
10488 }
10489
Chris Lattner36d3e322009-02-21 00:46:50 +000010490 // If this load is a load from a GEP with a constant offset from an alloca,
10491 // then we don't want to sink it. In its present form, it will be
10492 // load [constant stack offset]. Sinking it will cause us to have to
10493 // materialize the stack addresses in each predecessor in a register only to
10494 // do a shared load from register in the successor.
10495 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10496 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10497 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10498 return false;
10499
Chris Lattner76c73142006-11-01 07:13:54 +000010500 return true;
10501}
10502
Chris Lattner9fe38862003-06-19 17:00:31 +000010503
Chris Lattnerbac32862004-11-14 19:13:23 +000010504// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10505// operator and they all are only used by the PHI, PHI together their
10506// inputs, and do the operation once, to the result of the PHI.
10507Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10508 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10509
10510 // Scan the instruction, looking for input operations that can be folded away.
10511 // If all input operands to the phi are the same instruction (e.g. a cast from
10512 // the same type or "+42") we can pull the operation through the PHI, reducing
10513 // code size and simplifying code.
10514 Constant *ConstantOp = 0;
10515 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010516 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010517 if (isa<CastInst>(FirstInst)) {
10518 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010519 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010520 // Can fold binop, compare or shift here if the RHS is a constant,
10521 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010522 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010523 if (ConstantOp == 0)
10524 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010525 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10526 isVolatile = LI->isVolatile();
10527 // We can't sink the load if the loaded value could be modified between the
10528 // load and the PHI.
10529 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010530 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010531 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010532
10533 // If the PHI is of volatile loads and the load block has multiple
10534 // successors, sinking it would remove a load of the volatile value from
10535 // the path through the other successor.
10536 if (isVolatile &&
10537 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10538 return 0;
10539
Chris Lattner9c080502006-11-01 07:43:41 +000010540 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010541 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010542 } else {
10543 return 0; // Cannot fold this operation.
10544 }
10545
10546 // Check to see if all arguments are the same operation.
10547 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10548 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10549 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010550 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010551 return 0;
10552 if (CastSrcTy) {
10553 if (I->getOperand(0)->getType() != CastSrcTy)
10554 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010555 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010556 // We can't sink the load if the loaded value could be modified between
10557 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010558 if (LI->isVolatile() != isVolatile ||
10559 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010560 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010561 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010562
Chris Lattner71042962008-07-08 17:18:32 +000010563 // If the PHI is of volatile loads and the load block has multiple
10564 // successors, sinking it would remove a load of the volatile value from
10565 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010566 if (isVolatile &&
10567 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10568 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010569
Chris Lattnerbac32862004-11-14 19:13:23 +000010570 } else if (I->getOperand(1) != ConstantOp) {
10571 return 0;
10572 }
10573 }
10574
10575 // Okay, they are all the same operation. Create a new PHI node of the
10576 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010577 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10578 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010579 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010580
10581 Value *InVal = FirstInst->getOperand(0);
10582 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010583
10584 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010585 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10586 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10587 if (NewInVal != InVal)
10588 InVal = 0;
10589 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10590 }
10591
10592 Value *PhiVal;
10593 if (InVal) {
10594 // The new PHI unions all of the same values together. This is really
10595 // common, so we handle it intelligently here for compile-time speed.
10596 PhiVal = InVal;
10597 delete NewPN;
10598 } else {
10599 InsertNewInstBefore(NewPN, PN);
10600 PhiVal = NewPN;
10601 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010602
Chris Lattnerbac32862004-11-14 19:13:23 +000010603 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010604 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010605 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010606 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010607 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010608 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010609 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010610 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010611 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10612
10613 // If this was a volatile load that we are merging, make sure to loop through
10614 // and mark all the input loads as non-volatile. If we don't do this, we will
10615 // insert a new volatile load and the old ones will not be deletable.
10616 if (isVolatile)
10617 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10618 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10619
10620 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010621}
Chris Lattnera1be5662002-05-02 17:06:02 +000010622
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010623/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10624/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010625static bool DeadPHICycle(PHINode *PN,
10626 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010627 if (PN->use_empty()) return true;
10628 if (!PN->hasOneUse()) return false;
10629
10630 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010631 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010632 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010633
10634 // Don't scan crazily complex things.
10635 if (PotentiallyDeadPHIs.size() == 16)
10636 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010637
10638 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10639 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010640
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010641 return false;
10642}
10643
Chris Lattnercf5008a2007-11-06 21:52:06 +000010644/// PHIsEqualValue - Return true if this phi node is always equal to
10645/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10646/// z = some value; x = phi (y, z); y = phi (x, z)
10647static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10648 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10649 // See if we already saw this PHI node.
10650 if (!ValueEqualPHIs.insert(PN))
10651 return true;
10652
10653 // Don't scan crazily complex things.
10654 if (ValueEqualPHIs.size() == 16)
10655 return false;
10656
10657 // Scan the operands to see if they are either phi nodes or are equal to
10658 // the value.
10659 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10660 Value *Op = PN->getIncomingValue(i);
10661 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10662 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10663 return false;
10664 } else if (Op != NonPhiInVal)
10665 return false;
10666 }
10667
10668 return true;
10669}
10670
10671
Chris Lattner473945d2002-05-06 18:06:38 +000010672// PHINode simplification
10673//
Chris Lattner7e708292002-06-25 16:13:24 +000010674Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010675 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010676 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010677
Owen Anderson7e057142006-07-10 22:03:18 +000010678 if (Value *V = PN.hasConstantValue())
10679 return ReplaceInstUsesWith(PN, V);
10680
Owen Anderson7e057142006-07-10 22:03:18 +000010681 // If all PHI operands are the same operation, pull them through the PHI,
10682 // reducing code size.
10683 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010684 isa<Instruction>(PN.getIncomingValue(1)) &&
10685 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10686 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10687 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10688 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010689 PN.getIncomingValue(0)->hasOneUse())
10690 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10691 return Result;
10692
10693 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10694 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10695 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010696 if (PN.hasOneUse()) {
10697 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10698 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010699 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010700 PotentiallyDeadPHIs.insert(&PN);
10701 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10702 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10703 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010704
10705 // If this phi has a single use, and if that use just computes a value for
10706 // the next iteration of a loop, delete the phi. This occurs with unused
10707 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10708 // common case here is good because the only other things that catch this
10709 // are induction variable analysis (sometimes) and ADCE, which is only run
10710 // late.
10711 if (PHIUser->hasOneUse() &&
10712 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10713 PHIUser->use_back() == &PN) {
10714 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10715 }
10716 }
Owen Anderson7e057142006-07-10 22:03:18 +000010717
Chris Lattnercf5008a2007-11-06 21:52:06 +000010718 // We sometimes end up with phi cycles that non-obviously end up being the
10719 // same value, for example:
10720 // z = some value; x = phi (y, z); y = phi (x, z)
10721 // where the phi nodes don't necessarily need to be in the same block. Do a
10722 // quick check to see if the PHI node only contains a single non-phi value, if
10723 // so, scan to see if the phi cycle is actually equal to that value.
10724 {
10725 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10726 // Scan for the first non-phi operand.
10727 while (InValNo != NumOperandVals &&
10728 isa<PHINode>(PN.getIncomingValue(InValNo)))
10729 ++InValNo;
10730
10731 if (InValNo != NumOperandVals) {
10732 Value *NonPhiInVal = PN.getOperand(InValNo);
10733
10734 // Scan the rest of the operands to see if there are any conflicts, if so
10735 // there is no need to recursively scan other phis.
10736 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10737 Value *OpVal = PN.getIncomingValue(InValNo);
10738 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10739 break;
10740 }
10741
10742 // If we scanned over all operands, then we have one unique value plus
10743 // phi values. Scan PHI nodes to see if they all merge in each other or
10744 // the value.
10745 if (InValNo == NumOperandVals) {
10746 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10747 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10748 return ReplaceInstUsesWith(PN, NonPhiInVal);
10749 }
10750 }
10751 }
Chris Lattner60921c92003-12-19 05:58:40 +000010752 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010753}
10754
Reid Spencer17212df2006-12-12 09:18:51 +000010755static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10756 Instruction *InsertPoint,
10757 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010758 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10759 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010760 // We must cast correctly to the pointer type. Ensure that we
10761 // sign extend the integer value if it is smaller as this is
10762 // used for address computation.
10763 Instruction::CastOps opcode =
10764 (VTySize < PtrSize ? Instruction::SExt :
10765 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10766 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010767}
10768
Chris Lattnera1be5662002-05-02 17:06:02 +000010769
Chris Lattner7e708292002-06-25 16:13:24 +000010770Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010771 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010772 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010773 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010774 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010775 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010776
Chris Lattnere87597f2004-10-16 18:11:37 +000010777 if (isa<UndefValue>(GEP.getOperand(0)))
10778 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10779
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010780 bool HasZeroPointerIndex = false;
10781 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10782 HasZeroPointerIndex = C->isNullValue();
10783
10784 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010785 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010786
Chris Lattner28977af2004-04-05 01:30:19 +000010787 // Eliminate unneeded casts for indices.
10788 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010789
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010790 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010791 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10792 i != e; ++i, ++GTI) {
Sanjiv Gupta7787d4a2009-04-24 02:37:54 +000010793 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010794 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010795 if (CI->getOpcode() == Instruction::ZExt ||
10796 CI->getOpcode() == Instruction::SExt) {
10797 const Type *SrcTy = CI->getOperand(0)->getType();
10798 // We can eliminate a cast from i32 to i64 iff the target
10799 // is a 32-bit pointer target.
10800 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10801 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010802 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010803 }
10804 }
10805 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010806 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010807 // to what we need. If narrower, sign-extend it to what we need.
10808 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010809 // insert it. This explicit cast can make subsequent optimizations more
10810 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010811 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010812 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010813 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010814 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010815 MadeChange = true;
10816 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010817 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10818 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010819 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010820 MadeChange = true;
10821 }
Dan Gohman4f833d42008-09-11 23:06:38 +000010822 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10823 if (Constant *C = dyn_cast<Constant>(Op)) {
10824 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10825 MadeChange = true;
10826 } else {
10827 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10828 GEP);
10829 *i = Op;
10830 MadeChange = true;
10831 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010832 }
Chris Lattner28977af2004-04-05 01:30:19 +000010833 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010834 }
Chris Lattner28977af2004-04-05 01:30:19 +000010835 if (MadeChange) return &GEP;
10836
Chris Lattner90ac28c2002-08-02 19:29:35 +000010837 // Combine Indices - If the source pointer to this getelementptr instruction
10838 // is a getelementptr instruction, combine the indices of the two
10839 // getelementptr instructions into a single instruction.
10840 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010841 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010842 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010843 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010844
10845 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010846 // Note that if our source is a gep chain itself that we wait for that
10847 // chain to be resolved before we perform this transformation. This
10848 // avoids us creating a TON of code in some cases.
10849 //
10850 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10851 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10852 return 0; // Wait until our source is folded to completion.
10853
Chris Lattner72588fc2007-02-15 22:48:32 +000010854 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010855
10856 // Find out whether the last index in the source GEP is a sequential idx.
10857 bool EndsWithSequential = false;
10858 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10859 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010860 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010861
Chris Lattner90ac28c2002-08-02 19:29:35 +000010862 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010863 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010864 // Replace: gep (gep %P, long B), long A, ...
10865 // With: T = long A+B; gep %P, T, ...
10866 //
Chris Lattner620ce142004-05-07 22:09:22 +000010867 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010868 if (SO1 == Constant::getNullValue(SO1->getType())) {
10869 Sum = GO1;
10870 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10871 Sum = SO1;
10872 } else {
10873 // If they aren't the same type, convert both to an integer of the
10874 // target's pointer size.
10875 if (SO1->getType() != GO1->getType()) {
10876 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010877 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010878 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010879 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010880 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010881 unsigned PS = TD->getPointerSizeInBits();
10882 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010883 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010884 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010885
Duncan Sands514ab342007-11-01 20:53:16 +000010886 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010887 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010888 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010889 } else {
10890 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010891 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10892 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010893 }
10894 }
10895 }
Chris Lattner620ce142004-05-07 22:09:22 +000010896 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10897 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10898 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010899 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010900 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010901 }
Chris Lattner28977af2004-04-05 01:30:19 +000010902 }
Chris Lattner620ce142004-05-07 22:09:22 +000010903
10904 // Recycle the GEP we already have if possible.
10905 if (SrcGEPOperands.size() == 2) {
10906 GEP.setOperand(0, SrcGEPOperands[0]);
10907 GEP.setOperand(1, Sum);
10908 return &GEP;
10909 } else {
10910 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10911 SrcGEPOperands.end()-1);
10912 Indices.push_back(Sum);
10913 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10914 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010915 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010916 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010917 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010918 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010919 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10920 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010921 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10922 }
10923
10924 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010925 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10926 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010927
Chris Lattner620ce142004-05-07 22:09:22 +000010928 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010929 // GEP of global variable. If all of the indices for this GEP are
10930 // constants, we can promote this to a constexpr instead of an instruction.
10931
10932 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010933 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010934 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10935 for (; I != E && isa<Constant>(*I); ++I)
10936 Indices.push_back(cast<Constant>(*I));
10937
10938 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010939 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10940 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010941
10942 // Replace all uses of the GEP with the new constexpr...
10943 return ReplaceInstUsesWith(GEP, CE);
10944 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010945 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010946 if (!isa<PointerType>(X->getType())) {
10947 // Not interesting. Source pointer must be a cast from pointer.
10948 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010949 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10950 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010951 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010952 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10953 // into : GEP i8* X, ...
10954 //
Chris Lattnereed48272005-09-13 00:40:14 +000010955 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000010956 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10957 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010958 if (const ArrayType *CATy =
10959 dyn_cast<ArrayType>(CPTy->getElementType())) {
10960 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10961 if (CATy->getElementType() == XTy->getElementType()) {
10962 // -> GEP i8* X, ...
10963 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10964 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10965 GEP.getName());
10966 } else if (const ArrayType *XATy =
10967 dyn_cast<ArrayType>(XTy->getElementType())) {
10968 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000010969 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010970 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010971 // At this point, we know that the cast source type is a pointer
10972 // to an array of the same type as the destination pointer
10973 // array. Because the array type is never stepped over (there
10974 // is a leading zero) we can fold the cast into this GEP.
10975 GEP.setOperand(0, X);
10976 return &GEP;
10977 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010978 }
10979 }
Chris Lattnereed48272005-09-13 00:40:14 +000010980 } else if (GEP.getNumOperands() == 2) {
10981 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010982 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10983 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010984 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10985 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10986 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000010987 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10988 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010989 Value *Idx[2];
10990 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10991 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010992 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010993 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010994 // V and GEP are both pointer types --> BitCast
10995 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010996 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010997
10998 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010999 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011000 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011001 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011002
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011003 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011004 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011005 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011006
11007 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11008 // allow either a mul, shift, or constant here.
11009 Value *NewIdx = 0;
11010 ConstantInt *Scale = 0;
11011 if (ArrayEltSize == 1) {
11012 NewIdx = GEP.getOperand(1);
11013 Scale = ConstantInt::get(NewIdx->getType(), 1);
11014 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000011015 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011016 Scale = CI;
11017 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11018 if (Inst->getOpcode() == Instruction::Shl &&
11019 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011020 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11021 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11022 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011023 NewIdx = Inst->getOperand(0);
11024 } else if (Inst->getOpcode() == Instruction::Mul &&
11025 isa<ConstantInt>(Inst->getOperand(1))) {
11026 Scale = cast<ConstantInt>(Inst->getOperand(1));
11027 NewIdx = Inst->getOperand(0);
11028 }
11029 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011030
Chris Lattner7835cdd2005-09-13 18:36:04 +000011031 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011032 // out, perform the transformation. Note, we don't know whether Scale is
11033 // signed or not. We'll use unsigned version of division/modulo
11034 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011035 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011036 Scale->getZExtValue() % ArrayEltSize == 0) {
11037 Scale = ConstantInt::get(Scale->getType(),
11038 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011039 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000011040 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011041 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011042 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011043 NewIdx = InsertNewInstBefore(Sc, GEP);
11044 }
11045
11046 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011047 Value *Idx[2];
11048 Idx[0] = Constant::getNullValue(Type::Int32Ty);
11049 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011050 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011051 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011052 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11053 // The NewGEP must be pointer typed, so must the old one -> BitCast
11054 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011055 }
11056 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011057 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011058 }
Chris Lattner58407792009-01-09 04:53:57 +000011059
Chris Lattner46cd5a12009-01-09 05:44:56 +000011060 /// See if we can simplify:
11061 /// X = bitcast A to B*
11062 /// Y = gep X, <...constant indices...>
11063 /// into a gep of the original struct. This is important for SROA and alias
11064 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011065 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011066 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11067 // Determine how much the GEP moves the pointer. We are guaranteed to get
11068 // a constant back from EmitGEPOffset.
11069 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11070 int64_t Offset = OffsetV->getSExtValue();
11071
11072 // If this GEP instruction doesn't move the pointer, just replace the GEP
11073 // with a bitcast of the real input to the dest type.
11074 if (Offset == 0) {
11075 // If the bitcast is of an allocation, and the allocation will be
11076 // converted to match the type of the cast, don't touch this.
11077 if (isa<AllocationInst>(BCI->getOperand(0))) {
11078 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11079 if (Instruction *I = visitBitCast(*BCI)) {
11080 if (I != BCI) {
11081 I->takeName(BCI);
11082 BCI->getParent()->getInstList().insert(BCI, I);
11083 ReplaceInstUsesWith(*BCI, I);
11084 }
11085 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011086 }
Chris Lattner58407792009-01-09 04:53:57 +000011087 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011088 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011089 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011090
11091 // Otherwise, if the offset is non-zero, we need to find out if there is a
11092 // field at Offset in 'A's type. If so, we can pull the cast through the
11093 // GEP.
11094 SmallVector<Value*, 8> NewIndices;
11095 const Type *InTy =
11096 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11097 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11098 Instruction *NGEP =
11099 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11100 NewIndices.end());
11101 if (NGEP->getType() == GEP.getType()) return NGEP;
11102 InsertNewInstBefore(NGEP, GEP);
11103 NGEP->takeName(&GEP);
11104 return new BitCastInst(NGEP, GEP.getType());
11105 }
Chris Lattner58407792009-01-09 04:53:57 +000011106 }
11107 }
11108
Chris Lattner8a2a3112001-12-14 16:52:21 +000011109 return 0;
11110}
11111
Chris Lattner0864acf2002-11-04 16:18:53 +000011112Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11113 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011114 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011115 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11116 const Type *NewTy =
11117 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011118 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011119
11120 // Create and insert the replacement instruction...
11121 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000011122 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011123 else {
11124 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000011125 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011126 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011127
11128 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011129
Chris Lattner0864acf2002-11-04 16:18:53 +000011130 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011131 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011132 //
11133 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011134 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011135
11136 // Now that I is pointing to the first non-allocation-inst in the block,
11137 // insert our getelementptr instruction...
11138 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000011139 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011140 Value *Idx[2];
11141 Idx[0] = NullIdx;
11142 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011143 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11144 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011145
11146 // Now make everything use the getelementptr instead of the original
11147 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011148 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011149 } else if (isa<UndefValue>(AI.getArraySize())) {
11150 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011151 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011152 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011153
Dan Gohman6893cd72009-01-13 20:18:38 +000011154 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11155 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011156 // Note that we only do this for alloca's, because malloc should allocate
11157 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011158 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Dan Gohman6893cd72009-01-13 20:18:38 +000011159 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11160
11161 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11162 if (AI.getAlignment() == 0)
11163 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11164 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011165
Chris Lattner0864acf2002-11-04 16:18:53 +000011166 return 0;
11167}
11168
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011169Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11170 Value *Op = FI.getOperand(0);
11171
Chris Lattner17be6352004-10-18 02:59:09 +000011172 // free undef -> unreachable.
11173 if (isa<UndefValue>(Op)) {
11174 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000011175 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011176 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011177 return EraseInstFromFunction(FI);
11178 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011179
Chris Lattner6160e852004-02-28 04:57:37 +000011180 // If we have 'free null' delete the instruction. This can happen in stl code
11181 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011182 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011183 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011184
11185 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11186 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11187 FI.setOperand(0, CI->getOperand(0));
11188 return &FI;
11189 }
11190
11191 // Change free (gep X, 0,0,0,0) into free(X)
11192 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11193 if (GEPI->hasAllZeroIndices()) {
11194 AddToWorkList(GEPI);
11195 FI.setOperand(0, GEPI->getOperand(0));
11196 return &FI;
11197 }
11198 }
11199
11200 // Change free(malloc) into nothing, if the malloc has a single use.
11201 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11202 if (MI->hasOneUse()) {
11203 EraseInstFromFunction(FI);
11204 return EraseInstFromFunction(*MI);
11205 }
Chris Lattner6160e852004-02-28 04:57:37 +000011206
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011207 return 0;
11208}
11209
11210
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011211/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011212static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011213 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011214 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011215 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000011216
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011217 if (TD) {
11218 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11219 // Instead of loading constant c string, use corresponding integer value
11220 // directly if string length is small enough.
11221 std::string Str;
11222 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11223 unsigned len = Str.length();
11224 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11225 unsigned numBits = Ty->getPrimitiveSizeInBits();
11226 // Replace LI with immediate integer store.
11227 if ((numBits >> 3) == len + 1) {
11228 APInt StrVal(numBits, 0);
11229 APInt SingleChar(numBits, 0);
11230 if (TD->isLittleEndian()) {
11231 for (signed i = len-1; i >= 0; i--) {
11232 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11233 StrVal = (StrVal << 8) | SingleChar;
11234 }
11235 } else {
11236 for (unsigned i = 0; i < len; i++) {
11237 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11238 StrVal = (StrVal << 8) | SingleChar;
11239 }
11240 // Append NULL at the end.
11241 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011242 StrVal = (StrVal << 8) | SingleChar;
11243 }
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011244 Value *NL = ConstantInt::get(StrVal);
11245 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011246 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011247 }
11248 }
11249 }
11250
Mon P Wang6753f952009-02-07 22:19:29 +000011251 const PointerType *DestTy = cast<PointerType>(CI->getType());
11252 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011253 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011254
11255 // If the address spaces don't match, don't eliminate the cast.
11256 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11257 return 0;
11258
Chris Lattnerb89e0712004-07-13 01:49:43 +000011259 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011260
Reid Spencer42230162007-01-22 05:51:25 +000011261 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011262 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011263 // If the source is an array, the code below will not succeed. Check to
11264 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11265 // constants.
11266 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11267 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11268 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011269 Value *Idxs[2];
11270 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11271 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011272 SrcTy = cast<PointerType>(CastOp->getType());
11273 SrcPTy = SrcTy->getElementType();
11274 }
11275
Reid Spencer42230162007-01-22 05:51:25 +000011276 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011277 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011278 // Do not allow turning this into a load of an integer, which is then
11279 // casted to a pointer, this pessimizes pointer analysis a lot.
11280 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011281 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11282 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011283
Chris Lattnerf9527852005-01-31 04:50:46 +000011284 // Okay, we are casting from one integer or pointer type to another of
11285 // the same size. Instead of casting the pointer before the load, cast
11286 // the result of the loaded value.
11287 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11288 CI->getName(),
11289 LI.isVolatile()),LI);
11290 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011291 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011292 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011293 }
11294 }
11295 return 0;
11296}
11297
Chris Lattnerc10aced2004-09-19 18:43:46 +000011298/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000011299/// from this value cannot trap. If it is not obviously safe to load from the
11300/// specified pointer, we do a quick local scan of the basic block containing
11301/// ScanFrom, to determine if the address is already accessed.
11302static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000011303 // If it is an alloca it is always safe to load from.
11304 if (isa<AllocaInst>(V)) return true;
11305
Duncan Sands46318cd2007-09-19 10:25:38 +000011306 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000011307 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000011308 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000011309 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000011310
11311 // Otherwise, be a little bit agressive by scanning the local block where we
11312 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011313 // from/to. If so, the previous load or store would have already trapped,
11314 // so there is no harm doing an extra load (also, CSE will later eliminate
11315 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000011316 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11317
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011318 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000011319 --BBI;
11320
Chris Lattner2de3fec2008-06-20 05:12:56 +000011321 // If we see a free or a call (which might do a free) the pointer could be
11322 // marked invalid.
Dale Johannesend1c135c2009-03-13 19:23:20 +000011323 if (isa<FreeInst>(BBI) ||
11324 (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)))
Chris Lattner2de3fec2008-06-20 05:12:56 +000011325 return false;
11326
Chris Lattner8a375202004-09-19 19:18:10 +000011327 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11328 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011329 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000011330 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011331 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011332
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011333 }
Chris Lattner8a375202004-09-19 19:18:10 +000011334 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000011335}
11336
Chris Lattner833b8a42003-06-26 05:06:25 +000011337Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11338 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011339
Dan Gohman9941f742007-07-20 16:34:21 +000011340 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011341 unsigned KnownAlign =
11342 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011343 if (KnownAlign >
11344 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11345 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011346 LI.setAlignment(KnownAlign);
11347
Chris Lattner37366c12005-05-01 04:24:53 +000011348 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011349 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011350 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011351 return Res;
11352
11353 // None of the following transforms are legal for volatile loads.
11354 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011355
Dan Gohman2276a7b2008-10-15 23:19:35 +000011356 // Do really simple store-to-load forwarding and load CSE, to catch cases
11357 // where there are several consequtive memory accesses to the same location,
11358 // separated by a few arithmetic operations.
11359 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011360 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11361 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011362
Christopher Lambb15147e2007-12-29 07:56:53 +000011363 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11364 const Value *GEPI0 = GEPI->getOperand(0);
11365 // TODO: Consider a target hook for valid address spaces for this xform.
11366 if (isa<ConstantPointerNull>(GEPI0) &&
11367 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011368 // Insert a new store to null instruction before the load to indicate
11369 // that this code is not reachable. We do this instead of inserting
11370 // an unreachable instruction directly because we cannot modify the
11371 // CFG.
11372 new StoreInst(UndefValue::get(LI.getType()),
11373 Constant::getNullValue(Op->getType()), &LI);
11374 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11375 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011376 }
Chris Lattner37366c12005-05-01 04:24:53 +000011377
Chris Lattnere87597f2004-10-16 18:11:37 +000011378 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011379 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011380 // TODO: Consider a target hook for valid address spaces for this xform.
11381 if (isa<UndefValue>(C) || (C->isNullValue() &&
11382 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011383 // Insert a new store to null instruction before the load to indicate that
11384 // this code is not reachable. We do this instead of inserting an
11385 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000011386 new StoreInst(UndefValue::get(LI.getType()),
11387 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000011388 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011389 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011390
Chris Lattnere87597f2004-10-16 18:11:37 +000011391 // Instcombine load (constant global) into the value loaded.
11392 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011393 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011394 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011395
Chris Lattnere87597f2004-10-16 18:11:37 +000011396 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011397 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011398 if (CE->getOpcode() == Instruction::GetElementPtr) {
11399 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011400 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011401 if (Constant *V =
11402 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011403 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011404 if (CE->getOperand(0)->isNullValue()) {
11405 // Insert a new store to null instruction before the load to indicate
11406 // that this code is not reachable. We do this instead of inserting
11407 // an unreachable instruction directly because we cannot modify the
11408 // CFG.
11409 new StoreInst(UndefValue::get(LI.getType()),
11410 Constant::getNullValue(Op->getType()), &LI);
11411 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11412 }
11413
Reid Spencer3da59db2006-11-27 01:05:10 +000011414 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011415 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011416 return Res;
11417 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011418 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011419 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011420
11421 // If this load comes from anywhere in a constant global, and if the global
11422 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011423 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011424 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011425 if (GV->getInitializer()->isNullValue())
11426 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11427 else if (isa<UndefValue>(GV->getInitializer()))
11428 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11429 }
11430 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011431
Chris Lattner37366c12005-05-01 04:24:53 +000011432 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011433 // Change select and PHI nodes to select values instead of addresses: this
11434 // helps alias analysis out a lot, allows many others simplifications, and
11435 // exposes redundancy in the code.
11436 //
11437 // Note that we cannot do the transformation unless we know that the
11438 // introduced loads cannot trap! Something like this is valid as long as
11439 // the condition is always false: load (select bool %C, int* null, int* %G),
11440 // but it would not be valid if we transformed it to load from null
11441 // unconditionally.
11442 //
11443 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11444 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011445 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11446 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011447 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011448 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011449 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011450 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011451 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011452 }
11453
Chris Lattner684fe212004-09-23 15:46:00 +000011454 // load (select (cond, null, P)) -> load P
11455 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11456 if (C->isNullValue()) {
11457 LI.setOperand(0, SI->getOperand(2));
11458 return &LI;
11459 }
11460
11461 // load (select (cond, P, null)) -> load P
11462 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11463 if (C->isNullValue()) {
11464 LI.setOperand(0, SI->getOperand(1));
11465 return &LI;
11466 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011467 }
11468 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011469 return 0;
11470}
11471
Reid Spencer55af2b52007-01-19 21:20:31 +000011472/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011473/// when possible. This makes it generally easy to do alias analysis and/or
11474/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011475static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11476 User *CI = cast<User>(SI.getOperand(1));
11477 Value *CastOp = CI->getOperand(0);
11478
11479 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011480 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11481 if (SrcTy == 0) return 0;
11482
11483 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011484
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011485 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11486 return 0;
11487
Chris Lattner3914f722009-01-24 01:00:13 +000011488 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11489 /// to its first element. This allows us to handle things like:
11490 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11491 /// on 32-bit hosts.
11492 SmallVector<Value*, 4> NewGEPIndices;
11493
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011494 // If the source is an array, the code below will not succeed. Check to
11495 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11496 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011497 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11498 // Index through pointer.
11499 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11500 NewGEPIndices.push_back(Zero);
11501
11502 while (1) {
11503 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011504 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011505 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011506 NewGEPIndices.push_back(Zero);
11507 SrcPTy = STy->getElementType(0);
11508 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11509 NewGEPIndices.push_back(Zero);
11510 SrcPTy = ATy->getElementType();
11511 } else {
11512 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011513 }
Chris Lattner3914f722009-01-24 01:00:13 +000011514 }
11515
11516 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11517 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011518
11519 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11520 return 0;
11521
Chris Lattner71759c42009-01-16 20:12:52 +000011522 // If the pointers point into different address spaces or if they point to
11523 // values with different sizes, we can't do the transformation.
11524 if (SrcTy->getAddressSpace() !=
11525 cast<PointerType>(CI->getType())->getAddressSpace() ||
11526 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011527 IC.getTargetData().getTypeSizeInBits(DestPTy))
11528 return 0;
11529
11530 // Okay, we are casting from one integer or pointer type to another of
11531 // the same size. Instead of casting the pointer before
11532 // the store, cast the value to be stored.
11533 Value *NewCast;
11534 Value *SIOp0 = SI.getOperand(0);
11535 Instruction::CastOps opcode = Instruction::BitCast;
11536 const Type* CastSrcTy = SIOp0->getType();
11537 const Type* CastDstTy = SrcPTy;
11538 if (isa<PointerType>(CastDstTy)) {
11539 if (CastSrcTy->isInteger())
11540 opcode = Instruction::IntToPtr;
11541 } else if (isa<IntegerType>(CastDstTy)) {
11542 if (isa<PointerType>(SIOp0->getType()))
11543 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011544 }
Chris Lattner3914f722009-01-24 01:00:13 +000011545
11546 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11547 // emit a GEP to index into its first field.
11548 if (!NewGEPIndices.empty()) {
11549 if (Constant *C = dyn_cast<Constant>(CastOp))
11550 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11551 NewGEPIndices.size());
11552 else
11553 CastOp = IC.InsertNewInstBefore(
11554 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11555 NewGEPIndices.end()), SI);
11556 }
11557
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011558 if (Constant *C = dyn_cast<Constant>(SIOp0))
11559 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11560 else
11561 NewCast = IC.InsertNewInstBefore(
11562 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11563 SI);
11564 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011565}
11566
Chris Lattner4aebaee2008-11-27 08:56:30 +000011567/// equivalentAddressValues - Test if A and B will obviously have the same
11568/// value. This includes recognizing that %t0 and %t1 will have the same
11569/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011570/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011571/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011572/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011573/// %t2 = load i32* %t1
11574///
11575static bool equivalentAddressValues(Value *A, Value *B) {
11576 // Test if the values are trivially equivalent.
11577 if (A == B) return true;
11578
11579 // Test if the values come form identical arithmetic instructions.
11580 if (isa<BinaryOperator>(A) ||
11581 isa<CastInst>(A) ||
11582 isa<PHINode>(A) ||
11583 isa<GetElementPtrInst>(A))
11584 if (Instruction *BI = dyn_cast<Instruction>(B))
11585 if (cast<Instruction>(A)->isIdenticalTo(BI))
11586 return true;
11587
11588 // Otherwise they may not be equivalent.
11589 return false;
11590}
11591
Dale Johannesen4945c652009-03-03 21:26:39 +000011592// If this instruction has two uses, one of which is a llvm.dbg.declare,
11593// return the llvm.dbg.declare.
11594DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11595 if (!V->hasNUses(2))
11596 return 0;
11597 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11598 UI != E; ++UI) {
11599 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11600 return DI;
11601 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11602 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11603 return DI;
11604 }
11605 }
11606 return 0;
11607}
11608
Chris Lattner2f503e62005-01-31 05:36:43 +000011609Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11610 Value *Val = SI.getOperand(0);
11611 Value *Ptr = SI.getOperand(1);
11612
11613 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011614 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011615 ++NumCombined;
11616 return 0;
11617 }
Chris Lattner836692d2007-01-15 06:51:56 +000011618
11619 // If the RHS is an alloca with a single use, zapify the store, making the
11620 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011621 // If the RHS is an alloca with a two uses, the other one being a
11622 // llvm.dbg.declare, zapify the store and the declare, making the
11623 // alloca dead. We must do this to prevent declare's from affecting
11624 // codegen.
11625 if (!SI.isVolatile()) {
11626 if (Ptr->hasOneUse()) {
11627 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011628 EraseInstFromFunction(SI);
11629 ++NumCombined;
11630 return 0;
11631 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011632 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11633 if (isa<AllocaInst>(GEP->getOperand(0))) {
11634 if (GEP->getOperand(0)->hasOneUse()) {
11635 EraseInstFromFunction(SI);
11636 ++NumCombined;
11637 return 0;
11638 }
11639 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11640 EraseInstFromFunction(*DI);
11641 EraseInstFromFunction(SI);
11642 ++NumCombined;
11643 return 0;
11644 }
11645 }
11646 }
11647 }
11648 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11649 EraseInstFromFunction(*DI);
11650 EraseInstFromFunction(SI);
11651 ++NumCombined;
11652 return 0;
11653 }
Chris Lattner836692d2007-01-15 06:51:56 +000011654 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011655
Dan Gohman9941f742007-07-20 16:34:21 +000011656 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011657 unsigned KnownAlign =
11658 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011659 if (KnownAlign >
11660 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11661 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011662 SI.setAlignment(KnownAlign);
11663
Dale Johannesenacb51a32009-03-03 01:43:03 +000011664 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011665 // stores to the same location, separated by a few arithmetic operations. This
11666 // situation often occurs with bitfield accesses.
11667 BasicBlock::iterator BBI = &SI;
11668 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11669 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011670 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011671 // Don't count debug info directives, lest they affect codegen,
11672 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11673 // It is necessary for correctness to skip those that feed into a
11674 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011675 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011676 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011677 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011678 continue;
11679 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011680
11681 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11682 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011683 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11684 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011685 ++NumDeadStore;
11686 ++BBI;
11687 EraseInstFromFunction(*PrevSI);
11688 continue;
11689 }
11690 break;
11691 }
11692
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011693 // If this is a load, we have to stop. However, if the loaded value is from
11694 // the pointer we're loading and is producing the pointer we're storing,
11695 // then *this* store is dead (X = load P; store X -> P).
11696 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011697 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11698 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011699 EraseInstFromFunction(SI);
11700 ++NumCombined;
11701 return 0;
11702 }
11703 // Otherwise, this is a load from some other location. Stores before it
11704 // may not be dead.
11705 break;
11706 }
11707
Chris Lattner9ca96412006-02-08 03:25:32 +000011708 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011709 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011710 break;
11711 }
11712
11713
11714 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011715
11716 // store X, null -> turns into 'unreachable' in SimplifyCFG
11717 if (isa<ConstantPointerNull>(Ptr)) {
11718 if (!isa<UndefValue>(Val)) {
11719 SI.setOperand(0, UndefValue::get(Val->getType()));
11720 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011721 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011722 ++NumCombined;
11723 }
11724 return 0; // Do not modify these!
11725 }
11726
11727 // store undef, Ptr -> noop
11728 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011729 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011730 ++NumCombined;
11731 return 0;
11732 }
11733
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011734 // If the pointer destination is a cast, see if we can fold the cast into the
11735 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011736 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011737 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11738 return Res;
11739 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011740 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011741 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11742 return Res;
11743
Chris Lattner408902b2005-09-12 23:23:25 +000011744
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011745 // If this store is the last instruction in the basic block (possibly
11746 // excepting debug info instructions and the pointer bitcasts that feed
11747 // into them), and if the block ends with an unconditional branch, try
11748 // to move it to the successor block.
11749 BBI = &SI;
11750 do {
11751 ++BBI;
11752 } while (isa<DbgInfoIntrinsic>(BBI) ||
11753 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011754 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011755 if (BI->isUnconditional())
11756 if (SimplifyStoreAtEndOfBlock(SI))
11757 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011758
Chris Lattner2f503e62005-01-31 05:36:43 +000011759 return 0;
11760}
11761
Chris Lattner3284d1f2007-04-15 00:07:55 +000011762/// SimplifyStoreAtEndOfBlock - Turn things like:
11763/// if () { *P = v1; } else { *P = v2 }
11764/// into a phi node with a store in the successor.
11765///
Chris Lattner31755a02007-04-15 01:02:18 +000011766/// Simplify things like:
11767/// *P = v1; if () { *P = v2; }
11768/// into a phi node with a store in the successor.
11769///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011770bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11771 BasicBlock *StoreBB = SI.getParent();
11772
11773 // Check to see if the successor block has exactly two incoming edges. If
11774 // so, see if the other predecessor contains a store to the same location.
11775 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011776 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011777
11778 // Determine whether Dest has exactly two predecessors and, if so, compute
11779 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011780 pred_iterator PI = pred_begin(DestBB);
11781 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011782 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011783 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011784 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011785 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011786 return false;
11787
11788 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011789 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011790 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011791 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011792 }
Chris Lattner31755a02007-04-15 01:02:18 +000011793 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011794 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011795
11796 // Bail out if all the relevant blocks aren't distinct (this can happen,
11797 // for example, if SI is in an infinite loop)
11798 if (StoreBB == DestBB || OtherBB == DestBB)
11799 return false;
11800
Chris Lattner31755a02007-04-15 01:02:18 +000011801 // Verify that the other block ends in a branch and is not otherwise empty.
11802 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011803 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011804 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011805 return false;
11806
Chris Lattner31755a02007-04-15 01:02:18 +000011807 // If the other block ends in an unconditional branch, check for the 'if then
11808 // else' case. there is an instruction before the branch.
11809 StoreInst *OtherStore = 0;
11810 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011811 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011812 // Skip over debugging info.
11813 while (isa<DbgInfoIntrinsic>(BBI) ||
11814 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11815 if (BBI==OtherBB->begin())
11816 return false;
11817 --BBI;
11818 }
11819 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011820 OtherStore = dyn_cast<StoreInst>(BBI);
11821 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11822 return false;
11823 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011824 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011825 // destinations is StoreBB, then we have the if/then case.
11826 if (OtherBr->getSuccessor(0) != StoreBB &&
11827 OtherBr->getSuccessor(1) != StoreBB)
11828 return false;
11829
11830 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011831 // if/then triangle. See if there is a store to the same ptr as SI that
11832 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011833 for (;; --BBI) {
11834 // Check to see if we find the matching store.
11835 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11836 if (OtherStore->getOperand(1) != SI.getOperand(1))
11837 return false;
11838 break;
11839 }
Eli Friedman6903a242008-06-13 22:02:12 +000011840 // If we find something that may be using or overwriting the stored
11841 // value, or if we run out of instructions, we can't do the xform.
11842 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011843 BBI == OtherBB->begin())
11844 return false;
11845 }
11846
11847 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011848 // make sure nothing reads or overwrites the stored value in
11849 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011850 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11851 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011852 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011853 return false;
11854 }
11855 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011856
Chris Lattner31755a02007-04-15 01:02:18 +000011857 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011858 Value *MergedVal = OtherStore->getOperand(0);
11859 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011860 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011861 PN->reserveOperandSpace(2);
11862 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011863 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11864 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011865 }
11866
11867 // Advance to a place where it is safe to insert the new store and
11868 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011869 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011870 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11871 OtherStore->isVolatile()), *BBI);
11872
11873 // Nuke the old stores.
11874 EraseInstFromFunction(SI);
11875 EraseInstFromFunction(*OtherStore);
11876 ++NumCombined;
11877 return true;
11878}
11879
Chris Lattner2f503e62005-01-31 05:36:43 +000011880
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011881Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11882 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011883 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011884 BasicBlock *TrueDest;
11885 BasicBlock *FalseDest;
11886 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11887 !isa<Constant>(X)) {
11888 // Swap Destinations and condition...
11889 BI.setCondition(X);
11890 BI.setSuccessor(0, FalseDest);
11891 BI.setSuccessor(1, TrueDest);
11892 return &BI;
11893 }
11894
Reid Spencere4d87aa2006-12-23 06:05:41 +000011895 // Cannonicalize fcmp_one -> fcmp_oeq
11896 FCmpInst::Predicate FPred; Value *Y;
11897 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11898 TrueDest, FalseDest)))
11899 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11900 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11901 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011902 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011903 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11904 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011905 // Swap Destinations and condition...
11906 BI.setCondition(NewSCC);
11907 BI.setSuccessor(0, FalseDest);
11908 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011909 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011910 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011911 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011912 return &BI;
11913 }
11914
11915 // Cannonicalize icmp_ne -> icmp_eq
11916 ICmpInst::Predicate IPred;
11917 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11918 TrueDest, FalseDest)))
11919 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11920 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11921 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11922 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011923 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011924 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11925 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011926 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011927 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011928 BI.setSuccessor(0, FalseDest);
11929 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011930 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011931 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011932 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011933 return &BI;
11934 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011935
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011936 return 0;
11937}
Chris Lattner0864acf2002-11-04 16:18:53 +000011938
Chris Lattner46238a62004-07-03 00:26:11 +000011939Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11940 Value *Cond = SI.getCondition();
11941 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11942 if (I->getOpcode() == Instruction::Add)
11943 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11944 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11945 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011946 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011947 AddRHS));
11948 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011949 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011950 return &SI;
11951 }
11952 }
11953 return 0;
11954}
11955
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011956Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011957 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011958
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011959 if (!EV.hasIndices())
11960 return ReplaceInstUsesWith(EV, Agg);
11961
11962 if (Constant *C = dyn_cast<Constant>(Agg)) {
11963 if (isa<UndefValue>(C))
11964 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11965
11966 if (isa<ConstantAggregateZero>(C))
11967 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11968
11969 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11970 // Extract the element indexed by the first index out of the constant
11971 Value *V = C->getOperand(*EV.idx_begin());
11972 if (EV.getNumIndices() > 1)
11973 // Extract the remaining indices out of the constant indexed by the
11974 // first index
11975 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11976 else
11977 return ReplaceInstUsesWith(EV, V);
11978 }
11979 return 0; // Can't handle other constants
11980 }
11981 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11982 // We're extracting from an insertvalue instruction, compare the indices
11983 const unsigned *exti, *exte, *insi, *inse;
11984 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11985 exte = EV.idx_end(), inse = IV->idx_end();
11986 exti != exte && insi != inse;
11987 ++exti, ++insi) {
11988 if (*insi != *exti)
11989 // The insert and extract both reference distinctly different elements.
11990 // This means the extract is not influenced by the insert, and we can
11991 // replace the aggregate operand of the extract with the aggregate
11992 // operand of the insert. i.e., replace
11993 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11994 // %E = extractvalue { i32, { i32 } } %I, 0
11995 // with
11996 // %E = extractvalue { i32, { i32 } } %A, 0
11997 return ExtractValueInst::Create(IV->getAggregateOperand(),
11998 EV.idx_begin(), EV.idx_end());
11999 }
12000 if (exti == exte && insi == inse)
12001 // Both iterators are at the end: Index lists are identical. Replace
12002 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12003 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12004 // with "i32 42"
12005 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12006 if (exti == exte) {
12007 // The extract list is a prefix of the insert list. i.e. replace
12008 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12009 // %E = extractvalue { i32, { i32 } } %I, 1
12010 // with
12011 // %X = extractvalue { i32, { i32 } } %A, 1
12012 // %E = insertvalue { i32 } %X, i32 42, 0
12013 // by switching the order of the insert and extract (though the
12014 // insertvalue should be left in, since it may have other uses).
12015 Value *NewEV = InsertNewInstBefore(
12016 ExtractValueInst::Create(IV->getAggregateOperand(),
12017 EV.idx_begin(), EV.idx_end()),
12018 EV);
12019 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12020 insi, inse);
12021 }
12022 if (insi == inse)
12023 // The insert list is a prefix of the extract list
12024 // We can simply remove the common indices from the extract and make it
12025 // operate on the inserted value instead of the insertvalue result.
12026 // i.e., replace
12027 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12028 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12029 // with
12030 // %E extractvalue { i32 } { i32 42 }, 0
12031 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12032 exti, exte);
12033 }
12034 // Can't simplify extracts from other values. Note that nested extracts are
12035 // already simplified implicitely by the above (extract ( extract (insert) )
12036 // will be translated into extract ( insert ( extract ) ) first and then just
12037 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012038 return 0;
12039}
12040
Chris Lattner220b0cf2006-03-05 00:22:33 +000012041/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12042/// is to leave as a vector operation.
12043static bool CheapToScalarize(Value *V, bool isConstant) {
12044 if (isa<ConstantAggregateZero>(V))
12045 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012046 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012047 if (isConstant) return true;
12048 // If all elts are the same, we can extract.
12049 Constant *Op0 = C->getOperand(0);
12050 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12051 if (C->getOperand(i) != Op0)
12052 return false;
12053 return true;
12054 }
12055 Instruction *I = dyn_cast<Instruction>(V);
12056 if (!I) return false;
12057
12058 // Insert element gets simplified to the inserted element or is deleted if
12059 // this is constant idx extract element and its a constant idx insertelt.
12060 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12061 isa<ConstantInt>(I->getOperand(2)))
12062 return true;
12063 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12064 return true;
12065 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12066 if (BO->hasOneUse() &&
12067 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12068 CheapToScalarize(BO->getOperand(1), isConstant)))
12069 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012070 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12071 if (CI->hasOneUse() &&
12072 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12073 CheapToScalarize(CI->getOperand(1), isConstant)))
12074 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012075
12076 return false;
12077}
12078
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012079/// Read and decode a shufflevector mask.
12080///
12081/// It turns undef elements into values that are larger than the number of
12082/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012083static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12084 unsigned NElts = SVI->getType()->getNumElements();
12085 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12086 return std::vector<unsigned>(NElts, 0);
12087 if (isa<UndefValue>(SVI->getOperand(2)))
12088 return std::vector<unsigned>(NElts, 2*NElts);
12089
12090 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012091 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012092 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12093 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012094 Result.push_back(NElts*2); // undef -> 8
12095 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012096 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012097 return Result;
12098}
12099
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012100/// FindScalarElement - Given a vector and an element number, see if the scalar
12101/// value is already around as a register, for example if it were inserted then
12102/// extracted from the vector.
12103static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012104 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12105 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012106 unsigned Width = PTy->getNumElements();
12107 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012108 return UndefValue::get(PTy->getElementType());
12109
12110 if (isa<UndefValue>(V))
12111 return UndefValue::get(PTy->getElementType());
12112 else if (isa<ConstantAggregateZero>(V))
12113 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012114 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012115 return CP->getOperand(EltNo);
12116 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12117 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012118 if (!isa<ConstantInt>(III->getOperand(2)))
12119 return 0;
12120 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012121
12122 // If this is an insert to the element we are looking for, return the
12123 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012124 if (EltNo == IIElt)
12125 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012126
12127 // Otherwise, the insertelement doesn't modify the value, recurse on its
12128 // vector input.
12129 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000012130 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012131 unsigned LHSWidth =
12132 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012133 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012134 if (InEl < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012135 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012136 else if (InEl < LHSWidth*2)
12137 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000012138 else
12139 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012140 }
12141
12142 // Otherwise, we don't know.
12143 return 0;
12144}
12145
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012146Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012147 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012148 if (isa<UndefValue>(EI.getOperand(0)))
12149 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12150
Dan Gohman07a96762007-07-16 14:29:03 +000012151 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012152 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12153 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12154
Reid Spencer9d6565a2007-02-15 02:26:10 +000012155 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012156 // If vector val is constant with all elements the same, replace EI with
12157 // that element. When the elements are not identical, we cannot replace yet
12158 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012159 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012160 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012161 if (C->getOperand(i) != op0) {
12162 op0 = 0;
12163 break;
12164 }
12165 if (op0)
12166 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012167 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000012168
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012169 // If extracting a specified index from the vector, see if we can recursively
12170 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012171 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012172 unsigned IndexVal = IdxC->getZExtValue();
12173 unsigned VectorWidth =
12174 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12175
12176 // If this is extracting an invalid index, turn this into undef, to avoid
12177 // crashing the code below.
12178 if (IndexVal >= VectorWidth)
12179 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12180
Chris Lattner867b99f2006-10-05 06:55:50 +000012181 // This instruction only demands the single element from the input vector.
12182 // If the input vector has a single use, simplify it based on this use
12183 // property.
Chris Lattner85464092007-04-09 01:37:55 +000012184 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012185 APInt UndefElts(VectorWidth, 0);
12186 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012187 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012188 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012189 EI.setOperand(0, V);
12190 return &EI;
12191 }
12192 }
12193
Reid Spencerb83eb642006-10-20 07:07:24 +000012194 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012195 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012196
12197 // If the this extractelement is directly using a bitcast from a vector of
12198 // the same number of elements, see if we can find the source element from
12199 // it. In this case, we will end up needing to bitcast the scalars.
12200 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12201 if (const VectorType *VT =
12202 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12203 if (VT->getNumElements() == VectorWidth)
12204 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12205 return new BitCastInst(Elt, EI.getType());
12206 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012207 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012208
Chris Lattner73fa49d2006-05-25 22:53:38 +000012209 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012210 if (I->hasOneUse()) {
12211 // Push extractelement into predecessor operation if legal and
12212 // profitable to do so
12213 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012214 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12215 if (CheapToScalarize(BO, isConstantElt)) {
12216 ExtractElementInst *newEI0 =
12217 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12218 EI.getName()+".lhs");
12219 ExtractElementInst *newEI1 =
12220 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12221 EI.getName()+".rhs");
12222 InsertNewInstBefore(newEI0, EI);
12223 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012224 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012225 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012226 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012227 unsigned AS =
12228 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012229 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12230 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012231 GetElementPtrInst *GEP =
12232 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012233 InsertNewInstBefore(GEP, EI);
12234 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012235 }
12236 }
12237 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12238 // Extracting the inserted element?
12239 if (IE->getOperand(2) == EI.getOperand(1))
12240 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12241 // If the inserted and extracted elements are constants, they must not
12242 // be the same value, extract from the pre-inserted value instead.
12243 if (isa<Constant>(IE->getOperand(2)) &&
12244 isa<Constant>(EI.getOperand(1))) {
12245 AddUsesToWorkList(EI);
12246 EI.setOperand(0, IE->getOperand(0));
12247 return &EI;
12248 }
12249 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12250 // If this is extracting an element from a shufflevector, figure out where
12251 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012252 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12253 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012254 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012255 unsigned LHSWidth =
12256 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12257
12258 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012259 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012260 else if (SrcIdx < LHSWidth*2) {
12261 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012262 Src = SVI->getOperand(1);
12263 } else {
12264 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012265 }
Chris Lattner867b99f2006-10-05 06:55:50 +000012266 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012267 }
12268 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012269 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012270 return 0;
12271}
12272
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012273/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12274/// elements from either LHS or RHS, return the shuffle mask and true.
12275/// Otherwise, return false.
12276static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12277 std::vector<Constant*> &Mask) {
12278 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12279 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012280 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012281
12282 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012283 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012284 return true;
12285 } else if (V == LHS) {
12286 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012287 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012288 return true;
12289 } else if (V == RHS) {
12290 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012291 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012292 return true;
12293 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12294 // If this is an insert of an extract from some other vector, include it.
12295 Value *VecOp = IEI->getOperand(0);
12296 Value *ScalarOp = IEI->getOperand(1);
12297 Value *IdxOp = IEI->getOperand(2);
12298
Chris Lattnerd929f062006-04-27 21:14:21 +000012299 if (!isa<ConstantInt>(IdxOp))
12300 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012301 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012302
12303 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12304 // Okay, we can handle this if the vector we are insertinting into is
12305 // transitively ok.
12306 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12307 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000012308 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012309 return true;
12310 }
12311 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12312 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012313 EI->getOperand(0)->getType() == V->getType()) {
12314 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012315 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012316
12317 // This must be extracting from either LHS or RHS.
12318 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12319 // Okay, we can handle this if the vector we are insertinting into is
12320 // transitively ok.
12321 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12322 // If so, update the mask to reflect the inserted value.
12323 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012324 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012325 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012326 } else {
12327 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012328 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012329 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012330
12331 }
12332 return true;
12333 }
12334 }
12335 }
12336 }
12337 }
12338 // TODO: Handle shufflevector here!
12339
12340 return false;
12341}
12342
12343/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12344/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12345/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012346static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012347 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012348 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012349 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012350 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012351 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012352
12353 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012354 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012355 return V;
12356 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012357 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012358 return V;
12359 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12360 // If this is an insert of an extract from some other vector, include it.
12361 Value *VecOp = IEI->getOperand(0);
12362 Value *ScalarOp = IEI->getOperand(1);
12363 Value *IdxOp = IEI->getOperand(2);
12364
12365 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12366 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12367 EI->getOperand(0)->getType() == V->getType()) {
12368 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012369 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12370 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012371
12372 // Either the extracted from or inserted into vector must be RHSVec,
12373 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012374 if (EI->getOperand(0) == RHS || RHS == 0) {
12375 RHS = EI->getOperand(0);
12376 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012377 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012378 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012379 return V;
12380 }
12381
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012382 if (VecOp == RHS) {
12383 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000012384 // Everything but the extracted element is replaced with the RHS.
12385 for (unsigned i = 0; i != NumElts; ++i) {
12386 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012387 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012388 }
12389 return V;
12390 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012391
12392 // If this insertelement is a chain that comes from exactly these two
12393 // vectors, return the vector and the effective shuffle.
12394 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12395 return EI->getOperand(0);
12396
Chris Lattnerefb47352006-04-15 01:39:45 +000012397 }
12398 }
12399 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012400 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012401
12402 // Otherwise, can't do anything fancy. Return an identity vector.
12403 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012404 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012405 return V;
12406}
12407
12408Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12409 Value *VecOp = IE.getOperand(0);
12410 Value *ScalarOp = IE.getOperand(1);
12411 Value *IdxOp = IE.getOperand(2);
12412
Chris Lattner599ded12007-04-09 01:11:16 +000012413 // Inserting an undef or into an undefined place, remove this.
12414 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12415 ReplaceInstUsesWith(IE, VecOp);
12416
Chris Lattnerefb47352006-04-15 01:39:45 +000012417 // If the inserted element was extracted from some other vector, and if the
12418 // indexes are constant, try to turn this into a shufflevector operation.
12419 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12420 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12421 EI->getOperand(0)->getType() == IE.getType()) {
12422 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012423 unsigned ExtractedIdx =
12424 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012425 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012426
12427 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12428 return ReplaceInstUsesWith(IE, VecOp);
12429
12430 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12431 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12432
12433 // If we are extracting a value from a vector, then inserting it right
12434 // back into the same place, just use the input vector.
12435 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12436 return ReplaceInstUsesWith(IE, VecOp);
12437
12438 // We could theoretically do this for ANY input. However, doing so could
12439 // turn chains of insertelement instructions into a chain of shufflevector
12440 // instructions, and right now we do not merge shufflevectors. As such,
12441 // only do this in a situation where it is clear that there is benefit.
12442 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12443 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12444 // the values of VecOp, except then one read from EIOp0.
12445 // Build a new shuffle mask.
12446 std::vector<Constant*> Mask;
12447 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000012448 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012449 else {
12450 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000012451 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012452 NumVectorElts));
12453 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000012454 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012455 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000012456 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012457 }
12458
12459 // If this insertelement isn't used by some other insertelement, turn it
12460 // (and any insertelements it points to), into one big shuffle.
12461 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12462 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012463 Value *RHS = 0;
12464 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12465 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12466 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000012467 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012468 }
12469 }
12470 }
12471
12472 return 0;
12473}
12474
12475
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012476Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12477 Value *LHS = SVI.getOperand(0);
12478 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012479 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012480
12481 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012482
Chris Lattner867b99f2006-10-05 06:55:50 +000012483 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012484 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012485 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012486
Dan Gohman488fbfc2008-09-09 18:11:14 +000012487 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012488
12489 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12490 return 0;
12491
Evan Cheng388df622009-02-03 10:05:09 +000012492 APInt UndefElts(VWidth, 0);
12493 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12494 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012495 LHS = SVI.getOperand(0);
12496 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012497 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012498 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012499
Chris Lattner863bcff2006-05-25 23:48:38 +000012500 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12501 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12502 if (LHS == RHS || isa<UndefValue>(LHS)) {
12503 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012504 // shuffle(undef,undef,mask) -> undef.
12505 return ReplaceInstUsesWith(SVI, LHS);
12506 }
12507
Chris Lattner863bcff2006-05-25 23:48:38 +000012508 // Remap any references to RHS to use LHS.
12509 std::vector<Constant*> Elts;
12510 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012511 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012512 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012513 else {
12514 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012515 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012516 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000012517 Elts.push_back(UndefValue::get(Type::Int32Ty));
12518 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012519 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000012520 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12521 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012522 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012523 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012524 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012525 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000012526 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012527 LHS = SVI.getOperand(0);
12528 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012529 MadeChange = true;
12530 }
12531
Chris Lattner7b2e27922006-05-26 00:29:06 +000012532 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012533 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012534
Chris Lattner863bcff2006-05-25 23:48:38 +000012535 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12536 if (Mask[i] >= e*2) continue; // Ignore undef values.
12537 // Is this an identity shuffle of the LHS value?
12538 isLHSID &= (Mask[i] == i);
12539
12540 // Is this an identity shuffle of the RHS value?
12541 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012542 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012543
Chris Lattner863bcff2006-05-25 23:48:38 +000012544 // Eliminate identity shuffles.
12545 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12546 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012547
Chris Lattner7b2e27922006-05-26 00:29:06 +000012548 // If the LHS is a shufflevector itself, see if we can combine it with this
12549 // one without producing an unusual shuffle. Here we are really conservative:
12550 // we are absolutely afraid of producing a shuffle mask not in the input
12551 // program, because the code gen may not be smart enough to turn a merged
12552 // shuffle into two specific shuffles: it may produce worse code. As such,
12553 // we only merge two shuffles if the result is one of the two input shuffle
12554 // masks. In this case, merging the shuffles just removes one instruction,
12555 // which we know is safe. This is good for things like turning:
12556 // (splat(splat)) -> splat.
12557 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12558 if (isa<UndefValue>(RHS)) {
12559 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12560
12561 std::vector<unsigned> NewMask;
12562 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12563 if (Mask[i] >= 2*e)
12564 NewMask.push_back(2*e);
12565 else
12566 NewMask.push_back(LHSMask[Mask[i]]);
12567
12568 // If the result mask is equal to the src shuffle or this shuffle mask, do
12569 // the replacement.
12570 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012571 unsigned LHSInNElts =
12572 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012573 std::vector<Constant*> Elts;
12574 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012575 if (NewMask[i] >= LHSInNElts*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012576 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012577 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012578 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012579 }
12580 }
12581 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12582 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000012583 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012584 }
12585 }
12586 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012587
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012588 return MadeChange ? &SVI : 0;
12589}
12590
12591
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012592
Chris Lattnerea1c4542004-12-08 23:43:58 +000012593
12594/// TryToSinkInstruction - Try to move the specified instruction from its
12595/// current block into the beginning of DestBlock, which can only happen if it's
12596/// safe to move the instruction past all of the instructions between it and the
12597/// end of its block.
12598static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12599 assert(I->hasOneUse() && "Invariants didn't hold!");
12600
Chris Lattner108e9022005-10-27 17:13:11 +000012601 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012602 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012603 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012604
Chris Lattnerea1c4542004-12-08 23:43:58 +000012605 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012606 if (isa<AllocaInst>(I) && I->getParent() ==
12607 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012608 return false;
12609
Chris Lattner96a52a62004-12-09 07:14:34 +000012610 // We can only sink load instructions if there is nothing between the load and
12611 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012612 if (I->mayReadFromMemory()) {
12613 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012614 Scan != E; ++Scan)
12615 if (Scan->mayWriteToMemory())
12616 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012617 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012618
Dan Gohman02dea8b2008-05-23 21:05:58 +000012619 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012620
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012621 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012622 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012623 ++NumSunkInst;
12624 return true;
12625}
12626
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012627
12628/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12629/// all reachable code to the worklist.
12630///
12631/// This has a couple of tricks to make the code faster and more powerful. In
12632/// particular, we constant fold and DCE instructions as we go, to avoid adding
12633/// them to the worklist (this significantly speeds up instcombine on code where
12634/// many instructions are dead or constant). Additionally, if we find a branch
12635/// whose condition is a known constant, we only visit the reachable successors.
12636///
12637static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012638 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012639 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012640 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012641 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012642 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012643
Chris Lattner2c7718a2007-03-23 19:17:18 +000012644 while (!Worklist.empty()) {
12645 BB = Worklist.back();
12646 Worklist.pop_back();
12647
12648 // We have now visited this block! If we've already been here, ignore it.
12649 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012650
12651 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012652 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12653 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012654
Chris Lattner2c7718a2007-03-23 19:17:18 +000012655 // DCE instruction if trivially dead.
12656 if (isInstructionTriviallyDead(Inst)) {
12657 ++NumDeadInst;
12658 DOUT << "IC: DCE: " << *Inst;
12659 Inst->eraseFromParent();
12660 continue;
12661 }
12662
12663 // ConstantProp instruction if trivially constant.
12664 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12665 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12666 Inst->replaceAllUsesWith(C);
12667 ++NumConstProp;
12668 Inst->eraseFromParent();
12669 continue;
12670 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012671
Devang Patel7fe1dec2008-11-19 18:56:50 +000012672 // If there are two consecutive llvm.dbg.stoppoint calls then
12673 // it is likely that the optimizer deleted code in between these
12674 // two intrinsics.
12675 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12676 if (DBI_Next) {
12677 if (DBI_Prev
12678 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12679 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12680 IC.RemoveFromWorkList(DBI_Prev);
12681 DBI_Prev->eraseFromParent();
12682 }
12683 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012684 } else {
12685 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012686 }
12687
Chris Lattner2c7718a2007-03-23 19:17:18 +000012688 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012689 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012690
12691 // Recursively visit successors. If this is a branch or switch on a
12692 // constant, only visit the reachable successor.
12693 TerminatorInst *TI = BB->getTerminator();
12694 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12695 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12696 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012697 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012698 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012699 continue;
12700 }
12701 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12702 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12703 // See if this is an explicit destination.
12704 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12705 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012706 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012707 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012708 continue;
12709 }
12710
12711 // Otherwise it is the default destination.
12712 Worklist.push_back(SI->getSuccessor(0));
12713 continue;
12714 }
12715 }
12716
12717 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12718 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012719 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012720}
12721
Chris Lattnerec9c3582007-03-03 02:04:50 +000012722bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012723 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012724 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012725
12726 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12727 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012728
Chris Lattnerb3d59702005-07-07 20:40:38 +000012729 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012730 // Do a depth-first traversal of the function, populate the worklist with
12731 // the reachable instructions. Ignore blocks that are not reachable. Keep
12732 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012733 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012734 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012735
Chris Lattnerb3d59702005-07-07 20:40:38 +000012736 // Do a quick scan over the function. If we find any blocks that are
12737 // unreachable, remove any instructions inside of them. This prevents
12738 // the instcombine code from having to deal with some bad special cases.
12739 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12740 if (!Visited.count(BB)) {
12741 Instruction *Term = BB->getTerminator();
12742 while (Term != BB->begin()) { // Remove instrs bottom-up
12743 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012744
Bill Wendlingb7427032006-11-26 09:46:52 +000012745 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012746 // A debug intrinsic shouldn't force another iteration if we weren't
12747 // going to do one without it.
12748 if (!isa<DbgInfoIntrinsic>(I)) {
12749 ++NumDeadInst;
12750 Changed = true;
12751 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012752 if (!I->use_empty())
12753 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12754 I->eraseFromParent();
12755 }
12756 }
12757 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012758
Chris Lattnerdbab3862007-03-02 21:28:56 +000012759 while (!Worklist.empty()) {
12760 Instruction *I = RemoveOneFromWorkList();
12761 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012762
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012763 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012764 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012765 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012766 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012767 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012768 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012769
Bill Wendlingb7427032006-11-26 09:46:52 +000012770 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012771
12772 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012773 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012774 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012775 continue;
12776 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012777
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012778 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000012779 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012780 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012781
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012782 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012783 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012784 ReplaceInstUsesWith(*I, C);
12785
Chris Lattner62b14df2002-09-02 04:59:56 +000012786 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012787 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012788 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012789 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012790 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012791 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012792
Dan Gohman31e4c772009-05-07 19:43:39 +000012793 if (TD &&
12794 (I->getType()->getTypeID() == Type::VoidTyID ||
12795 I->isTrapping())) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012796 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012797 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12798 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012799 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012800 if (NewC != CE) {
12801 i->set(NewC);
12802 Changed = true;
12803 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012804 }
12805
Chris Lattnerea1c4542004-12-08 23:43:58 +000012806 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012807 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012808 BasicBlock *BB = I->getParent();
12809 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12810 if (UserParent != BB) {
12811 bool UserIsSuccessor = false;
12812 // See if the user is one of our successors.
12813 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12814 if (*SI == UserParent) {
12815 UserIsSuccessor = true;
12816 break;
12817 }
12818
12819 // If the user is one of our immediate successors, and if that successor
12820 // only has us as a predecessors (we'd have to split the critical edge
12821 // otherwise), we can keep going.
12822 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12823 next(pred_begin(UserParent)) == pred_end(UserParent))
12824 // Okay, the CFG is simple enough, try to sink this instruction.
12825 Changed |= TryToSinkInstruction(I, UserParent);
12826 }
12827 }
12828
Chris Lattner8a2a3112001-12-14 16:52:21 +000012829 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012830#ifndef NDEBUG
12831 std::string OrigI;
12832#endif
12833 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012834 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012835 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012836 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012837 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012838 DOUT << "IC: Old = " << *I
12839 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000012840
Chris Lattnerf523d062004-06-09 05:08:07 +000012841 // Everything uses the new instruction now.
12842 I->replaceAllUsesWith(Result);
12843
12844 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012845 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000012846 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012847
Chris Lattner6934a042007-02-11 01:23:03 +000012848 // Move the name to the new instruction first.
12849 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012850
12851 // Insert the new instruction into the basic block...
12852 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012853 BasicBlock::iterator InsertPos = I;
12854
12855 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12856 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12857 ++InsertPos;
12858
12859 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012860
Chris Lattner00d51312004-05-01 23:27:23 +000012861 // Make sure that we reprocess all operands now that we reduced their
12862 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012863 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000012864
Chris Lattnerf523d062004-06-09 05:08:07 +000012865 // Instructions can end up on the worklist more than once. Make sure
12866 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012867 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012868
12869 // Erase the old instruction.
12870 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000012871 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012872#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000012873 DOUT << "IC: Mod = " << OrigI
12874 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000012875#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012876
Chris Lattner90ac28c2002-08-02 19:29:35 +000012877 // If the instruction was modified, it's possible that it is now dead.
12878 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012879 if (isInstructionTriviallyDead(I)) {
12880 // Make sure we process all operands now that we are reducing their
12881 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000012882 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012883
Chris Lattner00d51312004-05-01 23:27:23 +000012884 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012885 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012886 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000012887 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000012888 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000012889 AddToWorkList(I);
12890 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012891 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012892 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012893 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012894 }
12895 }
12896
Chris Lattnerec9c3582007-03-03 02:04:50 +000012897 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000012898
12899 // Do an explicit clear, this shrinks the map if needed.
12900 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012901 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012902}
12903
Chris Lattnerec9c3582007-03-03 02:04:50 +000012904
12905bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012906 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12907
Chris Lattnerec9c3582007-03-03 02:04:50 +000012908 bool EverMadeChange = false;
12909
12910 // Iterate while there is work to do.
12911 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012912 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012913 EverMadeChange = true;
12914 return EverMadeChange;
12915}
12916
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012917FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012918 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012919}