blob: 39ad04f53e0df0019fa8240de5f1642043060430 [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"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000043#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000044#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000045#include "llvm/Target/TargetData.h"
46#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000048#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000049#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000050#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000051#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000053#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000054#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000055#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000056#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000057#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000058#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000059#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000060#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000061#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000062#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000063#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000064#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000065using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000066using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000067
Chris Lattner0e5f4992006-12-19 21:40:18 +000068STATISTIC(NumCombined , "Number of insts combined");
69STATISTIC(NumConstProp, "Number of constant folds");
70STATISTIC(NumDeadInst , "Number of dead inst eliminated");
71STATISTIC(NumDeadStore, "Number of dead stores eliminated");
72STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000073
Chris Lattner0e5f4992006-12-19 21:40:18 +000074namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000075 class VISIBILITY_HIDDEN InstCombiner
76 : public FunctionPass,
77 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000078 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000079 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000080 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000081 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000082 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000083 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000084 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000085 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000086
Owen Anderson07cf79e2009-07-06 23:00:19 +000087 LLVMContext *getContext() { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +000088
Chris Lattnerdbab3862007-03-02 21:28:56 +000089 /// AddToWorkList - Add the specified instruction to the worklist if it
90 /// isn't already in it.
91 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000092 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000093 Worklist.push_back(I);
94 }
95
96 // RemoveFromWorkList - remove I from the worklist if it exists.
97 void RemoveFromWorkList(Instruction *I) {
98 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
99 if (It == WorklistMap.end()) return; // Not in worklist.
100
101 // Don't bother moving everything down, just null out the slot.
102 Worklist[It->second] = 0;
103
104 WorklistMap.erase(It);
105 }
106
107 Instruction *RemoveOneFromWorkList() {
108 Instruction *I = Worklist.back();
109 Worklist.pop_back();
110 WorklistMap.erase(I);
111 return I;
112 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000113
Chris Lattnerdbab3862007-03-02 21:28:56 +0000114
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000115 /// AddUsersToWorkList - When an instruction is simplified, add all users of
116 /// the instruction to the work lists because they might get more simplified
117 /// now.
118 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000119 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000120 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000121 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000122 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000123 }
124
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000125 /// AddUsesToWorkList - When an instruction is simplified, add operands to
126 /// the work lists because they might get more simplified now.
127 ///
128 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000129 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
130 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000131 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000132 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000133
134 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
135 /// dead. Add all of its operands to the worklist, turning them into
136 /// undef's to reduce the number of uses of those instructions.
137 ///
138 /// Return the specified operand before it is turned into an undef.
139 ///
140 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
141 Value *R = I.getOperand(op);
142
Gabor Greif177dd3f2008-06-12 21:37:33 +0000143 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
144 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000145 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000146 // Set the operand to undef to drop the use.
Owen Andersond672ecb2009-07-03 00:17:18 +0000147 *i = Context->getUndef(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000148 }
149
150 return R;
151 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000152
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000153 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000154 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000155
156 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000157
Chris Lattner97e52e42002-04-28 21:27:06 +0000158 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000159 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000160 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000161 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000162 }
163
Chris Lattner28977af2004-04-05 01:30:19 +0000164 TargetData &getTargetData() const { return *TD; }
165
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000166 // Visitation implementation - Implement instruction combining for different
167 // instruction types. The semantics are as follows:
168 // Return Value:
169 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000170 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000171 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000172 //
Chris Lattner7e708292002-06-25 16:13:24 +0000173 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000174 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000175 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000176 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000177 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000178 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000179 Instruction *visitURem(BinaryOperator &I);
180 Instruction *visitSRem(BinaryOperator &I);
181 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000182 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000183 Instruction *commonRemTransforms(BinaryOperator &I);
184 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000185 Instruction *commonDivTransforms(BinaryOperator &I);
186 Instruction *commonIDivTransforms(BinaryOperator &I);
187 Instruction *visitUDiv(BinaryOperator &I);
188 Instruction *visitSDiv(BinaryOperator &I);
189 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000190 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000191 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000192 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000193 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000194 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000195 Instruction *visitOr (BinaryOperator &I);
196 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000197 Instruction *visitShl(BinaryOperator &I);
198 Instruction *visitAShr(BinaryOperator &I);
199 Instruction *visitLShr(BinaryOperator &I);
200 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000201 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
202 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000203 Instruction *visitFCmpInst(FCmpInst &I);
204 Instruction *visitICmpInst(ICmpInst &I);
205 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000206 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
207 Instruction *LHS,
208 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000209 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
210 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000211
Reid Spencere4d87aa2006-12-23 06:05:41 +0000212 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
213 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000214 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000215 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000216 Instruction *commonCastTransforms(CastInst &CI);
217 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000218 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000219 Instruction *visitTrunc(TruncInst &CI);
220 Instruction *visitZExt(ZExtInst &CI);
221 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000222 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000223 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000224 Instruction *visitFPToUI(FPToUIInst &FI);
225 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000226 Instruction *visitUIToFP(CastInst &CI);
227 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000228 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000229 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000230 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000231 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
232 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000233 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000234 Instruction *visitSelectInst(SelectInst &SI);
235 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000236 Instruction *visitCallInst(CallInst &CI);
237 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000238 Instruction *visitPHINode(PHINode &PN);
239 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000240 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000241 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000242 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000243 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000244 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000245 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000246 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000247 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000248 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000249 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000250
251 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000252 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000253
Chris Lattner9fe38862003-06-19 17:00:31 +0000254 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000255 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000256 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000257 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000258 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
259 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000260 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000261 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
262
Chris Lattner9fe38862003-06-19 17:00:31 +0000263
Chris Lattner28977af2004-04-05 01:30:19 +0000264 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000265 // InsertNewInstBefore - insert an instruction New before instruction Old
266 // in the program. Add the new instruction to the worklist.
267 //
Chris Lattner955f3312004-09-28 21:48:02 +0000268 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000269 assert(New && New->getParent() == 0 &&
270 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000271 BasicBlock *BB = Old.getParent();
272 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000273 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000274 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000275 }
276
Chris Lattner0c967662004-09-24 15:21:34 +0000277 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
278 /// This also adds the cast to the worklist. Finally, this returns the
279 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000280 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
281 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000282 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000283
Chris Lattnere2ed0572006-04-06 19:19:17 +0000284 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000285 return Context->getConstantExprCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000286
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000287 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000288 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000289 return C;
290 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000291
292 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
293 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
294 }
295
Chris Lattner0c967662004-09-24 15:21:34 +0000296
Chris Lattner8b170942002-08-09 23:47:40 +0000297 // ReplaceInstUsesWith - This method is to be used when an instruction is
298 // found to be dead, replacable with another preexisting expression. Here
299 // we add all uses of I to the worklist, replace all uses of I with the new
300 // value, then return I, so that the inst combiner will know that I was
301 // modified.
302 //
303 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000304 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000305 if (&I != V) {
306 I.replaceAllUsesWith(V);
307 return &I;
308 } else {
309 // If we are replacing the instruction with itself, this must be in a
310 // segment of unreachable code, so just clobber the instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +0000311 I.replaceAllUsesWith(Context->getUndef(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000312 return &I;
313 }
Chris Lattner8b170942002-08-09 23:47:40 +0000314 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000315
316 // EraseInstFromFunction - When dealing with an instruction that has side
317 // effects or produces a void value, we can't rely on DCE to delete the
318 // instruction. Instead, visit methods should return the value returned by
319 // this function.
320 Instruction *EraseInstFromFunction(Instruction &I) {
321 assert(I.use_empty() && "Cannot erase instruction that is used!");
322 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000323 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000324 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000325 return 0; // Don't do anything with FI
326 }
Chris Lattner173234a2008-06-02 01:18:21 +0000327
328 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
329 APInt &KnownOne, unsigned Depth = 0) const {
330 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
331 }
332
333 bool MaskedValueIsZero(Value *V, const APInt &Mask,
334 unsigned Depth = 0) const {
335 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
336 }
337 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
338 return llvm::ComputeNumSignBits(Op, TD, Depth);
339 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000340
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000341 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000342
Reid Spencere4d87aa2006-12-23 06:05:41 +0000343 /// SimplifyCommutative - This performs a few simplifications for
344 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000345 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000346
Reid Spencere4d87aa2006-12-23 06:05:41 +0000347 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
348 /// most-complex to least-complex order.
349 bool SimplifyCompare(CmpInst &I);
350
Chris Lattner886ab6c2009-01-31 08:15:18 +0000351 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
352 /// based on the demanded bits.
353 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
354 APInt& KnownZero, APInt& KnownOne,
355 unsigned Depth);
356 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000357 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000358 unsigned Depth=0);
359
360 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
361 /// SimplifyDemandedBits knows about. See if the instruction has any
362 /// properties that allow us to simplify its operands.
363 bool SimplifyDemandedInstructionBits(Instruction &Inst);
364
Evan Cheng388df622009-02-03 10:05:09 +0000365 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
366 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000367
Chris Lattner4e998b22004-09-29 05:07:12 +0000368 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369 // PHI node as operand #0, see if we can fold the instruction into the PHI
370 // (which is only possible if all operands to the PHI are constants).
371 Instruction *FoldOpIntoPhi(Instruction &I);
372
Chris Lattnerbac32862004-11-14 19:13:23 +0000373 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374 // operator and they all are only used by the PHI, PHI together their
375 // inputs, and do the operation once, to the result of the PHI.
376 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000377 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000378 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
379
Chris Lattner7da52b22006-11-01 04:51:18 +0000380
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000381 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000383
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000384 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000385 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000386 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000387 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000388 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000389 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000390 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000391 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000392 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000393
Chris Lattnerafe91a52006-06-15 19:07:26 +0000394
Reid Spencerc55b2432006-12-13 18:21:21 +0000395 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000396
Dan Gohman6de29f82009-06-15 22:12:54 +0000397 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000398 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000399 unsigned GetOrEnforceKnownAlignment(Value *V,
400 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000401
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000402 };
403}
404
Dan Gohman844731a2008-05-13 00:00:25 +0000405char InstCombiner::ID = 0;
406static RegisterPass<InstCombiner>
407X("instcombine", "Combine redundant instructions");
408
Chris Lattner4f98c562003-03-10 21:43:22 +0000409// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000410// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson0a5372e2009-07-13 04:09:18 +0000411static unsigned getComplexity(LLVMContext *Context, Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000412 if (isa<Instruction>(V)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000413 if (BinaryOperator::isNeg(*Context, V) ||
414 BinaryOperator::isFNeg(*Context, V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000415 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000416 return 3;
417 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000418 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000419 if (isa<Argument>(V)) return 3;
420 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000421}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000422
Chris Lattnerc8802d22003-03-11 00:12:48 +0000423// isOnlyUse - Return true if this instruction will be deleted if we stop using
424// it.
425static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000426 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000427}
428
Chris Lattner4cb170c2004-02-23 06:38:22 +0000429// getPromotedType - Return the specified type promoted as it would be to pass
430// though a va_arg area...
431static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000432 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
433 if (ITy->getBitWidth() < 32)
434 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000435 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000436 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000437}
438
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000439/// getBitCastOperand - If the specified operand is a CastInst, a constant
440/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
441/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000442static Value *getBitCastOperand(Value *V) {
443 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000444 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000445 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000446 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
447 // GetElementPtrInst?
448 if (GEP->hasAllZeroIndices())
449 return GEP->getOperand(0);
450 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000451 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000452 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000453 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000454 else if (CE->getOpcode() == Instruction::GetElementPtr) {
455 // GetElementPtr ConstantExp?
456 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
457 I != E; ++I) {
458 ConstantInt *CI = dyn_cast<ConstantInt>(I);
459 if (!CI || !CI->isZero())
460 // Any non-zero indices? Not cast-like.
461 return 0;
462 }
463 // All-zero indices? This is just like casting.
464 return CE->getOperand(0);
465 }
466 }
Chris Lattnereed48272005-09-13 00:40:14 +0000467 return 0;
468}
469
Reid Spencer3da59db2006-11-27 01:05:10 +0000470/// This function is a wrapper around CastInst::isEliminableCastPair. It
471/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000472static Instruction::CastOps
473isEliminableCastPair(
474 const CastInst *CI, ///< The first cast instruction
475 unsigned opcode, ///< The opcode of the second cast instruction
476 const Type *DstTy, ///< The target type for the second cast instruction
477 TargetData *TD ///< The target data for pointer size
478) {
479
480 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
481 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000482
Reid Spencer3da59db2006-11-27 01:05:10 +0000483 // Get the opcodes of the two Cast instructions
484 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
485 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000486
Chris Lattnera0e69692009-03-24 18:35:40 +0000487 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
488 DstTy, TD->getIntPtrType());
489
490 // We don't want to form an inttoptr or ptrtoint that converts to an integer
491 // type that differs from the pointer size.
492 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
493 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
494 Res = 0;
495
496 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000497}
498
499/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
500/// in any code being generated. It does not require codegen if V is simple
501/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000502static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
503 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000504 if (V->getType() == Ty || isa<Constant>(V)) return false;
505
Chris Lattner01575b72006-05-25 23:24:33 +0000506 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000507 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000508 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000509 return false;
510 return true;
511}
512
Chris Lattner4f98c562003-03-10 21:43:22 +0000513// SimplifyCommutative - This performs a few simplifications for commutative
514// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000515//
Chris Lattner4f98c562003-03-10 21:43:22 +0000516// 1. Order operands such that they are listed from right (least complex) to
517// left (most complex). This puts constants before unary operators before
518// binary operators.
519//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000520// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
521// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000522//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000523bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000524 bool Changed = false;
Owen Anderson0a5372e2009-07-13 04:09:18 +0000525 if (getComplexity(Context, I.getOperand(0)) <
526 getComplexity(Context, I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000527 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000528
Chris Lattner4f98c562003-03-10 21:43:22 +0000529 if (!I.isAssociative()) return Changed;
530 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000531 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
532 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
533 if (isa<Constant>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000534 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000535 cast<Constant>(I.getOperand(1)),
536 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000537 I.setOperand(0, Op->getOperand(0));
538 I.setOperand(1, Folded);
539 return true;
540 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
541 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
542 isOnlyUse(Op) && isOnlyUse(Op1)) {
543 Constant *C1 = cast<Constant>(Op->getOperand(1));
544 Constant *C2 = cast<Constant>(Op1->getOperand(1));
545
546 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersond672ecb2009-07-03 00:17:18 +0000547 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000548 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000549 Op1->getOperand(0),
550 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000551 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000552 I.setOperand(0, New);
553 I.setOperand(1, Folded);
554 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000555 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000556 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000557 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000558}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000559
Reid Spencere4d87aa2006-12-23 06:05:41 +0000560/// SimplifyCompare - For a CmpInst this function just orders the operands
561/// so that theyare listed from right (least complex) to left (most complex).
562/// This puts constants before unary operators before binary operators.
563bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000564 if (getComplexity(Context, I.getOperand(0)) >=
565 getComplexity(Context, I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000566 return false;
567 I.swapOperands();
568 // Compare instructions are not associative so there's nothing else we can do.
569 return true;
570}
571
Chris Lattner8d969642003-03-10 23:06:50 +0000572// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
573// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000574//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000575static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000576 if (BinaryOperator::isNeg(*Context, V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000577 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000578
Chris Lattner0ce85802004-12-14 20:08:06 +0000579 // Constants can be considered to be negated values if they can be folded.
580 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000581 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000582
583 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
584 if (C->getType()->getElementType()->isInteger())
Owen Andersond672ecb2009-07-03 00:17:18 +0000585 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000586
Chris Lattner8d969642003-03-10 23:06:50 +0000587 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000588}
589
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000590// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
591// instruction if the LHS is a constant negative zero (which is the 'negate'
592// form).
593//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000594static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000595 if (BinaryOperator::isFNeg(*Context, V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000596 return BinaryOperator::getFNegArgument(V);
597
598 // Constants can be considered to be negated values if they can be folded.
599 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000600 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000601
602 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
603 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersond672ecb2009-07-03 00:17:18 +0000604 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000605
606 return 0;
607}
608
Owen Anderson07cf79e2009-07-06 23:00:19 +0000609static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Chris Lattner8d969642003-03-10 23:06:50 +0000610 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000611 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000612
613 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000614 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000615 return Context->getConstantInt(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000616 return 0;
617}
618
Chris Lattnerc8802d22003-03-11 00:12:48 +0000619// dyn_castFoldableMul - If this value is a multiply that can be folded into
620// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000621// non-constant operand of the multiply, and set CST to point to the multiplier.
622// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000623//
Owen Andersond672ecb2009-07-03 00:17:18 +0000624static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000625 LLVMContext *Context) {
Chris Lattner42a75512007-01-15 02:27:26 +0000626 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000627 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000628 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000629 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000630 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000631 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000632 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000633 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000634 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000635 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Andersond672ecb2009-07-03 00:17:18 +0000636 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000637 return I->getOperand(0);
638 }
639 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000640 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000641}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000642
Chris Lattner574da9b2005-01-13 20:14:25 +0000643/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
644/// expression, return it.
645static User *dyn_castGetElementPtr(Value *V) {
646 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
647 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
648 if (CE->getOpcode() == Instruction::GetElementPtr)
649 return cast<User>(V);
650 return false;
651}
652
Dan Gohmaneee962e2008-04-10 18:43:06 +0000653/// getOpcode - If this is an Instruction or a ConstantExpr, return the
654/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000655static unsigned getOpcode(const Value *V) {
656 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000657 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000658 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000659 return CE->getOpcode();
660 // Use UserOp1 to mean there's no opcode.
661 return Instruction::UserOp1;
662}
663
Reid Spencer7177c3a2007-03-25 05:33:51 +0000664/// AddOne - Add one to a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000665static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000666 return Context->getConstantExprAdd(C,
667 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000668}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000669/// SubOne - Subtract one from a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000670static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000671 return Context->getConstantExprSub(C,
672 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000673}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000674/// MultiplyOverflows - True if the multiply can not be expressed in an int
675/// this size.
Owen Andersond672ecb2009-07-03 00:17:18 +0000676static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000677 LLVMContext *Context) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000678 uint32_t W = C1->getBitWidth();
679 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
680 if (sign) {
681 LHSExt.sext(W * 2);
682 RHSExt.sext(W * 2);
683 } else {
684 LHSExt.zext(W * 2);
685 RHSExt.zext(W * 2);
686 }
687
688 APInt MulExt = LHSExt * RHSExt;
689
690 if (sign) {
691 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
692 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
693 return MulExt.slt(Min) || MulExt.sgt(Max);
694 } else
695 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
696}
Chris Lattner955f3312004-09-28 21:48:02 +0000697
Reid Spencere7816b52007-03-08 01:52:58 +0000698
Chris Lattner255d8912006-02-11 09:31:47 +0000699/// ShrinkDemandedConstant - Check to see if the specified operand of the
700/// specified instruction is a constant integer. If so, check to see if there
701/// are any bits set in the constant that are not demanded. If so, shrink the
702/// constant and return true.
703static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000704 APInt Demanded, LLVMContext *Context) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000705 assert(I && "No instruction?");
706 assert(OpNo < I->getNumOperands() && "Operand index too large");
707
708 // If the operand is not a constant integer, nothing to do.
709 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
710 if (!OpC) return false;
711
712 // If there are no bits set that aren't demanded, nothing to do.
713 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
714 if ((~Demanded & OpC->getValue()) == 0)
715 return false;
716
717 // This instruction is producing bits that are not demanded. Shrink the RHS.
718 Demanded &= OpC->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +0000719 I->setOperand(OpNo, Context->getConstantInt(Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000720 return true;
721}
722
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000723// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
724// set of known zero and one bits, compute the maximum and minimum values that
725// could have the specified known zero and known one bits, returning them in
726// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000727static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000728 const APInt& KnownOne,
729 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000730 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
731 KnownZero.getBitWidth() == Min.getBitWidth() &&
732 KnownZero.getBitWidth() == Max.getBitWidth() &&
733 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000734 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000735
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000736 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
737 // bit if it is unknown.
738 Min = KnownOne;
739 Max = KnownOne|UnknownBits;
740
Dan Gohman1c8491e2009-04-25 17:12:48 +0000741 if (UnknownBits.isNegative()) { // Sign bit is unknown
742 Min.set(Min.getBitWidth()-1);
743 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000744 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000745}
746
747// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
748// a set of known zero and one bits, compute the maximum and minimum values that
749// could have the specified known zero and known one bits, returning them in
750// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000751static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000752 const APInt &KnownOne,
753 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000754 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
755 KnownZero.getBitWidth() == Min.getBitWidth() &&
756 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000757 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000758 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000759
760 // The minimum value is when the unknown bits are all zeros.
761 Min = KnownOne;
762 // The maximum value is when the unknown bits are all ones.
763 Max = KnownOne|UnknownBits;
764}
Chris Lattner255d8912006-02-11 09:31:47 +0000765
Chris Lattner886ab6c2009-01-31 08:15:18 +0000766/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
767/// SimplifyDemandedBits knows about. See if the instruction has any
768/// properties that allow us to simplify its operands.
769bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000770 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000771 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
772 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
773
774 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
775 KnownZero, KnownOne, 0);
776 if (V == 0) return false;
777 if (V == &Inst) return true;
778 ReplaceInstUsesWith(Inst, V);
779 return true;
780}
781
782/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
783/// specified instruction operand if possible, updating it in place. It returns
784/// true if it made any change and false otherwise.
785bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
786 APInt &KnownZero, APInt &KnownOne,
787 unsigned Depth) {
788 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
789 KnownZero, KnownOne, Depth);
790 if (NewVal == 0) return false;
791 U.set(NewVal);
792 return true;
793}
794
795
796/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
797/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000798/// that only the bits set in DemandedMask of the result of V are ever used
799/// downstream. Consequently, depending on the mask and V, it may be possible
800/// to replace V with a constant or one of its operands. In such cases, this
801/// function does the replacement and returns true. In all other cases, it
802/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000803/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000804/// to be zero in the expression. These are provided to potentially allow the
805/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
806/// the expression. KnownOne and KnownZero always follow the invariant that
807/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
808/// the bits in KnownOne and KnownZero may only be accurate for those bits set
809/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
810/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000811///
812/// This returns null if it did not change anything and it permits no
813/// simplification. This returns V itself if it did some simplification of V's
814/// operands based on the information about what bits are demanded. This returns
815/// some other non-null value if it found out that V is equal to another value
816/// in the context where the specified bits are demanded, but not for all users.
817Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
818 APInt &KnownZero, APInt &KnownOne,
819 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000820 assert(V != 0 && "Null pointer of Value???");
821 assert(Depth <= 6 && "Limit Search Depth");
822 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000823 const Type *VTy = V->getType();
824 assert((TD || !isa<PointerType>(VTy)) &&
825 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000826 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
827 (!VTy->isIntOrIntVector() ||
828 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000829 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000830 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000831 "Value *V, DemandedMask, KnownZero and KnownOne "
832 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000833 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
834 // We know all of the bits for a constant!
835 KnownOne = CI->getValue() & DemandedMask;
836 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000837 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000838 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000839 if (isa<ConstantPointerNull>(V)) {
840 // We know all of the bits for a constant!
841 KnownOne.clear();
842 KnownZero = DemandedMask;
843 return 0;
844 }
845
Chris Lattner08d2cc72009-01-31 07:26:06 +0000846 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000847 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000848 if (DemandedMask == 0) { // Not demanding any bits from V.
849 if (isa<UndefValue>(V))
850 return 0;
Owen Andersond672ecb2009-07-03 00:17:18 +0000851 return Context->getUndef(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000852 }
853
Chris Lattner4598c942009-01-31 08:24:16 +0000854 if (Depth == 6) // Limit search depth.
855 return 0;
856
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000857 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
858 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
859
Dan Gohman1c8491e2009-04-25 17:12:48 +0000860 Instruction *I = dyn_cast<Instruction>(V);
861 if (!I) {
862 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
863 return 0; // Only analyze instructions.
864 }
865
Chris Lattner4598c942009-01-31 08:24:16 +0000866 // If there are multiple uses of this value and we aren't at the root, then
867 // we can't do any simplifications of the operands, because DemandedMask
868 // only reflects the bits demanded by *one* of the users.
869 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000870 // Despite the fact that we can't simplify this instruction in all User's
871 // context, we can at least compute the knownzero/knownone bits, and we can
872 // do simplifications that apply to *just* the one user if we know that
873 // this instruction has a simpler value in that context.
874 if (I->getOpcode() == Instruction::And) {
875 // If either the LHS or the RHS are Zero, the result is zero.
876 ComputeMaskedBits(I->getOperand(1), DemandedMask,
877 RHSKnownZero, RHSKnownOne, Depth+1);
878 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
879 LHSKnownZero, LHSKnownOne, Depth+1);
880
881 // If all of the demanded bits are known 1 on one side, return the other.
882 // These bits cannot contribute to the result of the 'and' in this
883 // context.
884 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
885 (DemandedMask & ~LHSKnownZero))
886 return I->getOperand(0);
887 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
888 (DemandedMask & ~RHSKnownZero))
889 return I->getOperand(1);
890
891 // If all of the demanded bits in the inputs are known zeros, return zero.
892 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000893 return Context->getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000894
895 } else if (I->getOpcode() == Instruction::Or) {
896 // We can simplify (X|Y) -> X or Y in the user's context if we know that
897 // only bits from X or Y are demanded.
898
899 // If either the LHS or the RHS are One, the result is One.
900 ComputeMaskedBits(I->getOperand(1), DemandedMask,
901 RHSKnownZero, RHSKnownOne, Depth+1);
902 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
903 LHSKnownZero, LHSKnownOne, Depth+1);
904
905 // If all of the demanded bits are known zero on one side, return the
906 // other. These bits cannot contribute to the result of the 'or' in this
907 // context.
908 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
909 (DemandedMask & ~LHSKnownOne))
910 return I->getOperand(0);
911 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
912 (DemandedMask & ~RHSKnownOne))
913 return I->getOperand(1);
914
915 // If all of the potentially set bits on one side are known to be set on
916 // the other side, just use the 'other' side.
917 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
918 (DemandedMask & (~RHSKnownZero)))
919 return I->getOperand(0);
920 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
921 (DemandedMask & (~LHSKnownZero)))
922 return I->getOperand(1);
923 }
924
Chris Lattner4598c942009-01-31 08:24:16 +0000925 // Compute the KnownZero/KnownOne bits to simplify things downstream.
926 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
927 return 0;
928 }
929
930 // If this is the root being simplified, allow it to have multiple uses,
931 // just set the DemandedMask to all bits so that we can try to simplify the
932 // operands. This allows visitTruncInst (for example) to simplify the
933 // operand of a trunc without duplicating all the logic below.
934 if (Depth == 0 && !V->hasOneUse())
935 DemandedMask = APInt::getAllOnesValue(BitWidth);
936
Reid Spencer8cb68342007-03-12 17:25:59 +0000937 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000938 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000939 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000940 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000941 case Instruction::And:
942 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000943 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
944 RHSKnownZero, RHSKnownOne, Depth+1) ||
945 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000946 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000947 return I;
948 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
949 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000950
951 // If all of the demanded bits are known 1 on one side, return the other.
952 // These bits cannot contribute to the result of the 'and'.
953 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
954 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000955 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000956 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
957 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000958 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000959
960 // If all of the demanded bits in the inputs are known zeros, return zero.
961 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000962 return Context->getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000963
964 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000965 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000966 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000967
968 // Output known-1 bits are only known if set in both the LHS & RHS.
969 RHSKnownOne &= LHSKnownOne;
970 // Output known-0 are known to be clear if zero in either the LHS | RHS.
971 RHSKnownZero |= LHSKnownZero;
972 break;
973 case Instruction::Or:
974 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000975 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
976 RHSKnownZero, RHSKnownOne, Depth+1) ||
977 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000978 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000979 return I;
980 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
981 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000982
983 // If all of the demanded bits are known zero on one side, return the other.
984 // These bits cannot contribute to the result of the 'or'.
985 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
986 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000987 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000988 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
989 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000990 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000991
992 // If all of the potentially set bits on one side are known to be set on
993 // the other side, just use the 'other' side.
994 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
995 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000996 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000997 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
998 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000999 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001000
1001 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +00001002 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001003 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001004
1005 // Output known-0 bits are only known if clear in both the LHS & RHS.
1006 RHSKnownZero &= LHSKnownZero;
1007 // Output known-1 are known to be set if set in either the LHS | RHS.
1008 RHSKnownOne |= LHSKnownOne;
1009 break;
1010 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001011 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1012 RHSKnownZero, RHSKnownOne, Depth+1) ||
1013 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001014 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001015 return I;
1016 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1017 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001018
1019 // If all of the demanded bits are known zero on one side, return the other.
1020 // These bits cannot contribute to the result of the 'xor'.
1021 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001022 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001023 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001024 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001025
1026 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1027 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1028 (RHSKnownOne & LHSKnownOne);
1029 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1030 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1031 (RHSKnownOne & LHSKnownZero);
1032
1033 // If all of the demanded bits are known to be zero on one side or the
1034 // other, turn this into an *inclusive* or.
1035 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1036 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1037 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001038 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001039 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001040 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001041 }
1042
1043 // If all of the demanded bits on one side are known, and all of the set
1044 // bits on that side are also known to be set on the other side, turn this
1045 // into an AND, as we know the bits will be cleared.
1046 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1047 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1048 // all known
1049 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001050 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001051 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001052 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001053 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001054 }
1055 }
1056
1057 // If the RHS is a constant, see if we can simplify it.
1058 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Andersond672ecb2009-07-03 00:17:18 +00001059 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001061
1062 RHSKnownZero = KnownZeroOut;
1063 RHSKnownOne = KnownOneOut;
1064 break;
1065 }
1066 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1068 RHSKnownZero, RHSKnownOne, Depth+1) ||
1069 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001070 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001071 return I;
1072 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1073 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001074
1075 // If the operands are constants, see if we can simplify them.
Owen Andersond672ecb2009-07-03 00:17:18 +00001076 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1077 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001079
1080 // Only known if known in both the LHS and RHS.
1081 RHSKnownOne &= LHSKnownOne;
1082 RHSKnownZero &= LHSKnownZero;
1083 break;
1084 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001085 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001086 DemandedMask.zext(truncBf);
1087 RHSKnownZero.zext(truncBf);
1088 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001089 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001090 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001091 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001092 DemandedMask.trunc(BitWidth);
1093 RHSKnownZero.trunc(BitWidth);
1094 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001095 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001096 break;
1097 }
1098 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001099 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001100 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001101
1102 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1103 if (const VectorType *SrcVTy =
1104 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1105 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1106 // Don't touch a bitcast between vectors of different element counts.
1107 return false;
1108 } else
1109 // Don't touch a scalar-to-vector bitcast.
1110 return false;
1111 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1112 // Don't touch a vector-to-scalar bitcast.
1113 return false;
1114
Chris Lattner886ab6c2009-01-31 08:15:18 +00001115 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001116 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001117 return I;
1118 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 break;
1120 case Instruction::ZExt: {
1121 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001122 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001123
Zhou Shengd48653a2007-03-29 04:45:55 +00001124 DemandedMask.trunc(SrcBitWidth);
1125 RHSKnownZero.trunc(SrcBitWidth);
1126 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001127 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001128 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001129 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001130 DemandedMask.zext(BitWidth);
1131 RHSKnownZero.zext(BitWidth);
1132 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001133 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001134 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001135 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001136 break;
1137 }
1138 case Instruction::SExt: {
1139 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001140 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001141
Reid Spencer8cb68342007-03-12 17:25:59 +00001142 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001143 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001144
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001146 // If any of the sign extended bits are demanded, we know that the sign
1147 // bit is demanded.
1148 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001149 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001150
Zhou Shengd48653a2007-03-29 04:45:55 +00001151 InputDemandedBits.trunc(SrcBitWidth);
1152 RHSKnownZero.trunc(SrcBitWidth);
1153 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001154 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001155 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001156 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001157 InputDemandedBits.zext(BitWidth);
1158 RHSKnownZero.zext(BitWidth);
1159 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001160 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001161
1162 // If the sign bit of the input is known set or clear, then we know the
1163 // top bits of the result.
1164
1165 // If the input sign bit is known zero, or if the NewBits are not demanded
1166 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001167 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001168 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001169 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1170 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001171 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001172 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001173 }
1174 break;
1175 }
1176 case Instruction::Add: {
1177 // Figure out what the input bits are. If the top bits of the and result
1178 // are not demanded, then the add doesn't demand them from its input
1179 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001180 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001181
1182 // If there is a constant on the RHS, there are a variety of xformations
1183 // we can do.
1184 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1185 // If null, this should be simplified elsewhere. Some of the xforms here
1186 // won't work if the RHS is zero.
1187 if (RHS->isZero())
1188 break;
1189
1190 // If the top bit of the output is demanded, demand everything from the
1191 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001192 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001193
1194 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001195 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001196 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001197 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001198
1199 // If the RHS of the add has bits set that can't affect the input, reduce
1200 // the constant.
Owen Andersond672ecb2009-07-03 00:17:18 +00001201 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001202 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001203
1204 // Avoid excess work.
1205 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1206 break;
1207
1208 // Turn it into OR if input bits are zero.
1209 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1210 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001211 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001212 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001213 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001214 }
1215
1216 // We can say something about the output known-zero and known-one bits,
1217 // depending on potential carries from the input constant and the
1218 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1219 // bits set and the RHS constant is 0x01001, then we know we have a known
1220 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1221
1222 // To compute this, we first compute the potential carry bits. These are
1223 // the bits which may be modified. I'm not aware of a better way to do
1224 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001225 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001226 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001227
1228 // Now that we know which bits have carries, compute the known-1/0 sets.
1229
1230 // Bits are known one if they are known zero in one operand and one in the
1231 // other, and there is no input carry.
1232 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1233 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1234
1235 // Bits are known zero if they are known zero in both operands and there
1236 // is no input carry.
1237 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1238 } else {
1239 // If the high-bits of this ADD are not demanded, then it does not demand
1240 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001241 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001242 // Right fill the mask of bits for this ADD to demand the most
1243 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001244 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001245 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1246 LHSKnownZero, LHSKnownOne, Depth+1) ||
1247 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001248 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001249 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001250 }
1251 }
1252 break;
1253 }
1254 case Instruction::Sub:
1255 // If the high-bits of this SUB are not demanded, then it does not demand
1256 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001257 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001258 // Right fill the mask of bits for this SUB to demand the most
1259 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001260 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001261 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001262 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1263 LHSKnownZero, LHSKnownOne, Depth+1) ||
1264 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001266 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001268 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1269 // the known zeros and ones.
1270 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001271 break;
1272 case Instruction::Shl:
1273 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001274 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001275 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001276 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001277 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001278 return I;
1279 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001280 RHSKnownZero <<= ShiftAmt;
1281 RHSKnownOne <<= ShiftAmt;
1282 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001283 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001284 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 }
1286 break;
1287 case Instruction::LShr:
1288 // For a logical shift right
1289 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001290 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001291
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001293 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001294 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001296 return I;
1297 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1299 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001300 if (ShiftAmt) {
1301 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001302 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001303 RHSKnownZero |= HighBits; // high bits known zero.
1304 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001305 }
1306 break;
1307 case Instruction::AShr:
1308 // If this is an arithmetic shift right and only the low-bit is set, we can
1309 // always convert this into a logical shr, even if the shift amount is
1310 // variable. The low bit of the shift cannot be an input sign bit unless
1311 // the shift amount is >= the size of the datatype, which is undefined.
1312 if (DemandedMask == 1) {
1313 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001314 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001315 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001316 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001318
1319 // If the sign bit is the only bit demanded by this ashr, then there is no
1320 // need to do it, the shift doesn't change the high bit.
1321 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001323
1324 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001325 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001326
Reid Spencer8cb68342007-03-12 17:25:59 +00001327 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001328 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001329 // If any of the "high bits" are demanded, we should set the sign bit as
1330 // demanded.
1331 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1332 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001333 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001334 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001335 return I;
1336 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001337 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001338 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001339 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1340 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1341
1342 // Handle the sign bits.
1343 APInt SignBit(APInt::getSignBit(BitWidth));
1344 // Adjust to where it is now in the mask.
1345 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1346
1347 // If the input sign bit is known to be zero, or if none of the top bits
1348 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001349 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001350 (HighBits & ~DemandedMask) == HighBits) {
1351 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001352 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001353 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001354 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001355 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1356 RHSKnownOne |= HighBits;
1357 }
1358 }
1359 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001360 case Instruction::SRem:
1361 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001362 APInt RA = Rem->getValue().abs();
1363 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001364 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001365 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001366
Nick Lewycky8e394322008-11-02 02:41:50 +00001367 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001368 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001369 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001370 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001371 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001372
1373 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1374 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001375
1376 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001377
Chris Lattner886ab6c2009-01-31 08:15:18 +00001378 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001379 }
1380 }
1381 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001382 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001383 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1384 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001385 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1386 KnownZero2, KnownOne2, Depth+1) ||
1387 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001388 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001389 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001390
Chris Lattner455e9ab2009-01-21 18:09:24 +00001391 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001392 Leaders = std::max(Leaders,
1393 KnownZero2.countLeadingOnes());
1394 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001395 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001396 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001397 case Instruction::Call:
1398 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1399 switch (II->getIntrinsicID()) {
1400 default: break;
1401 case Intrinsic::bswap: {
1402 // If the only bits demanded come from one byte of the bswap result,
1403 // just shift the input byte into position to eliminate the bswap.
1404 unsigned NLZ = DemandedMask.countLeadingZeros();
1405 unsigned NTZ = DemandedMask.countTrailingZeros();
1406
1407 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1408 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1409 // have 14 leading zeros, round to 8.
1410 NLZ &= ~7;
1411 NTZ &= ~7;
1412 // If we need exactly one byte, we can do this transformation.
1413 if (BitWidth-NLZ-NTZ == 8) {
1414 unsigned ResultBit = NTZ;
1415 unsigned InputBit = BitWidth-NTZ-8;
1416
1417 // Replace this with either a left or right shift to get the byte into
1418 // the right place.
1419 Instruction *NewVal;
1420 if (InputBit > ResultBit)
1421 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001422 Context->getConstantInt(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001423 else
1424 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001425 Context->getConstantInt(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001426 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001427 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001428 }
1429
1430 // TODO: Could compute known zero/one bits based on the input.
1431 break;
1432 }
1433 }
1434 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001435 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001436 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001437 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001438
1439 // If the client is only demanding bits that we know, return the known
1440 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001441 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001442 Constant *C = Context->getConstantInt(RHSKnownOne);
Dan Gohman1c8491e2009-04-25 17:12:48 +00001443 if (isa<PointerType>(V->getType()))
Owen Andersond672ecb2009-07-03 00:17:18 +00001444 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman1c8491e2009-04-25 17:12:48 +00001445 return C;
1446 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001447 return false;
1448}
1449
Chris Lattner867b99f2006-10-05 06:55:50 +00001450
Mon P Wangaeb06d22008-11-10 04:46:22 +00001451/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001452/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001453/// actually used by the caller. This method analyzes which elements of the
1454/// operand are undef and returns that information in UndefElts.
1455///
1456/// If the information about demanded elements can be used to simplify the
1457/// operation, the operation is simplified, then the resultant value is
1458/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001459Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1460 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001461 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001462 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001463 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001464 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001465
1466 if (isa<UndefValue>(V)) {
1467 // If the entire vector is undefined, just return this info.
1468 UndefElts = EltMask;
1469 return 0;
1470 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1471 UndefElts = EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001472 return Context->getUndef(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001473 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001474
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001476 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1477 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001478 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001479
1480 std::vector<Constant*> Elts;
1481 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001482 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001483 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001484 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001485 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1486 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001487 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001488 } else { // Otherwise, defined.
1489 Elts.push_back(CP->getOperand(i));
1490 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001491
Chris Lattner867b99f2006-10-05 06:55:50 +00001492 // If we changed the constant, return it.
Owen Andersond672ecb2009-07-03 00:17:18 +00001493 Constant *NewCP = Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001494 return NewCP != CP ? NewCP : 0;
1495 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001496 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001497 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001498
1499 // Check if this is identity. If so, return 0 since we are not simplifying
1500 // anything.
1501 if (DemandedElts == ((1ULL << VWidth) -1))
1502 return 0;
1503
Reid Spencer9d6565a2007-02-15 02:26:10 +00001504 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001505 Constant *Zero = Context->getNullValue(EltTy);
1506 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001507 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001508 for (unsigned i = 0; i != VWidth; ++i) {
1509 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1510 Elts.push_back(Elt);
1511 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001512 UndefElts = DemandedElts ^ EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001513 return Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001514 }
1515
Dan Gohman488fbfc2008-09-09 18:11:14 +00001516 // Limit search depth.
1517 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001518 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001519
1520 // If multiple users are using the root value, procede with
1521 // simplification conservatively assuming that all elements
1522 // are needed.
1523 if (!V->hasOneUse()) {
1524 // Quit if we find multiple users of a non-root value though.
1525 // They'll be handled when it's their turn to be visited by
1526 // the main instcombine process.
1527 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001528 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001529 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001530
1531 // Conservatively assume that all elements are needed.
1532 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001533 }
1534
1535 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001536 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001537
1538 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001539 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001540 Value *TmpV;
1541 switch (I->getOpcode()) {
1542 default: break;
1543
1544 case Instruction::InsertElement: {
1545 // If this is a variable index, we don't know which element it overwrites.
1546 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001547 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001548 if (Idx == 0) {
1549 // Note that we can't propagate undef elt info, because we don't know
1550 // which elt is getting updated.
1551 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1552 UndefElts2, Depth+1);
1553 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1554 break;
1555 }
1556
1557 // If this is inserting an element that isn't demanded, remove this
1558 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001559 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001560 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001561 return AddSoonDeadInstToWorklist(*I, 0);
1562
1563 // Otherwise, the element inserted overwrites whatever was there, so the
1564 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001565 APInt DemandedElts2 = DemandedElts;
1566 DemandedElts2.clear(IdxNo);
1567 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001568 UndefElts, Depth+1);
1569 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1570
1571 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001572 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001573 break;
1574 }
1575 case Instruction::ShuffleVector: {
1576 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001577 uint64_t LHSVWidth =
1578 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001579 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001580 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001581 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001582 unsigned MaskVal = Shuffle->getMaskValue(i);
1583 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001584 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001585 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001586 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001587 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001588 else
Evan Cheng388df622009-02-03 10:05:09 +00001589 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001590 }
1591 }
1592 }
1593
Nate Begeman7b254672009-02-11 22:36:25 +00001594 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001595 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001596 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001597 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1598
Nate Begeman7b254672009-02-11 22:36:25 +00001599 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001600 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1601 UndefElts3, Depth+1);
1602 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1603
1604 bool NewUndefElts = false;
1605 for (unsigned i = 0; i < VWidth; i++) {
1606 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001607 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001608 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001609 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001610 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001611 NewUndefElts = true;
1612 UndefElts.set(i);
1613 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001614 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001615 if (UndefElts3[MaskVal - LHSVWidth]) {
1616 NewUndefElts = true;
1617 UndefElts.set(i);
1618 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001619 }
1620 }
1621
1622 if (NewUndefElts) {
1623 // Add additional discovered undefs.
1624 std::vector<Constant*> Elts;
1625 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001626 if (UndefElts[i])
Owen Andersond672ecb2009-07-03 00:17:18 +00001627 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001628 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001629 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001630 Shuffle->getMaskValue(i)));
1631 }
Owen Andersond672ecb2009-07-03 00:17:18 +00001632 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001633 MadeChange = true;
1634 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001635 break;
1636 }
Chris Lattner69878332007-04-14 22:29:23 +00001637 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001638 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001639 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1640 if (!VTy) break;
1641 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001642 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001643 unsigned Ratio;
1644
1645 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001646 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001647 // elements as are demanded of us.
1648 Ratio = 1;
1649 InputDemandedElts = DemandedElts;
1650 } else if (VWidth > InVWidth) {
1651 // Untested so far.
1652 break;
1653
1654 // If there are more elements in the result than there are in the source,
1655 // then an input element is live if any of the corresponding output
1656 // elements are live.
1657 Ratio = VWidth/InVWidth;
1658 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001659 if (DemandedElts[OutIdx])
1660 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001661 }
1662 } else {
1663 // Untested so far.
1664 break;
1665
1666 // If there are more elements in the source than there are in the result,
1667 // then an input element is live if the corresponding output element is
1668 // live.
1669 Ratio = InVWidth/VWidth;
1670 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001671 if (DemandedElts[InIdx/Ratio])
1672 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001673 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001674
Chris Lattner69878332007-04-14 22:29:23 +00001675 // div/rem demand all inputs, because they don't want divide by zero.
1676 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1677 UndefElts2, Depth+1);
1678 if (TmpV) {
1679 I->setOperand(0, TmpV);
1680 MadeChange = true;
1681 }
1682
1683 UndefElts = UndefElts2;
1684 if (VWidth > InVWidth) {
Torok Edwinc25e7582009-07-11 20:10:48 +00001685 LLVM_UNREACHABLE("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001686 // If there are more elements in the result than there are in the source,
1687 // then an output element is undef if the corresponding input element is
1688 // undef.
1689 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001690 if (UndefElts2[OutIdx/Ratio])
1691 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001692 } else if (VWidth < InVWidth) {
Torok Edwinc25e7582009-07-11 20:10:48 +00001693 LLVM_UNREACHABLE("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001694 // If there are more elements in the source than there are in the result,
1695 // then a result element is undef if all of the corresponding input
1696 // elements are undef.
1697 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1698 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001699 if (!UndefElts2[InIdx]) // Not undef?
1700 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001701 }
1702 break;
1703 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001704 case Instruction::And:
1705 case Instruction::Or:
1706 case Instruction::Xor:
1707 case Instruction::Add:
1708 case Instruction::Sub:
1709 case Instruction::Mul:
1710 // div/rem demand all inputs, because they don't want divide by zero.
1711 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1712 UndefElts, Depth+1);
1713 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1714 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1715 UndefElts2, Depth+1);
1716 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1717
1718 // Output elements are undefined if both are undefined. Consider things
1719 // like undef&0. The result is known zero, not undef.
1720 UndefElts &= UndefElts2;
1721 break;
1722
1723 case Instruction::Call: {
1724 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1725 if (!II) break;
1726 switch (II->getIntrinsicID()) {
1727 default: break;
1728
1729 // Binary vector operations that work column-wise. A dest element is a
1730 // function of the corresponding input elements from the two inputs.
1731 case Intrinsic::x86_sse_sub_ss:
1732 case Intrinsic::x86_sse_mul_ss:
1733 case Intrinsic::x86_sse_min_ss:
1734 case Intrinsic::x86_sse_max_ss:
1735 case Intrinsic::x86_sse2_sub_sd:
1736 case Intrinsic::x86_sse2_mul_sd:
1737 case Intrinsic::x86_sse2_min_sd:
1738 case Intrinsic::x86_sse2_max_sd:
1739 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1740 UndefElts, Depth+1);
1741 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1742 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1743 UndefElts2, Depth+1);
1744 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1745
1746 // If only the low elt is demanded and this is a scalarizable intrinsic,
1747 // scalarize it now.
1748 if (DemandedElts == 1) {
1749 switch (II->getIntrinsicID()) {
1750 default: break;
1751 case Intrinsic::x86_sse_sub_ss:
1752 case Intrinsic::x86_sse_mul_ss:
1753 case Intrinsic::x86_sse2_sub_sd:
1754 case Intrinsic::x86_sse2_mul_sd:
1755 // TODO: Lower MIN/MAX/ABS/etc
1756 Value *LHS = II->getOperand(1);
1757 Value *RHS = II->getOperand(2);
1758 // Extract the element as scalars.
1759 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1760 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1761
1762 switch (II->getIntrinsicID()) {
Torok Edwinc25e7582009-07-11 20:10:48 +00001763 default: LLVM_UNREACHABLE("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001764 case Intrinsic::x86_sse_sub_ss:
1765 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001766 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001767 II->getName()), *II);
1768 break;
1769 case Intrinsic::x86_sse_mul_ss:
1770 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001771 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001772 II->getName()), *II);
1773 break;
1774 }
1775
1776 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001777 InsertElementInst::Create(
1778 Context->getUndef(II->getType()), TmpV, 0U, II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001779 InsertNewInstBefore(New, *II);
1780 AddSoonDeadInstToWorklist(*II, 0);
1781 return New;
1782 }
1783 }
1784
1785 // Output elements are undefined if both are undefined. Consider things
1786 // like undef&0. The result is known zero, not undef.
1787 UndefElts &= UndefElts2;
1788 break;
1789 }
1790 break;
1791 }
1792 }
1793 return MadeChange ? I : 0;
1794}
1795
Dan Gohman45b4e482008-05-19 22:14:15 +00001796
Chris Lattner564a7272003-08-13 19:01:45 +00001797/// AssociativeOpt - Perform an optimization on an associative operator. This
1798/// function is designed to check a chain of associative operators for a
1799/// potential to apply a certain optimization. Since the optimization may be
1800/// applicable if the expression was reassociated, this checks the chain, then
1801/// reassociates the expression as necessary to expose the optimization
1802/// opportunity. This makes use of a special Functor, which must define
1803/// 'shouldApply' and 'apply' methods.
1804///
1805template<typename Functor>
Owen Andersond672ecb2009-07-03 00:17:18 +00001806static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001807 LLVMContext *Context) {
Chris Lattner564a7272003-08-13 19:01:45 +00001808 unsigned Opcode = Root.getOpcode();
1809 Value *LHS = Root.getOperand(0);
1810
1811 // Quick check, see if the immediate LHS matches...
1812 if (F.shouldApply(LHS))
1813 return F.apply(Root);
1814
1815 // Otherwise, if the LHS is not of the same opcode as the root, return.
1816 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001817 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001818 // Should we apply this transform to the RHS?
1819 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1820
1821 // If not to the RHS, check to see if we should apply to the LHS...
1822 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1823 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1824 ShouldApply = true;
1825 }
1826
1827 // If the functor wants to apply the optimization to the RHS of LHSI,
1828 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1829 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001830 // Now all of the instructions are in the current basic block, go ahead
1831 // and perform the reassociation.
1832 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1833
1834 // First move the selected RHS to the LHS of the root...
1835 Root.setOperand(0, LHSI->getOperand(1));
1836
1837 // Make what used to be the LHS of the root be the user of the root...
1838 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001839 if (&Root == TmpLHSI) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001840 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001841 return 0;
1842 }
Chris Lattner65725312004-04-16 18:08:07 +00001843 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001844 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001845 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001846 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001847 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001848
1849 // Now propagate the ExtraOperand down the chain of instructions until we
1850 // get to LHSI.
1851 while (TmpLHSI != LHSI) {
1852 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001853 // Move the instruction to immediately before the chain we are
1854 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001855 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001856 ARI = NextLHSI;
1857
Chris Lattner564a7272003-08-13 19:01:45 +00001858 Value *NextOp = NextLHSI->getOperand(1);
1859 NextLHSI->setOperand(1, ExtraOperand);
1860 TmpLHSI = NextLHSI;
1861 ExtraOperand = NextOp;
1862 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001863
Chris Lattner564a7272003-08-13 19:01:45 +00001864 // Now that the instructions are reassociated, have the functor perform
1865 // the transformation...
1866 return F.apply(Root);
1867 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001868
Chris Lattner564a7272003-08-13 19:01:45 +00001869 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1870 }
1871 return 0;
1872}
1873
Dan Gohman844731a2008-05-13 00:00:25 +00001874namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001875
Nick Lewycky02d639f2008-05-23 04:34:58 +00001876// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001877struct AddRHS {
1878 Value *RHS;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001879 LLVMContext *Context;
1880 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001881 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1882 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001883 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00001884 Context->getConstantInt(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001885 }
1886};
1887
1888// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1889// iff C1&C2 == 0
1890struct AddMaskingAnd {
1891 Constant *C2;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001892 LLVMContext *Context;
1893 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001894 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001895 ConstantInt *C1;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001896 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Andersond672ecb2009-07-03 00:17:18 +00001897 Context->getConstantExprAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001898 }
1899 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001900 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001901 }
1902};
1903
Dan Gohman844731a2008-05-13 00:00:25 +00001904}
1905
Chris Lattner6e7ba452005-01-01 16:22:27 +00001906static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001907 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001908 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001909
Reid Spencer3da59db2006-11-27 01:05:10 +00001910 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001911 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001912 }
1913
Chris Lattner2eefe512004-04-09 19:05:30 +00001914 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001915 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1916 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001917
Chris Lattner2eefe512004-04-09 19:05:30 +00001918 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1919 if (ConstIsRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001920 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1921 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001922 }
1923
1924 Value *Op0 = SO, *Op1 = ConstOperand;
1925 if (!ConstIsRHS)
1926 std::swap(Op0, Op1);
1927 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001928 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001929 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001930 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001931 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1932 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001933 else {
Torok Edwin7d696d82009-07-11 13:10:19 +00001934 LLVM_UNREACHABLE("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001935 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001936 return IC->InsertNewInstBefore(New, I);
1937}
1938
1939// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1940// constant as the other operand, try to fold the binary operator into the
1941// select arguments. This also works for Cast instructions, which obviously do
1942// not have a second operand.
1943static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1944 InstCombiner *IC) {
1945 // Don't modify shared select instructions
1946 if (!SI->hasOneUse()) return 0;
1947 Value *TV = SI->getOperand(1);
1948 Value *FV = SI->getOperand(2);
1949
1950 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001951 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001952 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001953
Chris Lattner6e7ba452005-01-01 16:22:27 +00001954 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1955 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1956
Gabor Greif051a9502008-04-06 20:25:17 +00001957 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1958 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001959 }
1960 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001961}
1962
Chris Lattner4e998b22004-09-29 05:07:12 +00001963
1964/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1965/// node as operand #0, see if we can fold the instruction into the PHI (which
1966/// is only possible if all operands to the PHI are constants).
1967Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1968 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001969 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001970 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001971
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001972 // Check to see if all of the operands of the PHI are constants. If there is
1973 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001974 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001975 BasicBlock *NonConstBB = 0;
1976 for (unsigned i = 0; i != NumPHIValues; ++i)
1977 if (!isa<Constant>(PN->getIncomingValue(i))) {
1978 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001979 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001980 NonConstBB = PN->getIncomingBlock(i);
1981
1982 // If the incoming non-constant value is in I's block, we have an infinite
1983 // loop.
1984 if (NonConstBB == I.getParent())
1985 return 0;
1986 }
1987
1988 // If there is exactly one non-constant value, we can insert a copy of the
1989 // operation in that block. However, if this is a critical edge, we would be
1990 // inserting the computation one some other paths (e.g. inside a loop). Only
1991 // do this if the pred block is unconditionally branching into the phi block.
1992 if (NonConstBB) {
1993 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1994 if (!BI || !BI->isUnconditional()) return 0;
1995 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001996
1997 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001998 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001999 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002000 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002001 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002002
2003 // Next, add all of the operands to the PHI.
2004 if (I.getNumOperands() == 2) {
2005 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002006 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002007 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002008 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002009 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersond672ecb2009-07-03 00:17:18 +00002010 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002011 else
Owen Andersond672ecb2009-07-03 00:17:18 +00002012 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002013 } else {
2014 assert(PN->getIncomingBlock(i) == NonConstBB);
2015 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002016 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002017 PN->getIncomingValue(i), C, "phitmp",
2018 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002019 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00002020 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002021 CI->getPredicate(),
2022 PN->getIncomingValue(i), C, "phitmp",
2023 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002024 else
Torok Edwinc25e7582009-07-11 20:10:48 +00002025 LLVM_UNREACHABLE("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002026
Chris Lattnerdbab3862007-03-02 21:28:56 +00002027 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002028 }
2029 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002030 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002031 } else {
2032 CastInst *CI = cast<CastInst>(&I);
2033 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002034 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002035 Value *InV;
2036 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002037 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002038 } else {
2039 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002040 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002041 I.getType(), "phitmp",
2042 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002043 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002044 }
2045 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002046 }
2047 }
2048 return ReplaceInstUsesWith(I, NewPN);
2049}
2050
Chris Lattner2454a2e2008-01-29 06:52:45 +00002051
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002052/// WillNotOverflowSignedAdd - Return true if we can prove that:
2053/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2054/// This basically requires proving that the add in the original type would not
2055/// overflow to change the sign bit or have a carry out.
2056bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2057 // There are different heuristics we can use for this. Here are some simple
2058 // ones.
2059
2060 // Add has the property that adding any two 2's complement numbers can only
2061 // have one carry bit which can change a sign. As such, if LHS and RHS each
2062 // have at least two sign bits, we know that the addition of the two values will
2063 // sign extend fine.
2064 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2065 return true;
2066
2067
2068 // If one of the operands only has one non-zero bit, and if the other operand
2069 // has a known-zero bit in a more significant place than it (not including the
2070 // sign bit) the ripple may go up to and fill the zero, but won't change the
2071 // sign. For example, (X & ~4) + 1.
2072
2073 // TODO: Implement.
2074
2075 return false;
2076}
2077
Chris Lattner2454a2e2008-01-29 06:52:45 +00002078
Chris Lattner7e708292002-06-25 16:13:24 +00002079Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002080 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002081 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002082
Chris Lattner66331a42004-04-10 22:01:55 +00002083 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002084 // X + undef -> undef
2085 if (isa<UndefValue>(RHS))
2086 return ReplaceInstUsesWith(I, RHS);
2087
Chris Lattner66331a42004-04-10 22:01:55 +00002088 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002089 if (RHSC->isNullValue())
2090 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002091
Chris Lattner66331a42004-04-10 22:01:55 +00002092 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002093 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002094 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002095 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002096 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002097 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002098
2099 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2100 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002101 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002102 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002103
2104 // zext(i1) - 1 -> select i1, 0, -1
2105 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2106 if (CI->isAllOnesValue() &&
2107 ZI->getOperand(0)->getType() == Type::Int1Ty)
2108 return SelectInst::Create(ZI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002109 Context->getNullValue(I.getType()),
2110 Context->getConstantIntAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00002111 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002112
2113 if (isa<PHINode>(LHS))
2114 if (Instruction *NV = FoldOpIntoPhi(I))
2115 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002116
Chris Lattner4f637d42006-01-06 17:59:59 +00002117 ConstantInt *XorRHS = 0;
2118 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002119 if (isa<ConstantInt>(RHSC) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002120 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002121 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002122 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002123
Zhou Sheng4351c642007-04-02 08:20:41 +00002124 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002125 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2126 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002127 do {
2128 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002129 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2130 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002131 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2132 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002133 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002134 if (!MaskedValueIsZero(XorLHS,
2135 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002136 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002137 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002138 }
2139 }
2140 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002141 C0080Val = APIntOps::lshr(C0080Val, Size);
2142 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2143 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002144
Reid Spencer35c38852007-03-28 01:36:16 +00002145 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002146 // with funny bit widths then this switch statement should be removed. It
2147 // is just here to get the size of the "middle" type back up to something
2148 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002149 const Type *MiddleType = 0;
2150 switch (Size) {
2151 default: break;
2152 case 32: MiddleType = Type::Int32Ty; break;
2153 case 16: MiddleType = Type::Int16Ty; break;
2154 case 8: MiddleType = Type::Int8Ty; break;
2155 }
2156 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002157 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002158 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002159 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002160 }
2161 }
Chris Lattner66331a42004-04-10 22:01:55 +00002162 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002163
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002164 if (I.getType() == Type::Int1Ty)
2165 return BinaryOperator::CreateXor(LHS, RHS);
2166
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002167 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002168 if (I.getType()->isInteger()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002169 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2170 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002171
2172 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2173 if (RHSI->getOpcode() == Instruction::Sub)
2174 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2175 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2176 }
2177 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2178 if (LHSI->getOpcode() == Instruction::Sub)
2179 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2180 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2181 }
Robert Bocchino71698282004-07-27 21:02:21 +00002182 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002183
Chris Lattner5c4afb92002-05-08 22:46:53 +00002184 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002185 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002186 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002187 if (LHS->getType()->isIntOrIntVector()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002188 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002189 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002190 InsertNewInstBefore(NewAdd, I);
Owen Anderson0a5372e2009-07-13 04:09:18 +00002191 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002192 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002193 }
2194
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002195 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002196 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002197
2198 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002199 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002200 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002201 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002202
Misha Brukmanfd939082005-04-21 23:48:37 +00002203
Chris Lattner50af16a2004-11-13 19:50:12 +00002204 ConstantInt *C2;
Owen Andersond672ecb2009-07-03 00:17:18 +00002205 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002206 if (X == RHS) // X*C + X --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002207 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002208
2209 // X*C1 + X*C2 --> X * (C1+C2)
2210 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002211 if (X == dyn_castFoldableMul(RHS, C1, Context))
2212 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002213 }
2214
2215 // X + X*C --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002216 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2217 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002218
Chris Lattnere617c9e2007-01-05 02:17:46 +00002219 // X + ~X --> -1 since ~X = -X-1
Owen Andersond672ecb2009-07-03 00:17:18 +00002220 if (dyn_castNotVal(LHS, Context) == RHS ||
2221 dyn_castNotVal(RHS, Context) == LHS)
2222 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002223
Chris Lattnerad3448c2003-02-18 19:57:07 +00002224
Chris Lattner564a7272003-08-13 19:01:45 +00002225 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002226 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002227 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002228 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002229
2230 // A+B --> A|B iff A and B have no bits set in common.
2231 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2232 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2233 APInt LHSKnownOne(IT->getBitWidth(), 0);
2234 APInt LHSKnownZero(IT->getBitWidth(), 0);
2235 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2236 if (LHSKnownZero != 0) {
2237 APInt RHSKnownOne(IT->getBitWidth(), 0);
2238 APInt RHSKnownZero(IT->getBitWidth(), 0);
2239 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2240
2241 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002242 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002243 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002244 }
2245 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002246
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002247 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002248 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002249 Value *W, *X, *Y, *Z;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002250 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2251 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002252 if (W != Y) {
2253 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002254 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002255 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002256 std::swap(W, X);
2257 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002258 std::swap(Y, Z);
2259 std::swap(W, X);
2260 }
2261 }
2262
2263 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002264 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002265 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002266 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002267 }
2268 }
2269 }
2270
Chris Lattner6b032052003-10-02 15:11:26 +00002271 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002272 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002273 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Andersond672ecb2009-07-03 00:17:18 +00002274 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002275
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002276 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002277 if (LHS->hasOneUse() &&
2278 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002279 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002280 if (Anded == CRHS) {
2281 // See if all bits from the first bit set in the Add RHS up are included
2282 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002283 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002284
2285 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002286 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002287
2288 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002289 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002290
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002291 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2292 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002293 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002294 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002295 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002296 }
2297 }
2298 }
2299
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002300 // Try to fold constant add into select arguments.
2301 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002302 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002303 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002304 }
2305
Reid Spencer1628cec2006-10-26 06:15:43 +00002306 // add (cast *A to intptrtype) B ->
Dan Gohmana119de82009-06-14 23:30:43 +00002307 // cast (GEP (cast *A to i8*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002308 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002309 CastInst *CI = dyn_cast<CastInst>(LHS);
2310 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002311 if (!CI) {
2312 CI = dyn_cast<CastInst>(RHS);
2313 Other = LHS;
2314 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002315 if (CI && CI->getType()->isSized() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00002316 (CI->getType()->getScalarSizeInBits() ==
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002317 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002318 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002319 unsigned AS =
2320 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002321 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002322 Context->getPointerType(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002323 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002324 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002325 }
2326 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002327
Chris Lattner42790482007-12-20 01:56:58 +00002328 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002329 {
2330 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002331 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002332 if (!SI) {
2333 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002334 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002335 }
Chris Lattner42790482007-12-20 01:56:58 +00002336 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002337 Value *TV = SI->getTrueValue();
2338 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002339 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002340
2341 // Can we fold the add into the argument of the select?
2342 // We check both true and false select arguments for a matching subtract.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002343 if (match(FV, m_Zero(), *Context) &&
2344 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002345 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002346 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002347 if (match(TV, m_Zero(), *Context) &&
2348 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002349 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002350 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002351 }
2352 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002353
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002354 // Check for (add (sext x), y), see if we can merge this into an
2355 // integer add followed by a sext.
2356 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2357 // (add (sext x), cst) --> (sext (add x, cst'))
2358 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2359 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002360 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002361 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002362 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002363 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2364 // Insert the new, smaller add.
2365 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2366 CI, "addconv");
2367 InsertNewInstBefore(NewAdd, I);
2368 return new SExtInst(NewAdd, I.getType());
2369 }
2370 }
2371
2372 // (add (sext x), (sext y)) --> (sext (add int x, y))
2373 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2374 // Only do this if x/y have the same type, if at last one of them has a
2375 // single use (so we don't increase the number of sexts), and if the
2376 // integer add will not overflow.
2377 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2378 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2379 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2380 RHSConv->getOperand(0))) {
2381 // Insert the new integer add.
2382 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2383 RHSConv->getOperand(0),
2384 "addconv");
2385 InsertNewInstBefore(NewAdd, I);
2386 return new SExtInst(NewAdd, I.getType());
2387 }
2388 }
2389 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002390
2391 return Changed ? &I : 0;
2392}
2393
2394Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2395 bool Changed = SimplifyCommutative(I);
2396 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2397
2398 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2399 // X + 0 --> X
2400 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002401 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002402 (I.getType())->getValueAPF()))
2403 return ReplaceInstUsesWith(I, LHS);
2404 }
2405
2406 if (isa<PHINode>(LHS))
2407 if (Instruction *NV = FoldOpIntoPhi(I))
2408 return NV;
2409 }
2410
2411 // -A + B --> B - A
2412 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002413 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002414 return BinaryOperator::CreateFSub(RHS, LHSV);
2415
2416 // A + -B --> A - B
2417 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002418 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002419 return BinaryOperator::CreateFSub(LHS, V);
2420
2421 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2422 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2423 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2424 return ReplaceInstUsesWith(I, LHS);
2425
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002426 // Check for (add double (sitofp x), y), see if we can merge this into an
2427 // integer add followed by a promotion.
2428 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2429 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2430 // ... if the constant fits in the integer value. This is useful for things
2431 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2432 // requires a constant pool load, and generally allows the add to be better
2433 // instcombined.
2434 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2435 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002436 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002437 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002438 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002439 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2440 // Insert the new integer add.
2441 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2442 CI, "addconv");
2443 InsertNewInstBefore(NewAdd, I);
2444 return new SIToFPInst(NewAdd, I.getType());
2445 }
2446 }
2447
2448 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2449 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2450 // Only do this if x/y have the same type, if at last one of them has a
2451 // single use (so we don't increase the number of int->fp conversions),
2452 // and if the integer add will not overflow.
2453 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2454 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2455 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2456 RHSConv->getOperand(0))) {
2457 // Insert the new integer add.
2458 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2459 RHSConv->getOperand(0),
2460 "addconv");
2461 InsertNewInstBefore(NewAdd, I);
2462 return new SIToFPInst(NewAdd, I.getType());
2463 }
2464 }
2465 }
2466
Chris Lattner7e708292002-06-25 16:13:24 +00002467 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002468}
2469
Chris Lattner7e708292002-06-25 16:13:24 +00002470Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002471 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002472
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002473 if (Op0 == Op1) // sub X, X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002474 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002475
Chris Lattner233f7dc2002-08-12 21:17:25 +00002476 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002477 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002478 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002479
Chris Lattnere87597f2004-10-16 18:11:37 +00002480 if (isa<UndefValue>(Op0))
2481 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2482 if (isa<UndefValue>(Op1))
2483 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2484
Chris Lattnerd65460f2003-11-05 01:06:05 +00002485 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2486 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002487 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002488 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002489
Chris Lattnerd65460f2003-11-05 01:06:05 +00002490 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002491 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002492 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002493 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002494
Chris Lattner76b7a062007-01-15 07:02:54 +00002495 // -(X >>u 31) -> (X >>s 31)
2496 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002497 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002498 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002499 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002500 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002501 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002502 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002503 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002504 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002505 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002506 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002507 }
2508 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002509 }
2510 else if (SI->getOpcode() == Instruction::AShr) {
2511 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2512 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002513 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002514 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002515 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002516 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002517 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002518 }
2519 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002520 }
2521 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002522 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002523
2524 // Try to fold constant sub into select arguments.
2525 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002526 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002527 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002528 }
2529
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002530 if (I.getType() == Type::Int1Ty)
2531 return BinaryOperator::CreateXor(Op0, Op1);
2532
Chris Lattner43d84d62005-04-07 16:15:25 +00002533 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002534 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002535 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002536 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2537 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002538 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002539 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2540 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002541 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2542 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2543 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002544 return BinaryOperator::CreateSub(
2545 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002546 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002547 }
2548
Chris Lattnerfd059242003-10-15 16:48:29 +00002549 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002550 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2551 // is not used by anyone else...
2552 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002553 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002554 // Swap the two operands of the subexpr...
2555 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2556 Op1I->setOperand(0, IIOp1);
2557 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002558
Chris Lattnera2881962003-02-18 19:28:33 +00002559 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002560 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002561 }
2562
2563 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2564 //
2565 if (Op1I->getOpcode() == Instruction::And &&
2566 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2567 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2568
Chris Lattnerf523d062004-06-09 05:08:07 +00002569 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002570 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2571 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002572 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002573
Reid Spencerac5209e2006-10-16 23:08:08 +00002574 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002575 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002576 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002577 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002578 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002579 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002580 Context->getConstantExprNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002581
Chris Lattnerad3448c2003-02-18 19:57:07 +00002582 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002583 ConstantInt *C2 = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00002584 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2585 Constant *CP1 =
2586 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002587 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002588 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002589 }
Chris Lattner40371712002-05-09 01:29:19 +00002590 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002591 }
Chris Lattnera2881962003-02-18 19:28:33 +00002592
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002593 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2594 if (Op0I->getOpcode() == Instruction::Add) {
2595 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2596 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2597 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2598 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2599 } else if (Op0I->getOpcode() == Instruction::Sub) {
2600 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002601 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2602 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002603 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002604 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002605
Chris Lattner50af16a2004-11-13 19:50:12 +00002606 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002607 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002608 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002609 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002610
Chris Lattner50af16a2004-11-13 19:50:12 +00002611 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Andersond672ecb2009-07-03 00:17:18 +00002612 if (X == dyn_castFoldableMul(Op1, C2, Context))
2613 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002614 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002615 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002616}
2617
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002618Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2619 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2620
2621 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002622 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002623 return BinaryOperator::CreateFAdd(Op0, V);
2624
2625 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2626 if (Op1I->getOpcode() == Instruction::FAdd) {
2627 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002628 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2629 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002630 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002631 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2632 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002633 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002634 }
2635
2636 return 0;
2637}
2638
Chris Lattnera0141b92007-07-15 20:42:37 +00002639/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2640/// comparison only checks the sign bit. If it only checks the sign bit, set
2641/// TrueIfSigned if the result of the comparison is true when the input value is
2642/// signed.
2643static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2644 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002645 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002646 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2647 TrueIfSigned = true;
2648 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002649 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2650 TrueIfSigned = true;
2651 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002652 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2653 TrueIfSigned = false;
2654 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002655 case ICmpInst::ICMP_UGT:
2656 // True if LHS u> RHS and RHS == high-bit-mask - 1
2657 TrueIfSigned = true;
2658 return RHS->getValue() ==
2659 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2660 case ICmpInst::ICMP_UGE:
2661 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2662 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002663 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002664 default:
2665 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002666 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002667}
2668
Chris Lattner7e708292002-06-25 16:13:24 +00002669Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002670 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002671 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002672
Dan Gohman77b81fe2009-06-04 17:12:12 +00002673 // TODO: If Op1 is undef and Op0 is finite, return zero.
2674 if (!I.getType()->isFPOrFPVector() &&
2675 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002676 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002677
Chris Lattner233f7dc2002-08-12 21:17:25 +00002678 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002679 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2680 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002681
2682 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002683 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002684 if (SI->getOpcode() == Instruction::Shl)
2685 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002686 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002687 Context->getConstantExprShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002688
Zhou Sheng843f07672007-04-19 05:39:12 +00002689 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002690 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2691 if (CI->equalsInt(1)) // X * 1 == X
2692 return ReplaceInstUsesWith(I, Op0);
2693 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002694 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002695
Zhou Sheng97b52c22007-03-29 01:57:21 +00002696 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002697 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002698 return BinaryOperator::CreateShl(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00002699 Context->getConstantInt(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002700 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002701 } else if (isa<VectorType>(Op1->getType())) {
Dan Gohman77b81fe2009-06-04 17:12:12 +00002702 // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
Nick Lewycky895f0852008-11-27 20:21:08 +00002703
2704 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2705 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002706 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002707
2708 // As above, vector X*splat(1.0) -> X in all defined cases.
2709 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002710 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2711 if (CI->equalsInt(1))
2712 return ReplaceInstUsesWith(I, Op0);
2713 }
2714 }
Chris Lattnera2881962003-02-18 19:28:33 +00002715 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002716
2717 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2718 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002719 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002720 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002721 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002722 Op1, "tmp");
2723 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00002724 Value *C1C2 = Context->getConstantExprMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002725 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002726 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002727
2728 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002729
2730 // Try to fold constant mul into select arguments.
2731 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002732 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002733 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002734
2735 if (isa<PHINode>(Op0))
2736 if (Instruction *NV = FoldOpIntoPhi(I))
2737 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002738 }
2739
Owen Andersond672ecb2009-07-03 00:17:18 +00002740 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2741 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002742 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002743
Nick Lewycky0c730792008-11-21 07:33:58 +00002744 // (X / Y) * Y = X - (X % Y)
2745 // (X / Y) * -Y = (X % Y) - X
2746 {
2747 Value *Op1 = I.getOperand(1);
2748 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2749 if (!BO ||
2750 (BO->getOpcode() != Instruction::UDiv &&
2751 BO->getOpcode() != Instruction::SDiv)) {
2752 Op1 = Op0;
2753 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2754 }
Owen Andersond672ecb2009-07-03 00:17:18 +00002755 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky0c730792008-11-21 07:33:58 +00002756 if (BO && BO->hasOneUse() &&
2757 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2758 (BO->getOpcode() == Instruction::UDiv ||
2759 BO->getOpcode() == Instruction::SDiv)) {
2760 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2761
2762 Instruction *Rem;
2763 if (BO->getOpcode() == Instruction::UDiv)
2764 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2765 else
2766 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2767
2768 InsertNewInstBefore(Rem, I);
2769 Rem->takeName(BO);
2770
2771 if (Op1BO == Op1)
2772 return BinaryOperator::CreateSub(Op0BO, Rem);
2773 else
2774 return BinaryOperator::CreateSub(Rem, Op0BO);
2775 }
2776 }
2777
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002778 if (I.getType() == Type::Int1Ty)
2779 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2780
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002781 // If one of the operands of the multiply is a cast from a boolean value, then
2782 // we know the bool is either zero or one, so this is a 'masking' multiply.
2783 // See if we can simplify things based on how the boolean was originally
2784 // formed.
2785 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002786 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002787 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002788 BoolCast = CI;
2789 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002790 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002791 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002792 BoolCast = CI;
2793 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002794 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002795 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2796 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002797 bool TIS = false;
2798
Reid Spencere4d87aa2006-12-23 06:05:41 +00002799 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002800 // multiply into a shift/and combination.
2801 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002802 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2803 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002804 // Shift the X value right to turn it into "all signbits".
Owen Andersond672ecb2009-07-03 00:17:18 +00002805 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002806 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002807 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002808 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002809 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002810 BoolCast->getOperand(0)->getName()+
2811 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002812
2813 // If the multiply type is not the same as the source type, sign extend
2814 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002815 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002816 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2817 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002818 Instruction::CastOps opcode =
2819 (SrcBits == DstBits ? Instruction::BitCast :
2820 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2821 V = InsertCastBefore(opcode, V, I.getType(), I);
2822 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002823
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002824 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002825 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002826 }
2827 }
2828 }
2829
Chris Lattner7e708292002-06-25 16:13:24 +00002830 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002831}
2832
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002833Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2834 bool Changed = SimplifyCommutative(I);
2835 Value *Op0 = I.getOperand(0);
2836
2837 // Simplify mul instructions with a constant RHS...
2838 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2839 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2840 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2841 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2842 if (Op1F->isExactlyValue(1.0))
2843 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2844 } else if (isa<VectorType>(Op1->getType())) {
2845 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2846 // As above, vector X*splat(1.0) -> X in all defined cases.
2847 if (Constant *Splat = Op1V->getSplatValue()) {
2848 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2849 if (F->isExactlyValue(1.0))
2850 return ReplaceInstUsesWith(I, Op0);
2851 }
2852 }
2853 }
2854
2855 // Try to fold constant mul into select arguments.
2856 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2857 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2858 return R;
2859
2860 if (isa<PHINode>(Op0))
2861 if (Instruction *NV = FoldOpIntoPhi(I))
2862 return NV;
2863 }
2864
Owen Andersond672ecb2009-07-03 00:17:18 +00002865 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2866 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002867 return BinaryOperator::CreateFMul(Op0v, Op1v);
2868
2869 return Changed ? &I : 0;
2870}
2871
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002872/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2873/// instruction.
2874bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2875 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2876
2877 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2878 int NonNullOperand = -1;
2879 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2880 if (ST->isNullValue())
2881 NonNullOperand = 2;
2882 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2883 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2884 if (ST->isNullValue())
2885 NonNullOperand = 1;
2886
2887 if (NonNullOperand == -1)
2888 return false;
2889
2890 Value *SelectCond = SI->getOperand(0);
2891
2892 // Change the div/rem to use 'Y' instead of the select.
2893 I.setOperand(1, SI->getOperand(NonNullOperand));
2894
2895 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2896 // problem. However, the select, or the condition of the select may have
2897 // multiple uses. Based on our knowledge that the operand must be non-zero,
2898 // propagate the known value for the select into other uses of it, and
2899 // propagate a known value of the condition into its other users.
2900
2901 // If the select and condition only have a single use, don't bother with this,
2902 // early exit.
2903 if (SI->use_empty() && SelectCond->hasOneUse())
2904 return true;
2905
2906 // Scan the current block backward, looking for other uses of SI.
2907 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2908
2909 while (BBI != BBFront) {
2910 --BBI;
2911 // If we found a call to a function, we can't assume it will return, so
2912 // information from below it cannot be propagated above it.
2913 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2914 break;
2915
2916 // Replace uses of the select or its condition with the known values.
2917 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2918 I != E; ++I) {
2919 if (*I == SI) {
2920 *I = SI->getOperand(NonNullOperand);
2921 AddToWorkList(BBI);
2922 } else if (*I == SelectCond) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002923 *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2924 Context->getConstantIntFalse();
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002925 AddToWorkList(BBI);
2926 }
2927 }
2928
2929 // If we past the instruction, quit looking for it.
2930 if (&*BBI == SI)
2931 SI = 0;
2932 if (&*BBI == SelectCond)
2933 SelectCond = 0;
2934
2935 // If we ran out of things to eliminate, break out of the loop.
2936 if (SelectCond == 0 && SI == 0)
2937 break;
2938
2939 }
2940 return true;
2941}
2942
2943
Reid Spencer1628cec2006-10-26 06:15:43 +00002944/// This function implements the transforms on div instructions that work
2945/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2946/// used by the visitors to those instructions.
2947/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002948Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002949 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002950
Chris Lattner50b2ca42008-02-19 06:12:18 +00002951 // undef / X -> 0 for integer.
2952 // undef / X -> undef for FP (the undef could be a snan).
2953 if (isa<UndefValue>(Op0)) {
2954 if (Op0->getType()->isFPOrFPVector())
2955 return ReplaceInstUsesWith(I, Op0);
Owen Andersond672ecb2009-07-03 00:17:18 +00002956 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002957 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002958
2959 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002960 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002961 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002962
Reid Spencer1628cec2006-10-26 06:15:43 +00002963 return 0;
2964}
Misha Brukmanfd939082005-04-21 23:48:37 +00002965
Reid Spencer1628cec2006-10-26 06:15:43 +00002966/// This function implements the transforms common to both integer division
2967/// instructions (udiv and sdiv). It is called by the visitors to those integer
2968/// division instructions.
2969/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002970Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2972
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002973 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002974 if (Op0 == Op1) {
2975 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002976 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002977 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00002978 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002979 }
2980
Owen Andersond672ecb2009-07-03 00:17:18 +00002981 Constant *CI = Context->getConstantInt(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002982 return ReplaceInstUsesWith(I, CI);
2983 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002984
Reid Spencer1628cec2006-10-26 06:15:43 +00002985 if (Instruction *Common = commonDivTransforms(I))
2986 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002987
2988 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2989 // This does not apply for fdiv.
2990 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2991 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002992
2993 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2994 // div X, 1 == X
2995 if (RHS->equalsInt(1))
2996 return ReplaceInstUsesWith(I, Op0);
2997
2998 // (X / C1) / C2 -> X / (C1*C2)
2999 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3000 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3001 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003002 if (MultiplyOverflows(RHS, LHSRHS,
3003 I.getOpcode()==Instruction::SDiv, Context))
3004 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003005 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003006 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00003007 Context->getConstantExprMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003008 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003009
Reid Spencerbca0e382007-03-23 20:05:17 +00003010 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003011 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3012 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3013 return R;
3014 if (isa<PHINode>(Op0))
3015 if (Instruction *NV = FoldOpIntoPhi(I))
3016 return NV;
3017 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003018 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003019
Chris Lattnera2881962003-02-18 19:28:33 +00003020 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003021 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003022 if (LHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003023 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003024
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003025 // It can't be division by zero, hence it must be division by one.
3026 if (I.getType() == Type::Int1Ty)
3027 return ReplaceInstUsesWith(I, Op0);
3028
Nick Lewycky895f0852008-11-27 20:21:08 +00003029 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3030 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3031 // div X, 1 == X
3032 if (X->isOne())
3033 return ReplaceInstUsesWith(I, Op0);
3034 }
3035
Reid Spencer1628cec2006-10-26 06:15:43 +00003036 return 0;
3037}
3038
3039Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3040 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3041
3042 // Handle the integer div common cases
3043 if (Instruction *Common = commonIDivTransforms(I))
3044 return Common;
3045
Reid Spencer1628cec2006-10-26 06:15:43 +00003046 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003047 // X udiv C^2 -> X >> C
3048 // Check to see if this is an unsigned division with an exact power of 2,
3049 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003050 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003051 return BinaryOperator::CreateLShr(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00003052 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003053
3054 // X udiv C, where C >= signbit
3055 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003056 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3057 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003058 I);
Owen Andersond672ecb2009-07-03 00:17:18 +00003059 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3060 Context->getConstantInt(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003061 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003062 }
3063
3064 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003065 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003066 if (RHSI->getOpcode() == Instruction::Shl &&
3067 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003068 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003069 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003070 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003071 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003072 if (uint32_t C2 = C1.logBase2()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003073 Constant *C2V = Context->getConstantInt(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003074 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003075 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003076 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003077 }
3078 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003079 }
3080
Reid Spencer1628cec2006-10-26 06:15:43 +00003081 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3082 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003083 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003084 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003085 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003086 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003087 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003088 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003089 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003090 // Construct the "on true" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003091 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003092 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003093 Op0, TC, SI->getName()+".t");
3094 TSI = InsertNewInstBefore(TSI, I);
3095
3096 // Construct the "on false" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003097 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003098 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003099 Op0, FC, SI->getName()+".f");
3100 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003101
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003102 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003103 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003104 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003105 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003106 return 0;
3107}
3108
Reid Spencer1628cec2006-10-26 06:15:43 +00003109Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3110 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3111
3112 // Handle the integer div common cases
3113 if (Instruction *Common = commonIDivTransforms(I))
3114 return Common;
3115
3116 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3117 // sdiv X, -1 == -X
3118 if (RHS->isAllOnesValue())
Owen Anderson0a5372e2009-07-13 04:09:18 +00003119 return BinaryOperator::CreateNeg(*Context, Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003120 }
3121
3122 // If the sign bits of both operands are zero (i.e. we can prove they are
3123 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003124 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003125 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003126 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003127 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003128 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003129 }
3130 }
3131
3132 return 0;
3133}
3134
3135Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3136 return commonDivTransforms(I);
3137}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003138
Reid Spencer0a783f72006-11-02 01:53:59 +00003139/// This function implements the transforms on rem instructions that work
3140/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3141/// is used by the visitors to those instructions.
3142/// @brief Transforms common to all three rem instructions
3143Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003144 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003145
Chris Lattner50b2ca42008-02-19 06:12:18 +00003146 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3147 if (I.getType()->isFPOrFPVector())
3148 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersond672ecb2009-07-03 00:17:18 +00003149 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003150 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003151 if (isa<UndefValue>(Op1))
3152 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003153
3154 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003155 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3156 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003157
Reid Spencer0a783f72006-11-02 01:53:59 +00003158 return 0;
3159}
3160
3161/// This function implements the transforms common to both integer remainder
3162/// instructions (urem and srem). It is called by the visitors to those integer
3163/// remainder instructions.
3164/// @brief Common integer remainder transforms
3165Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3166 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3167
3168 if (Instruction *common = commonRemTransforms(I))
3169 return common;
3170
Dale Johannesened6af242009-01-21 00:35:19 +00003171 // 0 % X == 0 for integer, we don't need to preserve faults!
3172 if (Constant *LHS = dyn_cast<Constant>(Op0))
3173 if (LHS->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00003174 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003175
Chris Lattner857e8cd2004-12-12 21:48:58 +00003176 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003177 // X % 0 == undef, we don't need to preserve faults!
3178 if (RHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003179 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003180
Chris Lattnera2881962003-02-18 19:28:33 +00003181 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003182 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003183
Chris Lattner97943922006-02-28 05:49:21 +00003184 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3185 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3186 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3187 return R;
3188 } else if (isa<PHINode>(Op0I)) {
3189 if (Instruction *NV = FoldOpIntoPhi(I))
3190 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003191 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003192
3193 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003194 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003195 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003196 }
Chris Lattnera2881962003-02-18 19:28:33 +00003197 }
3198
Reid Spencer0a783f72006-11-02 01:53:59 +00003199 return 0;
3200}
3201
3202Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3203 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3204
3205 if (Instruction *common = commonIRemTransforms(I))
3206 return common;
3207
3208 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3209 // X urem C^2 -> X and C
3210 // Check to see if this is an unsigned remainder with an exact power of 2,
3211 // if so, convert to a bitwise and.
3212 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003213 if (C->getValue().isPowerOf2())
Owen Andersond672ecb2009-07-03 00:17:18 +00003214 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer0a783f72006-11-02 01:53:59 +00003215 }
3216
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003217 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003218 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3219 if (RHSI->getOpcode() == Instruction::Shl &&
3220 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003221 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003222 Constant *N1 = Context->getConstantIntAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003223 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003224 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003225 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003226 }
3227 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003228 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003229
Reid Spencer0a783f72006-11-02 01:53:59 +00003230 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3231 // where C1&C2 are powers of two.
3232 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3233 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3234 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3235 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003236 if ((STO->getValue().isPowerOf2()) &&
3237 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003238 Value *TrueAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003239 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3240 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003241 Value *FalseAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003242 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3243 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003244 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003245 }
3246 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003247 }
3248
Chris Lattner3f5b8772002-05-06 16:14:14 +00003249 return 0;
3250}
3251
Reid Spencer0a783f72006-11-02 01:53:59 +00003252Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3253 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3254
Dan Gohmancff55092007-11-05 23:16:33 +00003255 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003256 if (Instruction *common = commonIRemTransforms(I))
3257 return common;
3258
Owen Andersond672ecb2009-07-03 00:17:18 +00003259 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky23c04302008-09-03 06:24:21 +00003260 if (!isa<Constant>(RHSNeg) ||
3261 (isa<ConstantInt>(RHSNeg) &&
3262 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003263 // X % -Y -> X % Y
3264 AddUsesToWorkList(I);
3265 I.setOperand(1, RHSNeg);
3266 return &I;
3267 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003268
Dan Gohmancff55092007-11-05 23:16:33 +00003269 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003270 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003271 if (I.getType()->isInteger()) {
3272 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3273 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3274 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003275 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003276 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003277 }
3278
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003279 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003280 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3281 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003282
Nick Lewycky9dce8732008-12-20 16:48:00 +00003283 bool hasNegative = false;
3284 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3285 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3286 if (RHS->getValue().isNegative())
3287 hasNegative = true;
3288
3289 if (hasNegative) {
3290 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003291 for (unsigned i = 0; i != VWidth; ++i) {
3292 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3293 if (RHS->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00003294 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003295 else
3296 Elts[i] = RHS;
3297 }
3298 }
3299
Owen Andersond672ecb2009-07-03 00:17:18 +00003300 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003301 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003302 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003303 I.setOperand(1, NewRHSV);
3304 return &I;
3305 }
3306 }
3307 }
3308
Reid Spencer0a783f72006-11-02 01:53:59 +00003309 return 0;
3310}
3311
3312Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003313 return commonRemTransforms(I);
3314}
3315
Chris Lattner457dd822004-06-09 07:59:58 +00003316// isOneBitSet - Return true if there is exactly one bit set in the specified
3317// constant.
3318static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003319 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003320}
3321
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003322// isHighOnes - Return true if the constant is of the form 1+0+.
3323// This is the same as lowones(~X).
3324static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003325 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003326}
3327
Reid Spencere4d87aa2006-12-23 06:05:41 +00003328/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003329/// are carefully arranged to allow folding of expressions such as:
3330///
3331/// (A < B) | (A > B) --> (A != B)
3332///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003333/// Note that this is only valid if the first and second predicates have the
3334/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003335///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003336/// Three bits are used to represent the condition, as follows:
3337/// 0 A > B
3338/// 1 A == B
3339/// 2 A < B
3340///
3341/// <=> Value Definition
3342/// 000 0 Always false
3343/// 001 1 A > B
3344/// 010 2 A == B
3345/// 011 3 A >= B
3346/// 100 4 A < B
3347/// 101 5 A != B
3348/// 110 6 A <= B
3349/// 111 7 Always true
3350///
3351static unsigned getICmpCode(const ICmpInst *ICI) {
3352 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003353 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003354 case ICmpInst::ICMP_UGT: return 1; // 001
3355 case ICmpInst::ICMP_SGT: return 1; // 001
3356 case ICmpInst::ICMP_EQ: return 2; // 010
3357 case ICmpInst::ICMP_UGE: return 3; // 011
3358 case ICmpInst::ICMP_SGE: return 3; // 011
3359 case ICmpInst::ICMP_ULT: return 4; // 100
3360 case ICmpInst::ICMP_SLT: return 4; // 100
3361 case ICmpInst::ICMP_NE: return 5; // 101
3362 case ICmpInst::ICMP_ULE: return 6; // 110
3363 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003364 // True -> 7
3365 default:
Torok Edwinc25e7582009-07-11 20:10:48 +00003366 LLVM_UNREACHABLE("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003367 return 0;
3368 }
3369}
3370
Evan Cheng8db90722008-10-14 17:15:11 +00003371/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3372/// predicate into a three bit mask. It also returns whether it is an ordered
3373/// predicate by reference.
3374static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3375 isOrdered = false;
3376 switch (CC) {
3377 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3378 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003379 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3380 case FCmpInst::FCMP_UGT: return 1; // 001
3381 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3382 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003383 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3384 case FCmpInst::FCMP_UGE: return 3; // 011
3385 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3386 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003387 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3388 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003389 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3390 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003391 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003392 default:
3393 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc25e7582009-07-11 20:10:48 +00003394 LLVM_UNREACHABLE("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003395 return 0;
3396 }
3397}
3398
Reid Spencere4d87aa2006-12-23 06:05:41 +00003399/// getICmpValue - This is the complement of getICmpCode, which turns an
3400/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003401/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003402/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003403static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003404 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003405 switch (code) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003406 default: LLVM_UNREACHABLE("Illegal ICmp code!");
Owen Andersond672ecb2009-07-03 00:17:18 +00003407 case 0: return Context->getConstantIntFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003408 case 1:
3409 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003410 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003411 else
Owen Anderson333c4002009-07-09 23:48:35 +00003412 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3413 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003414 case 3:
3415 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003416 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003417 else
Owen Anderson333c4002009-07-09 23:48:35 +00003418 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003419 case 4:
3420 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003421 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003422 else
Owen Anderson333c4002009-07-09 23:48:35 +00003423 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3424 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003425 case 6:
3426 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003427 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003428 else
Owen Anderson333c4002009-07-09 23:48:35 +00003429 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00003430 case 7: return Context->getConstantIntTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003431 }
3432}
3433
Evan Cheng8db90722008-10-14 17:15:11 +00003434/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3435/// opcode and two operands into either a FCmp instruction. isordered is passed
3436/// in to determine which kind of predicate to use in the new fcmp instruction.
3437static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003438 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003439 switch (code) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003440 default: LLVM_UNREACHABLE("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003441 case 0:
3442 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003443 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003444 else
Owen Anderson333c4002009-07-09 23:48:35 +00003445 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003446 case 1:
3447 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003448 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003449 else
Owen Anderson333c4002009-07-09 23:48:35 +00003450 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003451 case 2:
3452 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003453 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003454 else
Owen Anderson333c4002009-07-09 23:48:35 +00003455 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003456 case 3:
3457 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003458 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003459 else
Owen Anderson333c4002009-07-09 23:48:35 +00003460 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003461 case 4:
3462 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003463 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003464 else
Owen Anderson333c4002009-07-09 23:48:35 +00003465 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003466 case 5:
3467 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003468 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003469 else
Owen Anderson333c4002009-07-09 23:48:35 +00003470 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003471 case 6:
3472 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003473 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003474 else
Owen Anderson333c4002009-07-09 23:48:35 +00003475 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00003476 case 7: return Context->getConstantIntTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003477 }
3478}
3479
Chris Lattnerb9553d62008-11-16 04:55:20 +00003480/// PredicatesFoldable - Return true if both predicates match sign or if at
3481/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003482static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3483 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003484 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3485 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003486}
3487
3488namespace {
3489// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3490struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003491 InstCombiner &IC;
3492 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003493 ICmpInst::Predicate pred;
3494 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3495 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3496 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003497 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003498 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3499 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003500 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3501 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003502 return false;
3503 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003504 Instruction *apply(Instruction &Log) const {
3505 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3506 if (ICI->getOperand(0) != LHS) {
3507 assert(ICI->getOperand(1) == LHS);
3508 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003509 }
3510
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003511 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003512 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003513 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003514 unsigned Code;
3515 switch (Log.getOpcode()) {
3516 case Instruction::And: Code = LHSCode & RHSCode; break;
3517 case Instruction::Or: Code = LHSCode | RHSCode; break;
3518 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc25e7582009-07-11 20:10:48 +00003519 default: LLVM_UNREACHABLE("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003520 }
3521
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003522 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3523 ICmpInst::isSignedPredicate(ICI->getPredicate());
3524
Owen Andersond672ecb2009-07-03 00:17:18 +00003525 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003526 if (Instruction *I = dyn_cast<Instruction>(RV))
3527 return I;
3528 // Otherwise, it's a constant boolean value...
3529 return IC.ReplaceInstUsesWith(Log, RV);
3530 }
3531};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003532} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003533
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003534// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3535// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003536// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003537Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003538 ConstantInt *OpRHS,
3539 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003540 BinaryOperator &TheAnd) {
3541 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003542 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003543 if (!Op->isShift())
Owen Andersond672ecb2009-07-03 00:17:18 +00003544 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003545
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 switch (Op->getOpcode()) {
3547 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003548 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003549 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003550 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003551 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003552 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003553 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003554 }
3555 break;
3556 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003557 if (Together == AndRHS) // (X | C) & C --> C
3558 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003559
Chris Lattner6e7ba452005-01-01 16:22:27 +00003560 if (Op->hasOneUse() && Together != OpRHS) {
3561 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003562 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003563 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003564 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003565 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003566 }
3567 break;
3568 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003569 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003570 // Adding a one to a single bit bit-field should be turned into an XOR
3571 // of the bit. First thing to check is to see if this AND is with a
3572 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003573 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003574
3575 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003576 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003577 // Ok, at this point, we know that we are masking the result of the
3578 // ADD down to exactly one bit. If the constant we are adding has
3579 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003580 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003581
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003582 // Check to see if any bits below the one bit set in AndRHSV are set.
3583 if ((AddRHS & (AndRHSV-1)) == 0) {
3584 // If not, the only thing that can effect the output of the AND is
3585 // the bit specified by AndRHSV. If that bit is set, the effect of
3586 // the XOR is to toggle the bit. If it is clear, then the ADD has
3587 // no effect.
3588 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3589 TheAnd.setOperand(0, X);
3590 return &TheAnd;
3591 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003592 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003593 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003594 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003595 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003596 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003597 }
3598 }
3599 }
3600 }
3601 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003602
3603 case Instruction::Shl: {
3604 // We know that the AND will not produce any of the bits shifted in, so if
3605 // the anded constant includes them, clear them now!
3606 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003607 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003608 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003609 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003610 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003611
Zhou Sheng290bec52007-03-29 08:15:12 +00003612 if (CI->getValue() == ShlMask) {
3613 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003614 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3615 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003616 TheAnd.setOperand(1, CI);
3617 return &TheAnd;
3618 }
3619 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003620 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003621 case Instruction::LShr:
3622 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003623 // We know that the AND will not produce any of the bits shifted in, so if
3624 // the anded constant includes them, clear them now! This only applies to
3625 // unsigned shifts, because a signed shr may bring in set bits!
3626 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003627 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003628 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003629 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003630 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003631
Zhou Sheng290bec52007-03-29 08:15:12 +00003632 if (CI->getValue() == ShrMask) {
3633 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003634 return ReplaceInstUsesWith(TheAnd, Op);
3635 } else if (CI != AndRHS) {
3636 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3637 return &TheAnd;
3638 }
3639 break;
3640 }
3641 case Instruction::AShr:
3642 // Signed shr.
3643 // See if this is shifting in some sign extension, then masking it out
3644 // with an and.
3645 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003646 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003647 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003648 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003649 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003650 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003651 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003652 // Make the argument unsigned.
3653 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003654 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003655 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003656 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003657 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003658 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003659 }
3660 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003661 }
3662 return 0;
3663}
3664
Chris Lattner8b170942002-08-09 23:47:40 +00003665
Chris Lattnera96879a2004-09-29 17:40:11 +00003666/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3667/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003668/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3669/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003670/// insert new instructions.
3671Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003672 bool isSigned, bool Inside,
3673 Instruction &IB) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003674 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003675 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003676 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003677
Chris Lattnera96879a2004-09-29 17:40:11 +00003678 if (Inside) {
3679 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003680 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003681
Reid Spencere4d87aa2006-12-23 06:05:41 +00003682 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003683 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003684 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003685 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003686 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003687 }
3688
3689 // Emit V-Lo <u Hi-Lo
Owen Andersond672ecb2009-07-03 00:17:18 +00003690 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003691 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003692 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003693 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003694 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003695 }
3696
3697 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003698 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003699
Reid Spencere4e40032007-03-21 23:19:50 +00003700 // V < Min || V >= Hi -> V > Hi-1
Owen Andersond672ecb2009-07-03 00:17:18 +00003701 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003702 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003703 ICmpInst::Predicate pred = (isSigned ?
3704 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003705 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003706 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003707
Reid Spencere4e40032007-03-21 23:19:50 +00003708 // Emit V-Lo >u Hi-1-Lo
3709 // Note that Hi has already had one subtracted from it, above.
Owen Andersond672ecb2009-07-03 00:17:18 +00003710 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003711 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003712 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003713 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003714 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003715}
3716
Chris Lattner7203e152005-09-18 07:22:02 +00003717// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3718// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3719// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3720// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003721static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003722 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003723 uint32_t BitWidth = Val->getType()->getBitWidth();
3724 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003725
3726 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003727 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003728 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003729 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003730 return true;
3731}
3732
Chris Lattner7203e152005-09-18 07:22:02 +00003733/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3734/// where isSub determines whether the operator is a sub. If we can fold one of
3735/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003736///
3737/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3738/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3739/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3740///
3741/// return (A +/- B).
3742///
3743Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003744 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003745 Instruction &I) {
3746 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3747 if (!LHSI || LHSI->getNumOperands() != 2 ||
3748 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3749
3750 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3751
3752 switch (LHSI->getOpcode()) {
3753 default: return 0;
3754 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00003755 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003756 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003757 if ((Mask->getValue().countLeadingZeros() +
3758 Mask->getValue().countPopulation()) ==
3759 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003760 break;
3761
3762 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3763 // part, we don't need any explicit masks to take them out of A. If that
3764 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003765 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003766 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003767 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003768 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003769 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003770 break;
3771 }
3772 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003773 return 0;
3774 case Instruction::Or:
3775 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003776 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003777 if ((Mask->getValue().countLeadingZeros() +
3778 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersond672ecb2009-07-03 00:17:18 +00003779 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003780 break;
3781 return 0;
3782 }
3783
3784 Instruction *New;
3785 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003786 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003787 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003788 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003789 return InsertNewInstBefore(New, I);
3790}
3791
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003792/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3793Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3794 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003795 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003796 ConstantInt *LHSCst, *RHSCst;
3797 ICmpInst::Predicate LHSCC, RHSCC;
3798
Chris Lattnerea065fb2008-11-16 05:10:52 +00003799 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003800 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3801 m_ConstantInt(LHSCst)), *Context) ||
3802 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3803 m_ConstantInt(RHSCst)), *Context))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003804 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003805
3806 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3807 // where C is a power of 2
3808 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3809 LHSCst->getValue().isPowerOf2()) {
3810 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3811 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003812 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003813 }
3814
3815 // From here on, we only handle:
3816 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3817 if (Val != Val2) return 0;
3818
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003819 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3820 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3821 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3822 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3823 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3824 return 0;
3825
3826 // We can't fold (ugt x, C) & (sgt x, C2).
3827 if (!PredicatesFoldable(LHSCC, RHSCC))
3828 return 0;
3829
3830 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003831 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003832 if (ICmpInst::isSignedPredicate(LHSCC) ||
3833 (ICmpInst::isEquality(LHSCC) &&
3834 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003835 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003836 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003837 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3838
3839 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003840 std::swap(LHS, RHS);
3841 std::swap(LHSCst, RHSCst);
3842 std::swap(LHSCC, RHSCC);
3843 }
3844
3845 // At this point, we know we have have two icmp instructions
3846 // comparing a value against two constants and and'ing the result
3847 // together. Because of the above check, we know that we only have
3848 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3849 // (from the FoldICmpLogical check above), that the two constants
3850 // are not equal and that the larger constant is on the RHS
3851 assert(LHSCst != RHSCst && "Compares not folded above?");
3852
3853 switch (LHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003854 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003855 case ICmpInst::ICMP_EQ:
3856 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003857 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003858 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3859 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3860 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003861 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003862 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3863 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3864 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3865 return ReplaceInstUsesWith(I, LHS);
3866 }
3867 case ICmpInst::ICMP_NE:
3868 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003869 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003870 case ICmpInst::ICMP_ULT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003871 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003872 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003873 break; // (X != 13 & X u< 15) -> no change
3874 case ICmpInst::ICMP_SLT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003875 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003876 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003877 break; // (X != 13 & X s< 15) -> no change
3878 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3879 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3880 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3881 return ReplaceInstUsesWith(I, RHS);
3882 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003883 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3884 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003885 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3886 Val->getName()+".off");
3887 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003888 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersond672ecb2009-07-03 00:17:18 +00003889 Context->getConstantInt(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003890 }
3891 break; // (X != 13 & X != 15) -> no change
3892 }
3893 break;
3894 case ICmpInst::ICMP_ULT:
3895 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003896 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003897 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3898 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003899 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003900 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3901 break;
3902 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3903 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3904 return ReplaceInstUsesWith(I, LHS);
3905 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3906 break;
3907 }
3908 break;
3909 case ICmpInst::ICMP_SLT:
3910 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003911 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003912 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3913 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003914 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003915 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3916 break;
3917 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3918 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3919 return ReplaceInstUsesWith(I, LHS);
3920 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3921 break;
3922 }
3923 break;
3924 case ICmpInst::ICMP_UGT:
3925 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003926 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003927 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3928 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3929 return ReplaceInstUsesWith(I, RHS);
3930 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3931 break;
3932 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003933 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003934 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003935 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003936 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003937 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3938 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003939 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3940 break;
3941 }
3942 break;
3943 case ICmpInst::ICMP_SGT:
3944 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003945 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003946 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3947 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3948 return ReplaceInstUsesWith(I, RHS);
3949 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3950 break;
3951 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003952 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003953 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003954 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003955 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003956 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3957 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003958 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3959 break;
3960 }
3961 break;
3962 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003963
3964 return 0;
3965}
3966
3967
Chris Lattner7e708292002-06-25 16:13:24 +00003968Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003969 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003970 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003971
Chris Lattnere87597f2004-10-16 18:11:37 +00003972 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003973 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003974
Chris Lattner6e7ba452005-01-01 16:22:27 +00003975 // and X, X = X
3976 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003977 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003978
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003979 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003980 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003981 if (SimplifyDemandedInstructionBits(I))
3982 return &I;
3983 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003984 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003985 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003986 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003987 } else if (isa<ConstantAggregateZero>(Op1)) {
3988 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003989 }
3990 }
Dan Gohman6de29f82009-06-15 22:12:54 +00003991
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003992 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003993 const APInt& AndRHSMask = AndRHS->getValue();
3994 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003995
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003996 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003997 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003998 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003999 Value *Op0LHS = Op0I->getOperand(0);
4000 Value *Op0RHS = Op0I->getOperand(1);
4001 switch (Op0I->getOpcode()) {
4002 case Instruction::Xor:
4003 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004004 // If the mask is only needed on one incoming arm, push it up.
4005 if (Op0I->hasOneUse()) {
4006 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4007 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004008 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004009 Op0RHS->getName()+".masked");
4010 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004011 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004012 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004013 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004014 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004015 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4016 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004017 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004018 Op0LHS->getName()+".masked");
4019 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004020 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004021 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4022 }
4023 }
4024
Chris Lattner6e7ba452005-01-01 16:22:27 +00004025 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004026 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004027 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4028 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4029 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4030 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004031 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004032 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004033 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004034 break;
4035
4036 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004037 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4038 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4039 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4040 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004041 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004042
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004043 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4044 // has 1's for all bits that the subtraction with A might affect.
4045 if (Op0I->hasOneUse()) {
4046 uint32_t BitWidth = AndRHSMask.getBitWidth();
4047 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4048 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4049
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004050 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004051 if (!(A && A->isZero()) && // avoid infinite recursion.
4052 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00004053 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004054 InsertNewInstBefore(NewNeg, I);
4055 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4056 }
4057 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004058 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004059
4060 case Instruction::Shl:
4061 case Instruction::LShr:
4062 // (1 << x) & 1 --> zext(x == 0)
4063 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004064 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004065 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4066 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004067 InsertNewInstBefore(NewICmp, I);
4068 return new ZExtInst(NewICmp, I.getType());
4069 }
4070 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004071 }
4072
Chris Lattner58403262003-07-23 19:25:52 +00004073 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004074 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004075 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004076 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004077 // If this is an integer truncation or change from signed-to-unsigned, and
4078 // if the source is an and/or with immediate, transform it. This
4079 // frequently occurs for bitfield accesses.
4080 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004081 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004082 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004083 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004084 if (CastOp->getOpcode() == Instruction::And) {
4085 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004086 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4087 // This will fold the two constants together, which may allow
4088 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004089 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004090 CastOp->getOperand(0), I.getType(),
4091 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004092 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004093 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004094 Constant *C3 =
4095 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4096 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004097 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004098 } else if (CastOp->getOpcode() == Instruction::Or) {
4099 // Change: and (cast (or X, C1) to T), C2
4100 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004101 Constant *C3 =
4102 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4103 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4104 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004105 return ReplaceInstUsesWith(I, AndRHS);
4106 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004107 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004108 }
Chris Lattner06782f82003-07-23 19:36:21 +00004109 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004110
4111 // Try to fold constant and into select arguments.
4112 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004113 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004114 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004115 if (isa<PHINode>(Op0))
4116 if (Instruction *NV = FoldOpIntoPhi(I))
4117 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004118 }
4119
Owen Andersond672ecb2009-07-03 00:17:18 +00004120 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4121 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattnera2881962003-02-18 19:28:33 +00004122
Chris Lattner5b62aa72004-06-18 06:07:51 +00004123 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004124 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004125
Misha Brukmancb6267b2004-07-30 12:50:08 +00004126 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004127 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004128 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004129 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004130 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004131 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004132 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004133
4134 {
Chris Lattner003b6202007-06-15 05:58:24 +00004135 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004136 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004137 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4138 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004139
4140 // (A|B) & ~(A&B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004141 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004142 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004143 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004144 }
4145 }
4146
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004147 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004148 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4149 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004150
4151 // ~(A&B) & (A|B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004152 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004153 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004154 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004155 }
4156 }
Chris Lattner64daab52006-04-01 08:03:55 +00004157
4158 if (Op0->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004159 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004160 if (A == Op1) { // (A^B)&A -> A&(A^B)
4161 I.swapOperands(); // Simplify below
4162 std::swap(Op0, Op1);
4163 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4164 cast<BinaryOperator>(Op0)->swapOperands();
4165 I.swapOperands(); // Simplify below
4166 std::swap(Op0, Op1);
4167 }
4168 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004169
Chris Lattner64daab52006-04-01 08:03:55 +00004170 if (Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004171 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004172 if (B == Op0) { // B&(A^B) -> B&(B^A)
4173 cast<BinaryOperator>(Op1)->swapOperands();
4174 std::swap(A, B);
4175 }
4176 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004177 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004178 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004179 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004180 }
4181 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004182
4183 // (A&((~A)|B)) -> A&B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004184 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4185 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004186 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004187 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4188 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004189 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004190 }
4191
Reid Spencere4d87aa2006-12-23 06:05:41 +00004192 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4193 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004194 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004195 return R;
4196
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004197 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4198 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4199 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004200 }
4201
Chris Lattner6fc205f2006-05-05 06:39:07 +00004202 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004203 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4204 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4205 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4206 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004207 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004208 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004209 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4210 I.getType(), TD) &&
4211 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4212 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004213 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004214 Op1C->getOperand(0),
4215 I.getName());
4216 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004217 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004218 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004219 }
Chris Lattnere511b742006-11-14 07:46:50 +00004220
4221 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004222 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4223 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4224 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004225 SI0->getOperand(1) == SI1->getOperand(1) &&
4226 (SI0->hasOneUse() || SI1->hasOneUse())) {
4227 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004228 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004229 SI1->getOperand(0),
4230 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004231 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004232 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004233 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004234 }
4235
Evan Cheng8db90722008-10-14 17:15:11 +00004236 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004237 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4238 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4239 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004240 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4241 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004242 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4243 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4244 // If either of the constants are nans, then the whole thing returns
4245 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004246 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersond672ecb2009-07-03 00:17:18 +00004247 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00004248 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4249 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004250 }
Evan Cheng8db90722008-10-14 17:15:11 +00004251 } else {
4252 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4253 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004254 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4255 m_Value(Op0RHS)), *Context) &&
4256 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4257 m_Value(Op1RHS)), *Context)) {
Evan Cheng4990b252008-10-14 18:13:38 +00004258 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4259 // Swap RHS operands to match LHS.
4260 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4261 std::swap(Op1LHS, Op1RHS);
4262 }
Evan Cheng8db90722008-10-14 17:15:11 +00004263 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4264 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4265 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004266 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4267 Op0LHS, Op0RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00004268 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4269 Op1CC == FCmpInst::FCMP_FALSE)
Owen Andersond672ecb2009-07-03 00:17:18 +00004270 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004271 else if (Op0CC == FCmpInst::FCMP_TRUE)
4272 return ReplaceInstUsesWith(I, Op1);
4273 else if (Op1CC == FCmpInst::FCMP_TRUE)
4274 return ReplaceInstUsesWith(I, Op0);
4275 bool Op0Ordered;
4276 bool Op1Ordered;
4277 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4278 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4279 if (Op1Pred == 0) {
4280 std::swap(Op0, Op1);
4281 std::swap(Op0Pred, Op1Pred);
4282 std::swap(Op0Ordered, Op1Ordered);
4283 }
4284 if (Op0Pred == 0) {
4285 // uno && ueq -> uno && (uno || eq) -> ueq
4286 // ord && olt -> ord && (ord && lt) -> olt
4287 if (Op0Ordered == Op1Ordered)
4288 return ReplaceInstUsesWith(I, Op1);
4289 // uno && oeq -> uno && (ord && eq) -> false
4290 // uno && ord -> false
4291 if (!Op0Ordered)
Owen Andersond672ecb2009-07-03 00:17:18 +00004292 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004293 // ord && ueq -> ord && (uno || eq) -> oeq
4294 return cast<Instruction>(getFCmpValue(true, Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004295 Op0LHS, Op0RHS, Context));
Evan Cheng8db90722008-10-14 17:15:11 +00004296 }
4297 }
4298 }
4299 }
Chris Lattner99c65742007-10-24 05:38:08 +00004300 }
4301 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004302
Chris Lattner7e708292002-06-25 16:13:24 +00004303 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004304}
4305
Chris Lattner8c34cd22008-10-05 02:13:19 +00004306/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4307/// capable of providing pieces of a bswap. The subexpression provides pieces
4308/// of a bswap if it is proven that each of the non-zero bytes in the output of
4309/// the expression came from the corresponding "byte swapped" byte in some other
4310/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4311/// we know that the expression deposits the low byte of %X into the high byte
4312/// of the bswap result and that all other bytes are zero. This expression is
4313/// accepted, the high byte of ByteValues is set to X to indicate a correct
4314/// match.
4315///
4316/// This function returns true if the match was unsuccessful and false if so.
4317/// On entry to the function the "OverallLeftShift" is a signed integer value
4318/// indicating the number of bytes that the subexpression is later shifted. For
4319/// example, if the expression is later right shifted by 16 bits, the
4320/// OverallLeftShift value would be -2 on entry. This is used to specify which
4321/// byte of ByteValues is actually being set.
4322///
4323/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4324/// byte is masked to zero by a user. For example, in (X & 255), X will be
4325/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4326/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4327/// always in the local (OverallLeftShift) coordinate space.
4328///
4329static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4330 SmallVector<Value*, 8> &ByteValues) {
4331 if (Instruction *I = dyn_cast<Instruction>(V)) {
4332 // If this is an or instruction, it may be an inner node of the bswap.
4333 if (I->getOpcode() == Instruction::Or) {
4334 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4335 ByteValues) ||
4336 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4337 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004338 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004339
4340 // If this is a logical shift by a constant multiple of 8, recurse with
4341 // OverallLeftShift and ByteMask adjusted.
4342 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4343 unsigned ShAmt =
4344 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4345 // Ensure the shift amount is defined and of a byte value.
4346 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4347 return true;
4348
4349 unsigned ByteShift = ShAmt >> 3;
4350 if (I->getOpcode() == Instruction::Shl) {
4351 // X << 2 -> collect(X, +2)
4352 OverallLeftShift += ByteShift;
4353 ByteMask >>= ByteShift;
4354 } else {
4355 // X >>u 2 -> collect(X, -2)
4356 OverallLeftShift -= ByteShift;
4357 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004358 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004359 }
4360
4361 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4362 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4363
4364 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4365 ByteValues);
4366 }
4367
4368 // If this is a logical 'and' with a mask that clears bytes, clear the
4369 // corresponding bytes in ByteMask.
4370 if (I->getOpcode() == Instruction::And &&
4371 isa<ConstantInt>(I->getOperand(1))) {
4372 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4373 unsigned NumBytes = ByteValues.size();
4374 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4375 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4376
4377 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4378 // If this byte is masked out by a later operation, we don't care what
4379 // the and mask is.
4380 if ((ByteMask & (1 << i)) == 0)
4381 continue;
4382
4383 // If the AndMask is all zeros for this byte, clear the bit.
4384 APInt MaskB = AndMask & Byte;
4385 if (MaskB == 0) {
4386 ByteMask &= ~(1U << i);
4387 continue;
4388 }
4389
4390 // If the AndMask is not all ones for this byte, it's not a bytezap.
4391 if (MaskB != Byte)
4392 return true;
4393
4394 // Otherwise, this byte is kept.
4395 }
4396
4397 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4398 ByteValues);
4399 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004400 }
4401
Chris Lattner8c34cd22008-10-05 02:13:19 +00004402 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4403 // the input value to the bswap. Some observations: 1) if more than one byte
4404 // is demanded from this input, then it could not be successfully assembled
4405 // into a byteswap. At least one of the two bytes would not be aligned with
4406 // their ultimate destination.
4407 if (!isPowerOf2_32(ByteMask)) return true;
4408 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004409
Chris Lattner8c34cd22008-10-05 02:13:19 +00004410 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4411 // is demanded, it needs to go into byte 0 of the result. This means that the
4412 // byte needs to be shifted until it lands in the right byte bucket. The
4413 // shift amount depends on the position: if the byte is coming from the high
4414 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4415 // low part, it must be shifted left.
4416 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4417 if (InputByteNo < ByteValues.size()/2) {
4418 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4419 return true;
4420 } else {
4421 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4422 return true;
4423 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004424
4425 // If the destination byte value is already defined, the values are or'd
4426 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004427 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004428 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004429 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004430 return false;
4431}
4432
4433/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4434/// If so, insert the new bswap intrinsic and return it.
4435Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004436 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004437 if (!ITy || ITy->getBitWidth() % 16 ||
4438 // ByteMask only allows up to 32-byte values.
4439 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004440 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004441
4442 /// ByteValues - For each byte of the result, we keep track of which value
4443 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004444 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004445 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004446
4447 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004448 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4449 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004450 return 0;
4451
4452 // Check to see if all of the bytes come from the same value.
4453 Value *V = ByteValues[0];
4454 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4455
4456 // Check to make sure that all of the bytes come from the same value.
4457 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4458 if (ByteValues[i] != V)
4459 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004460 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004461 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004462 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004463 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004464}
4465
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004466/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4467/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4468/// we can simplify this expression to "cond ? C : D or B".
4469static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004470 Value *C, Value *D,
4471 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004472 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004473 Value *Cond = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004474 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004475 return 0;
4476
Chris Lattnera6a474d2008-11-16 04:26:55 +00004477 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004478 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004479 return SelectInst::Create(Cond, C, B);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004480 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004481 return SelectInst::Create(Cond, C, B);
4482 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004483 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004484 return SelectInst::Create(Cond, C, D);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004485 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004486 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004487 return 0;
4488}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004489
Chris Lattner69d4ced2008-11-16 05:20:07 +00004490/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4491Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4492 ICmpInst *LHS, ICmpInst *RHS) {
4493 Value *Val, *Val2;
4494 ConstantInt *LHSCst, *RHSCst;
4495 ICmpInst::Predicate LHSCC, RHSCC;
4496
4497 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004498 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4499 m_ConstantInt(LHSCst)), *Context) ||
4500 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4501 m_ConstantInt(RHSCst)), *Context))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004502 return 0;
4503
4504 // From here on, we only handle:
4505 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4506 if (Val != Val2) return 0;
4507
4508 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4509 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4510 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4511 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4512 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4513 return 0;
4514
4515 // We can't fold (ugt x, C) | (sgt x, C2).
4516 if (!PredicatesFoldable(LHSCC, RHSCC))
4517 return 0;
4518
4519 // Ensure that the larger constant is on the RHS.
4520 bool ShouldSwap;
4521 if (ICmpInst::isSignedPredicate(LHSCC) ||
4522 (ICmpInst::isEquality(LHSCC) &&
4523 ICmpInst::isSignedPredicate(RHSCC)))
4524 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4525 else
4526 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4527
4528 if (ShouldSwap) {
4529 std::swap(LHS, RHS);
4530 std::swap(LHSCst, RHSCst);
4531 std::swap(LHSCC, RHSCC);
4532 }
4533
4534 // At this point, we know we have have two icmp instructions
4535 // comparing a value against two constants and or'ing the result
4536 // together. Because of the above check, we know that we only have
4537 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4538 // FoldICmpLogical check above), that the two constants are not
4539 // equal.
4540 assert(LHSCst != RHSCst && "Compares not folded above?");
4541
4542 switch (LHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00004543 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004544 case ICmpInst::ICMP_EQ:
4545 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00004546 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004547 case ICmpInst::ICMP_EQ:
Owen Andersond672ecb2009-07-03 00:17:18 +00004548 if (LHSCst == SubOne(RHSCst, Context)) {
4549 // (X == 13 | X == 14) -> X-13 <u 2
4550 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004551 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4552 Val->getName()+".off");
4553 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00004554 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004555 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004556 }
4557 break; // (X == 13 | X == 15) -> no change
4558 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4559 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4560 break;
4561 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4562 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4563 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4564 return ReplaceInstUsesWith(I, RHS);
4565 }
4566 break;
4567 case ICmpInst::ICMP_NE:
4568 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00004569 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004570 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4571 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4572 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4573 return ReplaceInstUsesWith(I, LHS);
4574 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4575 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4576 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004577 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004578 }
4579 break;
4580 case ICmpInst::ICMP_ULT:
4581 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00004582 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004583 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4584 break;
4585 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4586 // If RHSCst is [us]MAXINT, it is always false. Not handling
4587 // this can cause overflow.
4588 if (RHSCst->isMaxValue(false))
4589 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004590 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4591 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004592 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4593 break;
4594 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4595 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4596 return ReplaceInstUsesWith(I, RHS);
4597 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4598 break;
4599 }
4600 break;
4601 case ICmpInst::ICMP_SLT:
4602 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00004603 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004604 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4605 break;
4606 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4607 // If RHSCst is [us]MAXINT, it is always false. Not handling
4608 // this can cause overflow.
4609 if (RHSCst->isMaxValue(true))
4610 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004611 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4612 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004613 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4614 break;
4615 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4616 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4617 return ReplaceInstUsesWith(I, RHS);
4618 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4619 break;
4620 }
4621 break;
4622 case ICmpInst::ICMP_UGT:
4623 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00004624 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004625 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4626 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4627 return ReplaceInstUsesWith(I, LHS);
4628 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4629 break;
4630 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4631 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004632 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004633 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4634 break;
4635 }
4636 break;
4637 case ICmpInst::ICMP_SGT:
4638 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00004639 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004640 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4641 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4642 return ReplaceInstUsesWith(I, LHS);
4643 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4644 break;
4645 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4646 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004647 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004648 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4649 break;
4650 }
4651 break;
4652 }
4653 return 0;
4654}
4655
Bill Wendlinga698a472008-12-01 08:23:25 +00004656/// FoldOrWithConstants - This helper function folds:
4657///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004658/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004659///
4660/// into:
4661///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004662/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004663///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004664/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004665Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004666 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004667 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4668 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004669
Bill Wendling286a0542008-12-02 06:24:20 +00004670 Value *V1 = 0;
4671 ConstantInt *CI2 = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004672 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004673
Bill Wendling29976b92008-12-02 06:18:11 +00004674 APInt Xor = CI1->getValue() ^ CI2->getValue();
4675 if (!Xor.isAllOnesValue()) return 0;
4676
Bill Wendling286a0542008-12-02 06:24:20 +00004677 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004678 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004679 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4680 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004681 }
4682
4683 return 0;
4684}
4685
Chris Lattner7e708292002-06-25 16:13:24 +00004686Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004687 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004688 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004689
Chris Lattner42593e62007-03-24 23:56:43 +00004690 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004691 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004692
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004693 // or X, X = X
4694 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004695 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004696
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004697 // See if we can simplify any instructions used by the instruction whose sole
4698 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004699 if (SimplifyDemandedInstructionBits(I))
4700 return &I;
4701 if (isa<VectorType>(I.getType())) {
4702 if (isa<ConstantAggregateZero>(Op1)) {
4703 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4704 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4705 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4706 return ReplaceInstUsesWith(I, I.getOperand(1));
4707 }
Chris Lattner42593e62007-03-24 23:56:43 +00004708 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004709
Chris Lattner3f5b8772002-05-06 16:14:14 +00004710 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004711 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004712 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004713 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004714 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4715 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004716 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004717 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004718 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004719 return BinaryOperator::CreateAnd(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004720 Context->getConstantInt(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004721 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004722
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004723 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004724 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4725 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004726 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004727 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004728 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004729 return BinaryOperator::CreateXor(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004730 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004731 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004732
4733 // Try to fold constant and into select arguments.
4734 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004735 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004736 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004737 if (isa<PHINode>(Op0))
4738 if (Instruction *NV = FoldOpIntoPhi(I))
4739 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004740 }
4741
Chris Lattner4f637d42006-01-06 17:59:59 +00004742 Value *A = 0, *B = 0;
4743 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004744
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004745 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004746 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4747 return ReplaceInstUsesWith(I, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004748 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004749 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4750 return ReplaceInstUsesWith(I, Op0);
4751
Chris Lattner6423d4c2006-07-10 20:25:24 +00004752 // (A | B) | C and A | (B | C) -> bswap if possible.
4753 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004754 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4755 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4756 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4757 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004758 if (Instruction *BSwap = MatchBSwap(I))
4759 return BSwap;
4760 }
4761
Chris Lattner6e4c6492005-05-09 04:58:36 +00004762 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004763 if (Op0->hasOneUse() &&
4764 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004765 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004766 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004767 InsertNewInstBefore(NOr, I);
4768 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004769 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004770 }
4771
4772 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004773 if (Op1->hasOneUse() &&
4774 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004775 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004776 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004777 InsertNewInstBefore(NOr, I);
4778 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004779 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004780 }
4781
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004782 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004783 Value *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004784 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4785 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004786 Value *V1 = 0, *V2 = 0, *V3 = 0;
4787 C1 = dyn_cast<ConstantInt>(C);
4788 C2 = dyn_cast<ConstantInt>(D);
4789 if (C1 && C2) { // (A & C1)|(B & C2)
4790 // If we have: ((V + N) & C1) | (V & C2)
4791 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4792 // replace with V+N.
4793 if (C1->getValue() == ~C2->getValue()) {
4794 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004795 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004796 // Add commutes, try both ways.
4797 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4798 return ReplaceInstUsesWith(I, A);
4799 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4800 return ReplaceInstUsesWith(I, A);
4801 }
4802 // Or commutes, try both ways.
4803 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004804 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004805 // Add commutes, try both ways.
4806 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4807 return ReplaceInstUsesWith(I, B);
4808 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4809 return ReplaceInstUsesWith(I, B);
4810 }
4811 }
Chris Lattner044e5332007-04-08 08:01:49 +00004812 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004813 }
4814
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004815 // Check to see if we have any common things being and'ed. If so, find the
4816 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004817 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4818 if (A == B) // (A & C)|(A & D) == A & (C|D)
4819 V1 = A, V2 = C, V3 = D;
4820 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4821 V1 = A, V2 = B, V3 = C;
4822 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4823 V1 = C, V2 = A, V3 = D;
4824 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4825 V1 = C, V2 = A, V3 = B;
4826
4827 if (V1) {
4828 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004829 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4830 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004831 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004832 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004833
Dan Gohman1975d032008-10-30 20:40:10 +00004834 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004835 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004836 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004837 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004838 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004839 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004840 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004841 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004842 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004843
Bill Wendlingb01865c2008-11-30 13:52:49 +00004844 // ((A&~B)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004845 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4846 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004847 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004848 // ((~B&A)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004849 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4850 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004851 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004852 // ((A&~B)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004853 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4854 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004855 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004856 // ((~B&A)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004857 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4858 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004859 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004860 }
Chris Lattnere511b742006-11-14 07:46:50 +00004861
4862 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004863 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4864 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4865 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004866 SI0->getOperand(1) == SI1->getOperand(1) &&
4867 (SI0->hasOneUse() || SI1->hasOneUse())) {
4868 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004869 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004870 SI1->getOperand(0),
4871 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004872 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004873 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004874 }
4875 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004876
Bill Wendlingb3833d12008-12-01 01:07:11 +00004877 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004878 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4879 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004880 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004881 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004882 }
4883 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004884 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4885 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004886 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004887 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004888 }
4889
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004890 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004891 if (A == Op1) // ~A | A == -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004892 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004893 } else {
4894 A = 0;
4895 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004896 // Note, A is still live here!
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004897 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004898 if (Op0 == B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004899 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004900
Misha Brukmancb6267b2004-07-30 12:50:08 +00004901 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004902 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004903 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004904 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004905 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004906 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004907 }
Chris Lattnera2881962003-02-18 19:28:33 +00004908
Reid Spencere4d87aa2006-12-23 06:05:41 +00004909 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4910 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004911 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004912 return R;
4913
Chris Lattner69d4ced2008-11-16 05:20:07 +00004914 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4915 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4916 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004917 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004918
4919 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004920 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004921 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004922 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004923 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4924 !isa<ICmpInst>(Op1C->getOperand(0))) {
4925 const Type *SrcTy = Op0C->getOperand(0)->getType();
4926 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4927 // Only do this if the casts both really cause code to be
4928 // generated.
4929 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4930 I.getType(), TD) &&
4931 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4932 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004933 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004934 Op1C->getOperand(0),
4935 I.getName());
4936 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004937 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004938 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004939 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004940 }
Chris Lattner99c65742007-10-24 05:38:08 +00004941 }
4942
4943
4944 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4945 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4946 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4947 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004948 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004949 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004950 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4951 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4952 // If either of the constants are nans, then the whole thing returns
4953 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004954 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersond672ecb2009-07-03 00:17:18 +00004955 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner99c65742007-10-24 05:38:08 +00004956
4957 // Otherwise, no need to compare the two constants, compare the
4958 // rest.
Owen Anderson333c4002009-07-09 23:48:35 +00004959 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4960 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004961 }
Evan Cheng40300622008-10-14 18:44:08 +00004962 } else {
4963 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4964 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004965 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4966 m_Value(Op0RHS)), *Context) &&
4967 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4968 m_Value(Op1RHS)), *Context)) {
Evan Cheng40300622008-10-14 18:44:08 +00004969 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4970 // Swap RHS operands to match LHS.
4971 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4972 std::swap(Op1LHS, Op1RHS);
4973 }
4974 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4975 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4976 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004977 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4978 Op0LHS, Op0RHS);
Evan Cheng40300622008-10-14 18:44:08 +00004979 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4980 Op1CC == FCmpInst::FCMP_TRUE)
Owen Andersond672ecb2009-07-03 00:17:18 +00004981 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng40300622008-10-14 18:44:08 +00004982 else if (Op0CC == FCmpInst::FCMP_FALSE)
4983 return ReplaceInstUsesWith(I, Op1);
4984 else if (Op1CC == FCmpInst::FCMP_FALSE)
4985 return ReplaceInstUsesWith(I, Op0);
4986 bool Op0Ordered;
4987 bool Op1Ordered;
4988 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4989 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4990 if (Op0Ordered == Op1Ordered) {
4991 // If both are ordered or unordered, return a new fcmp with
4992 // or'ed predicates.
4993 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004994 Op0LHS, Op0RHS, Context);
Evan Cheng40300622008-10-14 18:44:08 +00004995 if (Instruction *I = dyn_cast<Instruction>(RV))
4996 return I;
4997 // Otherwise, it's a constant boolean value...
4998 return ReplaceInstUsesWith(I, RV);
4999 }
5000 }
5001 }
5002 }
Chris Lattner99c65742007-10-24 05:38:08 +00005003 }
5004 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005005
Chris Lattner7e708292002-06-25 16:13:24 +00005006 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005007}
5008
Dan Gohman844731a2008-05-13 00:00:25 +00005009namespace {
5010
Chris Lattnerc317d392004-02-16 01:20:27 +00005011// XorSelf - Implements: X ^ X --> 0
5012struct XorSelf {
5013 Value *RHS;
5014 XorSelf(Value *rhs) : RHS(rhs) {}
5015 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5016 Instruction *apply(BinaryOperator &Xor) const {
5017 return &Xor;
5018 }
5019};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005020
Dan Gohman844731a2008-05-13 00:00:25 +00005021}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005022
Chris Lattner7e708292002-06-25 16:13:24 +00005023Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005024 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005025 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005026
Evan Chengd34af782008-03-25 20:07:13 +00005027 if (isa<UndefValue>(Op1)) {
5028 if (isa<UndefValue>(Op0))
5029 // Handle undef ^ undef -> 0 special case. This is a common
5030 // idiom (misuse).
Owen Andersond672ecb2009-07-03 00:17:18 +00005031 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005032 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005033 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005034
Chris Lattnerc317d392004-02-16 01:20:27 +00005035 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersond672ecb2009-07-03 00:17:18 +00005036 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005037 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersond672ecb2009-07-03 00:17:18 +00005038 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005039 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005040
5041 // See if we can simplify any instructions used by the instruction whose sole
5042 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005043 if (SimplifyDemandedInstructionBits(I))
5044 return &I;
5045 if (isa<VectorType>(I.getType()))
5046 if (isa<ConstantAggregateZero>(Op1))
5047 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005048
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005049 // Is this a ~ operation?
Owen Andersond672ecb2009-07-03 00:17:18 +00005050 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005051 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5052 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5053 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5054 if (Op0I->getOpcode() == Instruction::And ||
5055 Op0I->getOpcode() == Instruction::Or) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005056 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5057 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005058 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005059 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005060 Op0I->getOperand(1)->getName()+".not");
5061 InsertNewInstBefore(NotY, I);
5062 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005063 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005064 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005065 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005066 }
5067 }
5068 }
5069 }
5070
5071
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005072 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005073 if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005074 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005075 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005076 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005077 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005078
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005079 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005080 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005081 FCI->getOperand(0), FCI->getOperand(1));
5082 }
5083
Nick Lewycky517e1f52008-05-31 19:01:33 +00005084 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5085 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5086 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5087 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5088 Instruction::CastOps Opcode = Op0C->getOpcode();
5089 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005090 if (RHS == Context->getConstantExprCast(Opcode,
5091 Context->getConstantIntTrue(),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005092 Op0C->getDestTy())) {
5093 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005094 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005095 CI->getOpcode(), CI->getInversePredicate(),
5096 CI->getOperand(0), CI->getOperand(1)), I);
5097 NewCI->takeName(CI);
5098 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5099 }
5100 }
5101 }
5102 }
5103 }
5104
Reid Spencere4d87aa2006-12-23 06:05:41 +00005105 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005106 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005107 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5108 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005109 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5110 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5111 Context->getConstantInt(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005112 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005113 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005114
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005115 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005116 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005117 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005118 if (RHS->isAllOnesValue()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005119 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005120 return BinaryOperator::CreateSub(
Owen Andersond672ecb2009-07-03 00:17:18 +00005121 Context->getConstantExprSub(NegOp0CI,
5122 Context->getConstantInt(I.getType(), 1)),
5123 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005124 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005125 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersond672ecb2009-07-03 00:17:18 +00005126 Constant *C =
5127 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005128 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005129
Chris Lattner7c4049c2004-01-12 19:35:11 +00005130 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005131 } else if (Op0I->getOpcode() == Instruction::Or) {
5132 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005133 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005134 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005135 // Anything in both C1 and C2 is known to be zero, remove it from
5136 // NewRHS.
Owen Andersond672ecb2009-07-03 00:17:18 +00005137 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5138 NewRHS = Context->getConstantExprAnd(NewRHS,
5139 Context->getConstantExprNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005140 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005141 I.setOperand(0, Op0I->getOperand(0));
5142 I.setOperand(1, NewRHS);
5143 return &I;
5144 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005145 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005146 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005147 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005148
5149 // Try to fold constant and into select arguments.
5150 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005151 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005152 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005153 if (isa<PHINode>(Op0))
5154 if (Instruction *NV = FoldOpIntoPhi(I))
5155 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005156 }
5157
Owen Andersond672ecb2009-07-03 00:17:18 +00005158 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005159 if (X == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005160 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005161
Owen Andersond672ecb2009-07-03 00:17:18 +00005162 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005163 if (X == Op0)
Owen Andersond672ecb2009-07-03 00:17:18 +00005164 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005165
Chris Lattner318bf792007-03-18 22:51:34 +00005166
5167 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5168 if (Op1I) {
5169 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005170 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005171 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005172 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005173 I.swapOperands();
5174 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005175 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005176 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005177 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005178 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005179 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005180 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005181 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005182 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005183 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5184 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005185 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005186 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005187 std::swap(A, B);
5188 }
Chris Lattner318bf792007-03-18 22:51:34 +00005189 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005190 I.swapOperands(); // Simplified below.
5191 std::swap(Op0, Op1);
5192 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005193 }
Chris Lattner318bf792007-03-18 22:51:34 +00005194 }
5195
5196 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5197 if (Op0I) {
5198 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005199 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5200 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005201 if (A == Op1) // (B|A)^B == (A|B)^B
5202 std::swap(A, B);
5203 if (B == Op1) { // (A|B)^B == A & ~B
5204 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005205 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5206 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005207 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005208 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005209 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005210 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005211 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005212 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5213 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005214 if (A == Op1) // (A&B)^A -> (B&A)^A
5215 std::swap(A, B);
5216 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005217 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005218 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005219 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5220 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005221 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005222 }
Chris Lattner318bf792007-03-18 22:51:34 +00005223 }
5224
5225 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5226 if (Op0I && Op1I && Op0I->isShift() &&
5227 Op0I->getOpcode() == Op1I->getOpcode() &&
5228 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5229 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5230 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005231 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005232 Op1I->getOperand(0),
5233 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005234 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005235 Op1I->getOperand(1));
5236 }
5237
5238 if (Op0I && Op1I) {
5239 Value *A, *B, *C, *D;
5240 // (A & B)^(A | B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005241 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5242 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005243 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005244 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005245 }
5246 // (A | B)^(A & B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005247 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5248 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005249 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005250 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005251 }
5252
5253 // (A & B)^(C & D)
5254 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005255 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5256 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005257 // (X & Y)^(X & Y) -> (Y^Z) & X
5258 Value *X = 0, *Y = 0, *Z = 0;
5259 if (A == C)
5260 X = A, Y = B, Z = D;
5261 else if (A == D)
5262 X = A, Y = B, Z = C;
5263 else if (B == C)
5264 X = B, Y = A, Z = D;
5265 else if (B == D)
5266 X = B, Y = A, Z = C;
5267
5268 if (X) {
5269 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005270 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5271 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005272 }
5273 }
5274 }
5275
Reid Spencere4d87aa2006-12-23 06:05:41 +00005276 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5277 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005278 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005279 return R;
5280
Chris Lattner6fc205f2006-05-05 06:39:07 +00005281 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005282 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005283 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005284 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5285 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005286 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005287 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005288 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5289 I.getType(), TD) &&
5290 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5291 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005292 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005293 Op1C->getOperand(0),
5294 I.getName());
5295 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005296 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005297 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005298 }
Chris Lattner99c65742007-10-24 05:38:08 +00005299 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005300
Chris Lattner7e708292002-06-25 16:13:24 +00005301 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005302}
5303
Owen Andersond672ecb2009-07-03 00:17:18 +00005304static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005305 LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005306 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005307}
Chris Lattnera96879a2004-09-29 17:40:11 +00005308
Dan Gohman6de29f82009-06-15 22:12:54 +00005309static bool HasAddOverflow(ConstantInt *Result,
5310 ConstantInt *In1, ConstantInt *In2,
5311 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005312 if (IsSigned)
5313 if (In2->getValue().isNegative())
5314 return Result->getValue().sgt(In1->getValue());
5315 else
5316 return Result->getValue().slt(In1->getValue());
5317 else
5318 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005319}
5320
Dan Gohman6de29f82009-06-15 22:12:54 +00005321/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005322/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005323static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005324 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005325 bool IsSigned = false) {
5326 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005327
Dan Gohman6de29f82009-06-15 22:12:54 +00005328 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5329 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005330 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5331 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5332 ExtractElement(In1, Idx, Context),
5333 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005334 IsSigned))
5335 return true;
5336 }
5337 return false;
5338 }
5339
5340 return HasAddOverflow(cast<ConstantInt>(Result),
5341 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5342 IsSigned);
5343}
5344
5345static bool HasSubOverflow(ConstantInt *Result,
5346 ConstantInt *In1, ConstantInt *In2,
5347 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005348 if (IsSigned)
5349 if (In2->getValue().isNegative())
5350 return Result->getValue().slt(In1->getValue());
5351 else
5352 return Result->getValue().sgt(In1->getValue());
5353 else
5354 return Result->getValue().ugt(In1->getValue());
5355}
5356
Dan Gohman6de29f82009-06-15 22:12:54 +00005357/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5358/// overflowed for this type.
5359static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005360 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005361 bool IsSigned = false) {
5362 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005363
5364 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5365 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005366 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5367 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5368 ExtractElement(In1, Idx, Context),
5369 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005370 IsSigned))
5371 return true;
5372 }
5373 return false;
5374 }
5375
5376 return HasSubOverflow(cast<ConstantInt>(Result),
5377 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5378 IsSigned);
5379}
5380
Chris Lattner574da9b2005-01-13 20:14:25 +00005381/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5382/// code necessary to compute the offset from the base pointer (without adding
5383/// in the base pointer). Return the result as a signed integer of intptr size.
5384static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5385 TargetData &TD = IC.getTargetData();
5386 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005387 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005388 LLVMContext *Context = IC.getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00005389 Value *Result = Context->getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005390
5391 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005392 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005393 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005394
Gabor Greif177dd3f2008-06-12 21:37:33 +00005395 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5396 ++i, ++GTI) {
5397 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005398 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005399 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5400 if (OpC->isZero()) continue;
5401
5402 // Handle a struct index, which adds its field offset to the pointer.
5403 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5404 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5405
5406 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005407 Result =
5408 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005409 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005410 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005411 BinaryOperator::CreateAdd(Result,
Owen Andersond672ecb2009-07-03 00:17:18 +00005412 Context->getConstantInt(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005413 GEP->getName()+".offs"), I);
5414 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005415 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005416
Owen Andersond672ecb2009-07-03 00:17:18 +00005417 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5418 Constant *OC =
5419 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5420 Scale = Context->getConstantExprMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005421 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005422 Result = Context->getConstantExprAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005423 else {
5424 // Emit an add instruction.
5425 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005426 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005427 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005428 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005429 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005430 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005431 // Convert to correct type.
5432 if (Op->getType() != IntPtrTy) {
5433 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005434 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005435 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005436 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5437 true,
5438 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005439 }
5440 if (Size != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005441 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005442 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005443 Op = Context->getConstantExprMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005444 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005445 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005446 GEP->getName()+".idx"), I);
5447 }
5448
5449 // Emit an add instruction.
5450 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005451 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005452 cast<Constant>(Result));
5453 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005454 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005455 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005456 }
5457 return Result;
5458}
5459
Chris Lattner10c0d912008-04-22 02:53:33 +00005460
5461/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5462/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5463/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5464/// complex, and scales are involved. The above expression would also be legal
5465/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5466/// later form is less amenable to optimization though, and we are allowed to
5467/// generate the first by knowing that pointer arithmetic doesn't overflow.
5468///
5469/// If we can't emit an optimized form for this expression, this returns null.
5470///
5471static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5472 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005473 TargetData &TD = IC.getTargetData();
5474 gep_type_iterator GTI = gep_type_begin(GEP);
5475
5476 // Check to see if this gep only has a single variable index. If so, and if
5477 // any constant indices are a multiple of its scale, then we can compute this
5478 // in terms of the scale of the variable index. For example, if the GEP
5479 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5480 // because the expression will cross zero at the same point.
5481 unsigned i, e = GEP->getNumOperands();
5482 int64_t Offset = 0;
5483 for (i = 1; i != e; ++i, ++GTI) {
5484 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5485 // Compute the aggregate offset of constant indices.
5486 if (CI->isZero()) continue;
5487
5488 // Handle a struct index, which adds its field offset to the pointer.
5489 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5490 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5491 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005492 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005493 Offset += Size*CI->getSExtValue();
5494 }
5495 } else {
5496 // Found our variable index.
5497 break;
5498 }
5499 }
5500
5501 // If there are no variable indices, we must have a constant offset, just
5502 // evaluate it the general way.
5503 if (i == e) return 0;
5504
5505 Value *VariableIdx = GEP->getOperand(i);
5506 // Determine the scale factor of the variable element. For example, this is
5507 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005508 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005509
5510 // Verify that there are no other variable indices. If so, emit the hard way.
5511 for (++i, ++GTI; i != e; ++i, ++GTI) {
5512 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5513 if (!CI) return 0;
5514
5515 // Compute the aggregate offset of constant indices.
5516 if (CI->isZero()) continue;
5517
5518 // Handle a struct index, which adds its field offset to the pointer.
5519 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5520 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5521 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005522 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005523 Offset += Size*CI->getSExtValue();
5524 }
5525 }
5526
5527 // Okay, we know we have a single variable index, which must be a
5528 // pointer/array/vector index. If there is no offset, life is simple, return
5529 // the index.
5530 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5531 if (Offset == 0) {
5532 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5533 // we don't need to bother extending: the extension won't affect where the
5534 // computation crosses zero.
5535 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5536 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5537 VariableIdx->getNameStart(), &I);
5538 return VariableIdx;
5539 }
5540
5541 // Otherwise, there is an index. The computation we will do will be modulo
5542 // the pointer size, so get it.
5543 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5544
5545 Offset &= PtrSizeMask;
5546 VariableScale &= PtrSizeMask;
5547
5548 // To do this transformation, any constant index must be a multiple of the
5549 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5550 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5551 // multiple of the variable scale.
5552 int64_t NewOffs = Offset / (int64_t)VariableScale;
5553 if (Offset != NewOffs*(int64_t)VariableScale)
5554 return 0;
5555
5556 // Okay, we can do this evaluation. Start by converting the index to intptr.
5557 const Type *IntPtrTy = TD.getIntPtrType();
5558 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005559 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005560 true /*SExt*/,
5561 VariableIdx->getNameStart(), &I);
Owen Andersond672ecb2009-07-03 00:17:18 +00005562 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005563 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005564}
5565
5566
Reid Spencere4d87aa2006-12-23 06:05:41 +00005567/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005568/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005569Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5570 ICmpInst::Predicate Cond,
5571 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005572 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005573
Chris Lattner10c0d912008-04-22 02:53:33 +00005574 // Look through bitcasts.
5575 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5576 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005577
Chris Lattner574da9b2005-01-13 20:14:25 +00005578 Value *PtrBase = GEPLHS->getOperand(0);
5579 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005580 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005581 // This transformation (ignoring the base and scales) is valid because we
5582 // know pointers can't overflow. See if we can output an optimized form.
5583 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5584
5585 // If not, synthesize the offset the hard way.
5586 if (Offset == 0)
5587 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005588 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersond672ecb2009-07-03 00:17:18 +00005589 Context->getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005590 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005591 // If the base pointers are different, but the indices are the same, just
5592 // compare the base pointer.
5593 if (PtrBase != GEPRHS->getOperand(0)) {
5594 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005595 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005596 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005597 if (IndicesTheSame)
5598 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5599 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5600 IndicesTheSame = false;
5601 break;
5602 }
5603
5604 // If all indices are the same, just compare the base pointers.
5605 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005606 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005607 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005608
5609 // Otherwise, the base pointers are different and the indices are
5610 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005611 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005612 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005613
Chris Lattnere9d782b2005-01-13 22:25:21 +00005614 // If one of the GEPs has all zero indices, recurse.
5615 bool AllZeros = true;
5616 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5617 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5618 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5619 AllZeros = false;
5620 break;
5621 }
5622 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005623 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5624 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005625
5626 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005627 AllZeros = true;
5628 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5629 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5630 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5631 AllZeros = false;
5632 break;
5633 }
5634 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005635 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005636
Chris Lattner4401c9c2005-01-14 00:20:05 +00005637 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5638 // If the GEPs only differ by one index, compare it.
5639 unsigned NumDifferences = 0; // Keep track of # differences.
5640 unsigned DiffOperand = 0; // The operand that differs.
5641 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5642 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005643 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5644 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005645 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005646 NumDifferences = 2;
5647 break;
5648 } else {
5649 if (NumDifferences++) break;
5650 DiffOperand = i;
5651 }
5652 }
5653
5654 if (NumDifferences == 0) // SAME GEP?
5655 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersond672ecb2009-07-03 00:17:18 +00005656 Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005657 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005658
Chris Lattner4401c9c2005-01-14 00:20:05 +00005659 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005660 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5661 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005662 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005663 return new ICmpInst(*Context,
5664 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005665 }
5666 }
5667
Reid Spencere4d87aa2006-12-23 06:05:41 +00005668 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005669 // the result to fold to a constant!
5670 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5671 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5672 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5673 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5674 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005675 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005676 }
5677 }
5678 return 0;
5679}
5680
Chris Lattnera5406232008-05-19 20:18:56 +00005681/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5682///
5683Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5684 Instruction *LHSI,
5685 Constant *RHSC) {
5686 if (!isa<ConstantFP>(RHSC)) return 0;
5687 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5688
5689 // Get the width of the mantissa. We don't want to hack on conversions that
5690 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005691 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005692 if (MantissaWidth == -1) return 0; // Unknown.
5693
5694 // Check to see that the input is converted from an integer type that is small
5695 // enough that preserves all bits. TODO: check here for "known" sign bits.
5696 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00005697 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005698
5699 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005700 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5701 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005702 ++InputSize;
5703
5704 // If the conversion would lose info, don't hack on this.
5705 if ((int)InputSize > MantissaWidth)
5706 return 0;
5707
5708 // Otherwise, we can potentially simplify the comparison. We know that it
5709 // will always come through as an integer value and we know the constant is
5710 // not a NAN (it would have been previously simplified).
5711 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5712
5713 ICmpInst::Predicate Pred;
5714 switch (I.getPredicate()) {
Torok Edwinc25e7582009-07-11 20:10:48 +00005715 default: LLVM_UNREACHABLE("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005716 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005717 case FCmpInst::FCMP_OEQ:
5718 Pred = ICmpInst::ICMP_EQ;
5719 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005720 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005721 case FCmpInst::FCMP_OGT:
5722 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5723 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005724 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005725 case FCmpInst::FCMP_OGE:
5726 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5727 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005728 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005729 case FCmpInst::FCMP_OLT:
5730 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5731 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005732 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005733 case FCmpInst::FCMP_OLE:
5734 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5735 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005736 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005737 case FCmpInst::FCMP_ONE:
5738 Pred = ICmpInst::ICMP_NE;
5739 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005740 case FCmpInst::FCMP_ORD:
Owen Andersond672ecb2009-07-03 00:17:18 +00005741 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005742 case FCmpInst::FCMP_UNO:
Owen Andersond672ecb2009-07-03 00:17:18 +00005743 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005744 }
5745
5746 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5747
5748 // Now we know that the APFloat is a normal number, zero or inf.
5749
Chris Lattner85162782008-05-20 03:50:52 +00005750 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005751 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005752 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005753
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005754 if (!LHSUnsigned) {
5755 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5756 // and large values.
5757 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5758 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5759 APFloat::rmNearestTiesToEven);
5760 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5761 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5762 Pred == ICmpInst::ICMP_SLE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005763 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5764 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005765 }
5766 } else {
5767 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5768 // +INF and large values.
5769 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5770 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5771 APFloat::rmNearestTiesToEven);
5772 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5773 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5774 Pred == ICmpInst::ICMP_ULE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005775 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5776 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005777 }
Chris Lattnera5406232008-05-19 20:18:56 +00005778 }
5779
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005780 if (!LHSUnsigned) {
5781 // See if the RHS value is < SignedMin.
5782 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5783 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5784 APFloat::rmNearestTiesToEven);
5785 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5786 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5787 Pred == ICmpInst::ICMP_SGE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005788 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5789 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005790 }
Chris Lattnera5406232008-05-19 20:18:56 +00005791 }
5792
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005793 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5794 // [0, UMAX], but it may still be fractional. See if it is fractional by
5795 // casting the FP value to the integer value and back, checking for equality.
5796 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005797 Constant *RHSInt = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005798 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5799 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005800 if (!RHS.isZero()) {
5801 bool Equal = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005802 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5803 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005804 if (!Equal) {
5805 // If we had a comparison against a fractional value, we have to adjust
5806 // the compare predicate and sometimes the value. RHSC is rounded towards
5807 // zero at this point.
5808 switch (Pred) {
Torok Edwinc25e7582009-07-11 20:10:48 +00005809 default: LLVM_UNREACHABLE("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005810 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00005811 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005812 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Andersond672ecb2009-07-03 00:17:18 +00005813 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005814 case ICmpInst::ICMP_ULE:
5815 // (float)int <= 4.4 --> int <= 4
5816 // (float)int <= -4.4 --> false
5817 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005818 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005819 break;
5820 case ICmpInst::ICMP_SLE:
5821 // (float)int <= 4.4 --> int <= 4
5822 // (float)int <= -4.4 --> int < -4
5823 if (RHS.isNegative())
5824 Pred = ICmpInst::ICMP_SLT;
5825 break;
5826 case ICmpInst::ICMP_ULT:
5827 // (float)int < -4.4 --> false
5828 // (float)int < 4.4 --> int <= 4
5829 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005830 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005831 Pred = ICmpInst::ICMP_ULE;
5832 break;
5833 case ICmpInst::ICMP_SLT:
5834 // (float)int < -4.4 --> int < -4
5835 // (float)int < 4.4 --> int <= 4
5836 if (!RHS.isNegative())
5837 Pred = ICmpInst::ICMP_SLE;
5838 break;
5839 case ICmpInst::ICMP_UGT:
5840 // (float)int > 4.4 --> int > 4
5841 // (float)int > -4.4 --> true
5842 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005843 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005844 break;
5845 case ICmpInst::ICMP_SGT:
5846 // (float)int > 4.4 --> int > 4
5847 // (float)int > -4.4 --> int >= -4
5848 if (RHS.isNegative())
5849 Pred = ICmpInst::ICMP_SGE;
5850 break;
5851 case ICmpInst::ICMP_UGE:
5852 // (float)int >= -4.4 --> true
5853 // (float)int >= 4.4 --> int > 4
5854 if (!RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005855 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005856 Pred = ICmpInst::ICMP_UGT;
5857 break;
5858 case ICmpInst::ICMP_SGE:
5859 // (float)int >= -4.4 --> int >= -4
5860 // (float)int >= 4.4 --> int > 4
5861 if (!RHS.isNegative())
5862 Pred = ICmpInst::ICMP_SGT;
5863 break;
5864 }
Chris Lattnera5406232008-05-19 20:18:56 +00005865 }
5866 }
5867
5868 // Lower this FP comparison into an appropriate integer version of the
5869 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005870 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005871}
5872
Reid Spencere4d87aa2006-12-23 06:05:41 +00005873Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5874 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005875 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005876
Chris Lattner58e97462007-01-14 19:42:17 +00005877 // Fold trivial predicates.
5878 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005879 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005880 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005881 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005882
5883 // Simplify 'fcmp pred X, X'
5884 if (Op0 == Op1) {
5885 switch (I.getPredicate()) {
Torok Edwinc25e7582009-07-11 20:10:48 +00005886 default: LLVM_UNREACHABLE("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005887 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5888 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5889 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Andersond672ecb2009-07-03 00:17:18 +00005890 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005891 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5892 case FCmpInst::FCMP_OLT: // True if ordered and less than
5893 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Andersond672ecb2009-07-03 00:17:18 +00005894 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005895
5896 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5897 case FCmpInst::FCMP_ULT: // True if unordered or less than
5898 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5899 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5900 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5901 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersond672ecb2009-07-03 00:17:18 +00005902 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005903 return &I;
5904
5905 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5906 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5907 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5908 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5909 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5910 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersond672ecb2009-07-03 00:17:18 +00005911 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005912 return &I;
5913 }
5914 }
5915
Reid Spencere4d87aa2006-12-23 06:05:41 +00005916 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005917 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005918
Reid Spencere4d87aa2006-12-23 06:05:41 +00005919 // Handle fcmp with constant RHS
5920 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005921 // If the constant is a nan, see if we can fold the comparison based on it.
5922 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5923 if (CFP->getValueAPF().isNaN()) {
5924 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Andersond672ecb2009-07-03 00:17:18 +00005925 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005926 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5927 "Comparison must be either ordered or unordered!");
5928 // True if unordered.
Owen Andersond672ecb2009-07-03 00:17:18 +00005929 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005930 }
5931 }
5932
Reid Spencere4d87aa2006-12-23 06:05:41 +00005933 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5934 switch (LHSI->getOpcode()) {
5935 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005936 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5937 // block. If in the same block, we're encouraging jump threading. If
5938 // not, we are just pessimizing the code by making an i1 phi.
5939 if (LHSI->getParent() == I.getParent())
5940 if (Instruction *NV = FoldOpIntoPhi(I))
5941 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005942 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005943 case Instruction::SIToFP:
5944 case Instruction::UIToFP:
5945 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5946 return NV;
5947 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005948 case Instruction::Select:
5949 // If either operand of the select is a constant, we can fold the
5950 // comparison into the select arms, which will cause one to be
5951 // constant folded and the select turned into a bitwise or.
5952 Value *Op1 = 0, *Op2 = 0;
5953 if (LHSI->hasOneUse()) {
5954 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5955 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005956 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005957 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005958 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005959 LHSI->getOperand(2), RHSC,
5960 I.getName()), I);
5961 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5962 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005963 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005964 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005965 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005966 LHSI->getOperand(1), RHSC,
5967 I.getName()), I);
5968 }
5969 }
5970
5971 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005972 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005973 break;
5974 }
5975 }
5976
5977 return Changed ? &I : 0;
5978}
5979
5980Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5981 bool Changed = SimplifyCompare(I);
5982 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5983 const Type *Ty = Op0->getType();
5984
5985 // icmp X, X
5986 if (Op0 == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005987 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005988 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005989
5990 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005991 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005992
Reid Spencere4d87aa2006-12-23 06:05:41 +00005993 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005994 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005995 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5996 isa<ConstantPointerNull>(Op0)) &&
5997 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005998 isa<ConstantPointerNull>(Op1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005999 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006000 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00006001
Reid Spencere4d87aa2006-12-23 06:05:41 +00006002 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00006003 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006004 switch (I.getPredicate()) {
Torok Edwinc25e7582009-07-11 20:10:48 +00006005 default: LLVM_UNREACHABLE("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006006 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006007 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00006008 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006009 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006010 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006011 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006012 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006013
Reid Spencere4d87aa2006-12-23 06:05:41 +00006014 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006015 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006016 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006017 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006018 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006019 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006020 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006021 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006022 case ICmpInst::ICMP_SGT:
6023 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006024 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006025 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
6026 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6027 InsertNewInstBefore(Not, I);
6028 return BinaryOperator::CreateAnd(Not, Op0);
6029 }
6030 case ICmpInst::ICMP_UGE:
6031 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6032 // FALL THROUGH
6033 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006034 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006035 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006036 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006037 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006038 case ICmpInst::ICMP_SGE:
6039 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6040 // FALL THROUGH
6041 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
6042 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6043 InsertNewInstBefore(Not, I);
6044 return BinaryOperator::CreateOr(Not, Op0);
6045 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006046 }
Chris Lattner8b170942002-08-09 23:47:40 +00006047 }
6048
Dan Gohman1c8491e2009-04-25 17:12:48 +00006049 unsigned BitWidth = 0;
6050 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006051 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6052 else if (Ty->isIntOrIntVector())
6053 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006054
6055 bool isSignBit = false;
6056
Dan Gohman81b28ce2008-09-16 18:46:06 +00006057 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006058 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006059 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006060
Chris Lattnerb6566012008-01-05 01:18:20 +00006061 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6062 if (I.isEquality() && CI->isNullValue() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006063 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006064 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006065 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006066 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006067
Dan Gohman81b28ce2008-09-16 18:46:06 +00006068 // If we have an icmp le or icmp ge instruction, turn it into the
6069 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6070 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006071 switch (I.getPredicate()) {
6072 default: break;
6073 case ICmpInst::ICMP_ULE:
6074 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006075 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006076 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6077 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006078 case ICmpInst::ICMP_SLE:
6079 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006080 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006081 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6082 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006083 case ICmpInst::ICMP_UGE:
6084 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006085 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006086 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6087 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006088 case ICmpInst::ICMP_SGE:
6089 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006090 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006091 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6092 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006093 }
6094
Chris Lattner183661e2008-07-11 05:40:05 +00006095 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006096 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006097 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006098 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6099 }
6100
6101 // See if we can fold the comparison based on range information we can get
6102 // by checking whether bits are known to be zero or one in the input.
6103 if (BitWidth != 0) {
6104 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6105 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6106
6107 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006108 isSignBit ? APInt::getSignBit(BitWidth)
6109 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006110 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006111 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006112 if (SimplifyDemandedBits(I.getOperandUse(1),
6113 APInt::getAllOnesValue(BitWidth),
6114 Op1KnownZero, Op1KnownOne, 0))
6115 return &I;
6116
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006117 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006118 // in. Compute the Min, Max and RHS values based on the known bits. For the
6119 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006120 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6121 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6122 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6123 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6124 Op0Min, Op0Max);
6125 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6126 Op1Min, Op1Max);
6127 } else {
6128 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6129 Op0Min, Op0Max);
6130 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6131 Op1Min, Op1Max);
6132 }
6133
Chris Lattner183661e2008-07-11 05:40:05 +00006134 // If Min and Max are known to be the same, then SimplifyDemandedBits
6135 // figured out that the LHS is a constant. Just constant fold this now so
6136 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006137 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006138 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006139 Context->getConstantInt(Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006140 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006141 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006142 Context->getConstantInt(Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006143
Chris Lattner183661e2008-07-11 05:40:05 +00006144 // Based on the range information we know about the LHS, see if we can
6145 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006146 switch (I.getPredicate()) {
Torok Edwinc25e7582009-07-11 20:10:48 +00006147 default: LLVM_UNREACHABLE("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006148 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006149 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersond672ecb2009-07-03 00:17:18 +00006150 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006151 break;
6152 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006153 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersond672ecb2009-07-03 00:17:18 +00006154 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner84dff672008-07-11 05:08:55 +00006155 break;
6156 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006157 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006158 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006160 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006162 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6164 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006165 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6166 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167
6168 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6169 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006170 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006171 Context->getConstantIntAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006172 }
Chris Lattner84dff672008-07-11 05:08:55 +00006173 break;
6174 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006175 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006176 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006178 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006179
6180 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006181 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6183 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006184 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6185 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186
6187 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6188 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006189 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006190 Context->getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006191 }
Chris Lattner84dff672008-07-11 05:08:55 +00006192 break;
6193 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006194 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Andersond672ecb2009-07-03 00:17:18 +00006195 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006196 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Andersond672ecb2009-07-03 00:17:18 +00006197 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006199 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006200 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6201 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006202 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6203 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006204 }
Chris Lattner84dff672008-07-11 05:08:55 +00006205 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 case ICmpInst::ICMP_SGT:
6207 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006208 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006209 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006210 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006211
6212 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006213 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006214 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6215 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006216 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6217 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006218 }
6219 break;
6220 case ICmpInst::ICMP_SGE:
6221 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6222 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006223 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006224 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006225 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006226 break;
6227 case ICmpInst::ICMP_SLE:
6228 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6229 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006230 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006232 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006233 break;
6234 case ICmpInst::ICMP_UGE:
6235 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6236 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006237 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006238 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006239 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006240 break;
6241 case ICmpInst::ICMP_ULE:
6242 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6243 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006244 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006245 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006246 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006247 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006248 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006249
6250 // Turn a signed comparison into an unsigned one if both operands
6251 // are known to have the same sign.
6252 if (I.isSignedPredicate() &&
6253 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6254 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006255 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006256 }
6257
6258 // Test if the ICmpInst instruction is used exclusively by a select as
6259 // part of a minimum or maximum operation. If so, refrain from doing
6260 // any other folding. This helps out other analyses which understand
6261 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6262 // and CodeGen. And in this case, at least one of the comparison
6263 // operands has at least one user besides the compare (the select),
6264 // which would often largely negate the benefit of folding anyway.
6265 if (I.hasOneUse())
6266 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6267 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6268 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6269 return 0;
6270
6271 // See if we are doing a comparison between a constant and an instruction that
6272 // can be folded into the comparison.
6273 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006274 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006275 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006276 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006277 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006278 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6279 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006280 }
6281
Chris Lattner01deb9d2007-04-03 17:43:25 +00006282 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006283 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6284 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6285 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006286 case Instruction::GetElementPtr:
6287 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006288 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006289 bool isAllZeros = true;
6290 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6291 if (!isa<Constant>(LHSI->getOperand(i)) ||
6292 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6293 isAllZeros = false;
6294 break;
6295 }
6296 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006297 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006298 Context->getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006299 }
6300 break;
6301
Chris Lattner6970b662005-04-23 15:31:55 +00006302 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006303 // Only fold icmp into the PHI if the phi and fcmp are in the same
6304 // block. If in the same block, we're encouraging jump threading. If
6305 // not, we are just pessimizing the code by making an i1 phi.
6306 if (LHSI->getParent() == I.getParent())
6307 if (Instruction *NV = FoldOpIntoPhi(I))
6308 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006309 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006310 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006311 // If either operand of the select is a constant, we can fold the
6312 // comparison into the select arms, which will cause one to be
6313 // constant folded and the select turned into a bitwise or.
6314 Value *Op1 = 0, *Op2 = 0;
6315 if (LHSI->hasOneUse()) {
6316 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6317 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006318 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006319 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006320 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006321 LHSI->getOperand(2), RHSC,
6322 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006323 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6324 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006325 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006326 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006327 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006328 LHSI->getOperand(1), RHSC,
6329 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006330 }
6331 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006332
Chris Lattner6970b662005-04-23 15:31:55 +00006333 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006334 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006335 break;
6336 }
Chris Lattner4802d902007-04-06 18:57:34 +00006337 case Instruction::Malloc:
6338 // If we have (malloc != null), and if the malloc has a single use, we
6339 // can assume it is successful and remove the malloc.
6340 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6341 AddToWorkList(LHSI);
Owen Andersond672ecb2009-07-03 00:17:18 +00006342 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006343 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006344 }
6345 break;
6346 }
Chris Lattner6970b662005-04-23 15:31:55 +00006347 }
6348
Reid Spencere4d87aa2006-12-23 06:05:41 +00006349 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006350 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006351 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006352 return NI;
6353 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006354 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6355 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006356 return NI;
6357
Reid Spencere4d87aa2006-12-23 06:05:41 +00006358 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006359 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6360 // now.
6361 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6362 if (isa<PointerType>(Op0->getType()) &&
6363 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006364 // We keep moving the cast from the left operand over to the right
6365 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006366 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006367
Chris Lattner57d86372007-01-06 01:45:59 +00006368 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6369 // so eliminate it as well.
6370 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6371 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006372
Chris Lattnerde90b762003-11-03 04:25:02 +00006373 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006374 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006375 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006376 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006377 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006378 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006379 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006380 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006381 }
Owen Anderson333c4002009-07-09 23:48:35 +00006382 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006383 }
Chris Lattner57d86372007-01-06 01:45:59 +00006384 }
6385
6386 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006387 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006388 // This comes up when you have code like
6389 // int X = A < B;
6390 // if (X) ...
6391 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006392 // with a constant or another cast from the same type.
6393 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006394 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006395 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006396 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006397
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006398 // See if it's the same type of instruction on the left and right.
6399 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6400 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006401 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006402 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006403 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006404 default: break;
6405 case Instruction::Add:
6406 case Instruction::Sub:
6407 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006408 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006409 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006410 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006411 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6412 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6413 if (CI->getValue().isSignBit()) {
6414 ICmpInst::Predicate Pred = I.isSignedPredicate()
6415 ? I.getUnsignedPredicate()
6416 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006417 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006418 Op1I->getOperand(0));
6419 }
6420
6421 if (CI->getValue().isMaxSignedValue()) {
6422 ICmpInst::Predicate Pred = I.isSignedPredicate()
6423 ? I.getUnsignedPredicate()
6424 : I.getSignedPredicate();
6425 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006426 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006427 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006428 }
6429 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006430 break;
6431 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006432 if (!I.isEquality())
6433 break;
6434
Nick Lewycky5d52c452008-08-21 05:56:10 +00006435 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6436 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6437 // Mask = -1 >> count-trailing-zeros(Cst).
6438 if (!CI->isZero() && !CI->isOne()) {
6439 const APInt &AP = CI->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +00006440 ConstantInt *Mask = Context->getConstantInt(
Nick Lewycky5d52c452008-08-21 05:56:10 +00006441 APInt::getLowBitsSet(AP.getBitWidth(),
6442 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006443 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006444 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6445 Mask);
6446 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6447 Mask);
6448 InsertNewInstBefore(And1, I);
6449 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006450 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006451 }
6452 }
6453 break;
6454 }
6455 }
6456 }
6457 }
6458
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006459 // ~x < ~y --> y < x
6460 { Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006461 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6462 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006463 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006464 }
6465
Chris Lattner65b72ba2006-09-18 04:22:48 +00006466 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006467 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006468
6469 // -x == -y --> x == y
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006470 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6471 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006472 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006473
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006474 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006475 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6476 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006477 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006478 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006479 }
6480
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006481 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006482 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006483 ConstantInt *C1, *C2;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006484 if (match(B, m_ConstantInt(C1), *Context) &&
6485 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006486 Constant *NC =
6487 Context->getConstantInt(C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006488 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006489 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006490 InsertNewInstBefore(Xor, I));
6491 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006492
6493 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006494 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6495 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6496 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6497 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006498 }
6499 }
6500
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006501 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006502 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006503 // A == (A^B) -> B == 0
6504 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006505 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006506 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006507 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006508
6509 // (A-B) == A -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006510 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006511 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006512 Context->getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006513
6514 // A == (A-B) -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006515 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006516 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006517 Context->getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006518
Chris Lattner9c2328e2006-11-14 06:06:06 +00006519 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6520 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006521 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6522 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006523 Value *X = 0, *Y = 0, *Z = 0;
6524
6525 if (A == C) {
6526 X = B; Y = D; Z = A;
6527 } else if (A == D) {
6528 X = B; Y = C; Z = A;
6529 } else if (B == C) {
6530 X = A; Y = D; Z = B;
6531 } else if (B == D) {
6532 X = A; Y = C; Z = B;
6533 }
6534
6535 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006536 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6537 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006538 I.setOperand(0, Op1);
Owen Andersond672ecb2009-07-03 00:17:18 +00006539 I.setOperand(1, Context->getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006540 return &I;
6541 }
6542 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006543 }
Chris Lattner7e708292002-06-25 16:13:24 +00006544 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006545}
6546
Chris Lattner562ef782007-06-20 23:46:26 +00006547
6548/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6549/// and CmpRHS are both known to be integer constants.
6550Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6551 ConstantInt *DivRHS) {
6552 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6553 const APInt &CmpRHSV = CmpRHS->getValue();
6554
6555 // FIXME: If the operand types don't match the type of the divide
6556 // then don't attempt this transform. The code below doesn't have the
6557 // logic to deal with a signed divide and an unsigned compare (and
6558 // vice versa). This is because (x /s C1) <s C2 produces different
6559 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6560 // (x /u C1) <u C2. Simply casting the operands and result won't
6561 // work. :( The if statement below tests that condition and bails
6562 // if it finds it.
6563 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6564 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6565 return 0;
6566 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006567 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006568 if (DivIsSigned && DivRHS->isAllOnesValue())
6569 return 0; // The overflow computation also screws up here
6570 if (DivRHS->isOne())
6571 return 0; // Not worth bothering, and eliminates some funny cases
6572 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006573
6574 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6575 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6576 // C2 (CI). By solving for X we can turn this into a range check
6577 // instead of computing a divide.
Owen Andersond672ecb2009-07-03 00:17:18 +00006578 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006579
6580 // Determine if the product overflows by seeing if the product is
6581 // not equal to the divide. Make sure we do the same kind of divide
6582 // as in the LHS instruction that we're folding.
Owen Andersond672ecb2009-07-03 00:17:18 +00006583 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6584 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006585
6586 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006587 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006588
Chris Lattner1dbfd482007-06-21 18:11:19 +00006589 // Figure out the interval that is being checked. For example, a comparison
6590 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6591 // Compute this interval based on the constants involved and the signedness of
6592 // the compare/divide. This computes a half-open interval, keeping track of
6593 // whether either value in the interval overflows. After analysis each
6594 // overflow variable is set to 0 if it's corresponding bound variable is valid
6595 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6596 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006597 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006598
Chris Lattner562ef782007-06-20 23:46:26 +00006599 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006600 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006601 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006602 HiOverflow = LoOverflow = ProdOV;
6603 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006604 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006605 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006606 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006607 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00006608 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6609 Context)));
Chris Lattner562ef782007-06-20 23:46:26 +00006610 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006611 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006612 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6613 HiOverflow = LoOverflow = ProdOV;
6614 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006615 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006616 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006617 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006618 HiBound = AddOne(Prod, Context);
Chris Lattnera6321b42008-10-11 22:55:00 +00006619 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6620 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006621 ConstantInt* DivNeg =
6622 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6623 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006624 true) ? -1 : 0;
6625 }
Chris Lattner562ef782007-06-20 23:46:26 +00006626 }
Dan Gohman76491272008-02-13 22:09:18 +00006627 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006628 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006629 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersond672ecb2009-07-03 00:17:18 +00006630 LoBound = AddOne(DivRHS, Context);
6631 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006632 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6633 HiOverflow = 1; // [INTMIN+1, overflow)
6634 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6635 }
Dan Gohman76491272008-02-13 22:09:18 +00006636 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006637 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006638 HiBound = AddOne(Prod, Context);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006639 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006640 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006641 LoOverflow = AddWithOverflow(LoBound, HiBound,
6642 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006643 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006644 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6645 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006646 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006647 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006648 }
6649
Chris Lattner1dbfd482007-06-21 18:11:19 +00006650 // Dividing by a negative swaps the condition. LT <-> GT
6651 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006652 }
6653
6654 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006655 switch (Pred) {
Torok Edwinc25e7582009-07-11 20:10:48 +00006656 default: LLVM_UNREACHABLE("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006657 case ICmpInst::ICMP_EQ:
6658 if (LoOverflow && HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006659 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner562ef782007-06-20 23:46:26 +00006660 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006661 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006662 ICmpInst::ICMP_UGE, X, LoBound);
6663 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006664 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006665 ICmpInst::ICMP_ULT, X, HiBound);
6666 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006667 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006668 case ICmpInst::ICMP_NE:
6669 if (LoOverflow && HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006670 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner562ef782007-06-20 23:46:26 +00006671 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006672 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006673 ICmpInst::ICMP_ULT, X, LoBound);
6674 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006675 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006676 ICmpInst::ICMP_UGE, X, HiBound);
6677 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006678 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006679 case ICmpInst::ICMP_ULT:
6680 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006681 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006682 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006683 if (LoOverflow == -1) // Low bound is less than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006684 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00006685 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006686 case ICmpInst::ICMP_UGT:
6687 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006688 if (HiOverflow == +1) // High bound greater than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006689 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006690 else if (HiOverflow == -1) // High bound less than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006691 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006692 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006693 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006694 else
Owen Anderson333c4002009-07-09 23:48:35 +00006695 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006696 }
6697}
6698
6699
Chris Lattner01deb9d2007-04-03 17:43:25 +00006700/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6701///
6702Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6703 Instruction *LHSI,
6704 ConstantInt *RHS) {
6705 const APInt &RHSV = RHS->getValue();
6706
6707 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006708 case Instruction::Trunc:
6709 if (ICI.isEquality() && LHSI->hasOneUse()) {
6710 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6711 // of the high bits truncated out of x are known.
6712 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6713 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6714 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6715 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6716 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6717
6718 // If all the high bits are known, we can do this xform.
6719 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6720 // Pull in the high bits from known-ones set.
6721 APInt NewRHS(RHS->getValue());
6722 NewRHS.zext(SrcBits);
6723 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006724 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006725 Context->getConstantInt(NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006726 }
6727 }
6728 break;
6729
Duncan Sands0091bf22007-04-04 06:42:45 +00006730 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006731 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6732 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6733 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006734 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6735 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006736 Value *CompareVal = LHSI->getOperand(0);
6737
6738 // If the sign bit of the XorCST is not set, there is no change to
6739 // the operation, just stop using the Xor.
6740 if (!XorCST->getValue().isNegative()) {
6741 ICI.setOperand(0, CompareVal);
6742 AddToWorkList(LHSI);
6743 return &ICI;
6744 }
6745
6746 // Was the old condition true if the operand is positive?
6747 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6748
6749 // If so, the new one isn't.
6750 isTrueIfPositive ^= true;
6751
6752 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006753 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006754 SubOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006755 else
Owen Anderson333c4002009-07-09 23:48:35 +00006756 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006757 AddOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006758 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006759
6760 if (LHSI->hasOneUse()) {
6761 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6762 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6763 const APInt &SignBit = XorCST->getValue();
6764 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6765 ? ICI.getUnsignedPredicate()
6766 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006767 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006768 Context->getConstantInt(RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006769 }
6770
6771 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006772 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006773 const APInt &NotSignBit = XorCST->getValue();
6774 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6775 ? ICI.getUnsignedPredicate()
6776 : ICI.getSignedPredicate();
6777 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006778 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006779 Context->getConstantInt(RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006780 }
6781 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006782 }
6783 break;
6784 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6785 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6786 LHSI->getOperand(0)->hasOneUse()) {
6787 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6788
6789 // If the LHS is an AND of a truncating cast, we can widen the
6790 // and/compare to be the input width without changing the value
6791 // produced, eliminating a cast.
6792 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6793 // We can do this transformation if either the AND constant does not
6794 // have its sign bit set or if it is an equality comparison.
6795 // Extending a relational comparison when we're checking the sign
6796 // bit would not work.
6797 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006798 (ICI.isEquality() ||
6799 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006800 uint32_t BitWidth =
6801 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6802 APInt NewCST = AndCST->getValue();
6803 NewCST.zext(BitWidth);
6804 APInt NewCI = RHSV;
6805 NewCI.zext(BitWidth);
6806 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006807 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006808 Context->getConstantInt(NewCST),LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006809 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006810 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersond672ecb2009-07-03 00:17:18 +00006811 Context->getConstantInt(NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006812 }
6813 }
6814
6815 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6816 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6817 // happens a LOT in code produced by the C front-end, for bitfield
6818 // access.
6819 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6820 if (Shift && !Shift->isShift())
6821 Shift = 0;
6822
6823 ConstantInt *ShAmt;
6824 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6825 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6826 const Type *AndTy = AndCST->getType(); // Type of the and.
6827
6828 // We can fold this as long as we can't shift unknown bits
6829 // into the mask. This can only happen with signed shift
6830 // rights, as they sign-extend.
6831 if (ShAmt) {
6832 bool CanFold = Shift->isLogicalShift();
6833 if (!CanFold) {
6834 // To test for the bad case of the signed shr, see if any
6835 // of the bits shifted in could be tested after the mask.
6836 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6837 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6838
6839 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6840 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6841 AndCST->getValue()) == 0)
6842 CanFold = true;
6843 }
6844
6845 if (CanFold) {
6846 Constant *NewCst;
6847 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006848 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006849 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006850 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006851
6852 // Check to see if we are shifting out any of the bits being
6853 // compared.
Owen Andersond672ecb2009-07-03 00:17:18 +00006854 if (Context->getConstantExpr(Shift->getOpcode(),
6855 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006856 // If we shifted bits out, the fold is not going to work out.
6857 // As a special case, check to see if this means that the
6858 // result is always true or false now.
6859 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersond672ecb2009-07-03 00:17:18 +00006860 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006861 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersond672ecb2009-07-03 00:17:18 +00006862 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006863 } else {
6864 ICI.setOperand(1, NewCst);
6865 Constant *NewAndCST;
6866 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006867 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006868 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006869 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006870 LHSI->setOperand(1, NewAndCST);
6871 LHSI->setOperand(0, Shift->getOperand(0));
6872 AddToWorkList(Shift); // Shift is dead.
6873 AddUsesToWorkList(ICI);
6874 return &ICI;
6875 }
6876 }
6877 }
6878
6879 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6880 // preferable because it allows the C<<Y expression to be hoisted out
6881 // of a loop if Y is invariant and X is not.
6882 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006883 ICI.isEquality() && !Shift->isArithmeticShift() &&
6884 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006885 // Compute C << Y.
6886 Value *NS;
6887 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006888 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006889 Shift->getOperand(1), "tmp");
6890 } else {
6891 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006892 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006893 Shift->getOperand(1), "tmp");
6894 }
6895 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6896
6897 // Compute X & (C << Y).
6898 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006899 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006900 InsertNewInstBefore(NewAnd, ICI);
6901
6902 ICI.setOperand(0, NewAnd);
6903 return &ICI;
6904 }
6905 }
6906 break;
6907
Chris Lattnera0141b92007-07-15 20:42:37 +00006908 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6909 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6910 if (!ShAmt) break;
6911
6912 uint32_t TypeBits = RHSV.getBitWidth();
6913
6914 // Check that the shift amount is in range. If not, don't perform
6915 // undefined shifts. When the shift is visited it will be
6916 // simplified.
6917 if (ShAmt->uge(TypeBits))
6918 break;
6919
6920 if (ICI.isEquality()) {
6921 // If we are comparing against bits always shifted out, the
6922 // comparison cannot succeed.
6923 Constant *Comp =
Owen Andersond672ecb2009-07-03 00:17:18 +00006924 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6925 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006926 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6927 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006928 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006929 return ReplaceInstUsesWith(ICI, Cst);
6930 }
6931
6932 if (LHSI->hasOneUse()) {
6933 // Otherwise strength reduce the shift into an and.
6934 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6935 Constant *Mask =
Owen Andersond672ecb2009-07-03 00:17:18 +00006936 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6937 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006938
Chris Lattnera0141b92007-07-15 20:42:37 +00006939 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006940 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006941 Mask, LHSI->getName()+".mask");
6942 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006943 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006944 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006945 }
6946 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006947
6948 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6949 bool TrueIfSigned = false;
6950 if (LHSI->hasOneUse() &&
6951 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6952 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersond672ecb2009-07-03 00:17:18 +00006953 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006954 (TypeBits-ShAmt->getZExtValue()-1));
6955 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006956 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006957 Mask, LHSI->getName()+".mask");
6958 Value *And = InsertNewInstBefore(AndI, ICI);
6959
Owen Anderson333c4002009-07-09 23:48:35 +00006960 return new ICmpInst(*Context,
6961 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersond672ecb2009-07-03 00:17:18 +00006962 And, Context->getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006963 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006964 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006965 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006966
6967 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006968 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006969 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006970 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006971 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006972
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006973 // Check that the shift amount is in range. If not, don't perform
6974 // undefined shifts. When the shift is visited it will be
6975 // simplified.
6976 uint32_t TypeBits = RHSV.getBitWidth();
6977 if (ShAmt->uge(TypeBits))
6978 break;
6979
6980 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006981
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006982 // If we are comparing against bits always shifted out, the
6983 // comparison cannot succeed.
6984 APInt Comp = RHSV << ShAmtVal;
6985 if (LHSI->getOpcode() == Instruction::LShr)
6986 Comp = Comp.lshr(ShAmtVal);
6987 else
6988 Comp = Comp.ashr(ShAmtVal);
6989
6990 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6991 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006992 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006993 return ReplaceInstUsesWith(ICI, Cst);
6994 }
6995
6996 // Otherwise, check to see if the bits shifted out are known to be zero.
6997 // If so, we can compare against the unshifted value:
6998 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006999 if (LHSI->hasOneUse() &&
7000 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007001 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00007002 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007003 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007004 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007005
Evan Chengf30752c2008-04-23 00:38:06 +00007006 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007007 // Otherwise strength reduce the shift into an and.
7008 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00007009 Constant *Mask = Context->getConstantInt(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007010
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007011 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007012 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007013 Mask, LHSI->getName()+".mask");
7014 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007015 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00007016 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007017 }
7018 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007019 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007020
7021 case Instruction::SDiv:
7022 case Instruction::UDiv:
7023 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7024 // Fold this div into the comparison, producing a range check.
7025 // Determine, based on the divide type, what the range is being
7026 // checked. If there is an overflow on the low or high side, remember
7027 // it, otherwise compute the range [low, hi) bounding the new value.
7028 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007029 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7030 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7031 DivRHS))
7032 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007033 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007034
7035 case Instruction::Add:
7036 // Fold: icmp pred (add, X, C1), C2
7037
7038 if (!ICI.isEquality()) {
7039 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7040 if (!LHSC) break;
7041 const APInt &LHSV = LHSC->getValue();
7042
7043 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7044 .subtract(LHSV);
7045
7046 if (ICI.isSignedPredicate()) {
7047 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007048 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007049 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007050 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007051 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007052 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007053 }
7054 } else {
7055 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007056 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007057 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007058 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007059 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007060 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007061 }
7062 }
7063 }
7064 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007065 }
7066
7067 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7068 if (ICI.isEquality()) {
7069 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7070
7071 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7072 // the second operand is a constant, simplify a bit.
7073 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7074 switch (BO->getOpcode()) {
7075 case Instruction::SRem:
7076 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7077 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7078 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7079 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7080 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007081 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007082 BO->getName());
7083 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007084 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersond672ecb2009-07-03 00:17:18 +00007085 Context->getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007086 }
7087 }
7088 break;
7089 case Instruction::Add:
7090 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7091 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7092 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007093 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007094 Context->getConstantExprSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007095 } else if (RHSV == 0) {
7096 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7097 // efficiently invertible, or if the add has just this one use.
7098 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7099
Owen Andersond672ecb2009-07-03 00:17:18 +00007100 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007101 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersond672ecb2009-07-03 00:17:18 +00007102 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007103 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007104 else if (BO->hasOneUse()) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00007105 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007106 InsertNewInstBefore(Neg, ICI);
7107 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007108 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007109 }
7110 }
7111 break;
7112 case Instruction::Xor:
7113 // For the xor case, we can xor two constants together, eliminating
7114 // the explicit xor.
7115 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007116 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007117 Context->getConstantExprXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007118
7119 // FALLTHROUGH
7120 case Instruction::Sub:
7121 // Replace (([sub|xor] A, B) != 0) with (A != B)
7122 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007123 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007124 BO->getOperand(1));
7125 break;
7126
7127 case Instruction::Or:
7128 // If bits are being or'd in that are not present in the constant we
7129 // are comparing against, then the comparison could never succeed!
7130 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007131 Constant *NotCI = Context->getConstantExprNot(RHS);
7132 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7133 return ReplaceInstUsesWith(ICI,
7134 Context->getConstantInt(Type::Int1Ty,
7135 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007136 }
7137 break;
7138
7139 case Instruction::And:
7140 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7141 // If bits are being compared against that are and'd out, then the
7142 // comparison can never succeed!
7143 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007144 return ReplaceInstUsesWith(ICI,
7145 Context->getConstantInt(Type::Int1Ty,
7146 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007147
7148 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7149 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007150 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007151 ICmpInst::ICMP_NE, LHSI,
Owen Andersond672ecb2009-07-03 00:17:18 +00007152 Context->getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007153
7154 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007155 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007156 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007157 Constant *Zero = Context->getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007158 ICmpInst::Predicate pred = isICMP_NE ?
7159 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007160 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007161 }
7162
7163 // ((X & ~7) == 0) --> X < 8
7164 if (RHSV == 0 && isHighOnes(BOC)) {
7165 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007166 Constant *NegX = Context->getConstantExprNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007167 ICmpInst::Predicate pred = isICMP_NE ?
7168 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007169 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007170 }
7171 }
7172 default: break;
7173 }
7174 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7175 // Handle icmp {eq|ne} <intrinsic>, intcst.
7176 if (II->getIntrinsicID() == Intrinsic::bswap) {
7177 AddToWorkList(II);
7178 ICI.setOperand(0, II->getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007179 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007180 return &ICI;
7181 }
7182 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007183 }
7184 return 0;
7185}
7186
7187/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7188/// We only handle extending casts so far.
7189///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007190Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7191 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007192 Value *LHSCIOp = LHSCI->getOperand(0);
7193 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007194 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007195 Value *RHSCIOp;
7196
Chris Lattner8c756c12007-05-05 22:41:33 +00007197 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7198 // integer type is the same size as the pointer type.
7199 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7200 getTargetData().getPointerSizeInBits() ==
7201 cast<IntegerType>(DestTy)->getBitWidth()) {
7202 Value *RHSOp = 0;
7203 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007204 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007205 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7206 RHSOp = RHSC->getOperand(0);
7207 // If the pointer types don't match, insert a bitcast.
7208 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007209 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007210 }
7211
7212 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007213 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007214 }
7215
7216 // The code below only handles extension cast instructions, so far.
7217 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007218 if (LHSCI->getOpcode() != Instruction::ZExt &&
7219 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007220 return 0;
7221
Reid Spencere4d87aa2006-12-23 06:05:41 +00007222 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7223 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007224
Reid Spencere4d87aa2006-12-23 06:05:41 +00007225 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007226 // Not an extension from the same type?
7227 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007228 if (RHSCIOp->getType() != LHSCIOp->getType())
7229 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007230
Nick Lewycky4189a532008-01-28 03:48:02 +00007231 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007232 // and the other is a zext), then we can't handle this.
7233 if (CI->getOpcode() != LHSCI->getOpcode())
7234 return 0;
7235
Nick Lewycky4189a532008-01-28 03:48:02 +00007236 // Deal with equality cases early.
7237 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007238 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007239
7240 // A signed comparison of sign extended values simplifies into a
7241 // signed comparison.
7242 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007243 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007244
7245 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007246 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007247 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007248
Reid Spencere4d87aa2006-12-23 06:05:41 +00007249 // If we aren't dealing with a constant on the RHS, exit early
7250 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7251 if (!CI)
7252 return 0;
7253
7254 // Compute the constant that would happen if we truncated to SrcTy then
7255 // reextended to DestTy.
Owen Andersond672ecb2009-07-03 00:17:18 +00007256 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7257 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7258 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007259
7260 // If the re-extended constant didn't change...
7261 if (Res2 == CI) {
7262 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7263 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007264 // %A = sext i16 %X to i32
7265 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007266 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007267 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007268 // because %A may have negative value.
7269 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007270 // However, we allow this when the compare is EQ/NE, because they are
7271 // signless.
7272 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007273 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007274 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007275 }
7276
7277 // The re-extended constant changed so the constant cannot be represented
7278 // in the shorter type. Consequently, we cannot emit a simple comparison.
7279
7280 // First, handle some easy cases. We know the result cannot be equal at this
7281 // point so handle the ICI.isEquality() cases
7282 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersond672ecb2009-07-03 00:17:18 +00007283 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007284 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersond672ecb2009-07-03 00:17:18 +00007285 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007286
7287 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7288 // should have been folded away previously and not enter in here.
7289 Value *Result;
7290 if (isSignedCmp) {
7291 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007292 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00007293 Result = Context->getConstantIntFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007294 else
Owen Andersond672ecb2009-07-03 00:17:18 +00007295 Result = Context->getConstantIntTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007296 } else {
7297 // We're performing an unsigned comparison.
7298 if (isSignedExt) {
7299 // We're performing an unsigned comp with a sign extended value.
7300 // This is true if the input is >= 0. [aka >s -1]
Owen Andersond672ecb2009-07-03 00:17:18 +00007301 Constant *NegOne = Context->getConstantIntAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007302 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7303 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007304 } else {
7305 // Unsigned extend & unsigned compare -> always true.
Owen Andersond672ecb2009-07-03 00:17:18 +00007306 Result = Context->getConstantIntTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007307 }
7308 }
7309
7310 // Finally, return the value computed.
7311 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007312 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007313 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007314
7315 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7316 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7317 "ICmp should be folded!");
7318 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00007319 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Chris Lattnerf2991842008-07-11 04:09:09 +00007320 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007321}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007322
Reid Spencer832254e2007-02-02 02:16:23 +00007323Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7324 return commonShiftTransforms(I);
7325}
7326
7327Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7328 return commonShiftTransforms(I);
7329}
7330
7331Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007332 if (Instruction *R = commonShiftTransforms(I))
7333 return R;
7334
7335 Value *Op0 = I.getOperand(0);
7336
7337 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7338 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7339 if (CSI->isAllOnesValue())
7340 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007341
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007342 // See if we can turn a signed shr into an unsigned shr.
7343 if (MaskedValueIsZero(Op0,
7344 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7345 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7346
7347 // Arithmetic shifting an all-sign-bit value is a no-op.
7348 unsigned NumSignBits = ComputeNumSignBits(Op0);
7349 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7350 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007351
Chris Lattner348f6652007-12-06 01:59:46 +00007352 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007353}
7354
7355Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7356 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007357 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007358
7359 // shl X, 0 == X and shr X, 0 == X
7360 // shl 0, X == 0 and shr 0, X == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007361 if (Op1 == Context->getNullValue(Op1->getType()) ||
7362 Op0 == Context->getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007363 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007364
Reid Spencere4d87aa2006-12-23 06:05:41 +00007365 if (isa<UndefValue>(Op0)) {
7366 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007367 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007368 else // undef << X -> 0, undef >>u X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007369 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007370 }
7371 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007372 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7373 return ReplaceInstUsesWith(I, Op0);
7374 else // X << undef, X >>u undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007375 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007376 }
7377
Dan Gohman9004c8a2009-05-21 02:28:33 +00007378 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007379 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007380 return &I;
7381
Chris Lattner2eefe512004-04-09 19:05:30 +00007382 // Try to fold constant and into select arguments.
7383 if (isa<Constant>(Op0))
7384 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007385 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007386 return R;
7387
Reid Spencerb83eb642006-10-20 07:07:24 +00007388 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007389 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7390 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007391 return 0;
7392}
7393
Reid Spencerb83eb642006-10-20 07:07:24 +00007394Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007395 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007396 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007397
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007398 // See if we can simplify any instructions used by the instruction whose sole
7399 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007400 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007401
Dan Gohmana119de82009-06-14 23:30:43 +00007402 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7403 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007404 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007405 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007406 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007407 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007408 else {
Owen Andersond672ecb2009-07-03 00:17:18 +00007409 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007410 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007411 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007412 }
7413
7414 // ((X*C1) << C2) == (X * (C1 << C2))
7415 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7416 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7417 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007418 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007419 Context->getConstantExprShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007420
7421 // Try to fold constant and into select arguments.
7422 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7423 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7424 return R;
7425 if (isa<PHINode>(Op0))
7426 if (Instruction *NV = FoldOpIntoPhi(I))
7427 return NV;
7428
Chris Lattner8999dd32007-12-22 09:07:47 +00007429 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7430 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7431 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7432 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7433 // place. Don't try to do this transformation in this case. Also, we
7434 // require that the input operand is a shift-by-constant so that we have
7435 // confidence that the shifts will get folded together. We could do this
7436 // xform in more cases, but it is unlikely to be profitable.
7437 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7438 isa<ConstantInt>(TrOp->getOperand(1))) {
7439 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersond672ecb2009-07-03 00:17:18 +00007440 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007441 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007442 I.getName());
7443 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7444
7445 // For logical shifts, the truncation has the effect of making the high
7446 // part of the register be zeros. Emulate this by inserting an AND to
7447 // clear the top bits as needed. This 'and' will usually be zapped by
7448 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007449 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7450 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007451 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7452
7453 // The mask we constructed says what the trunc would do if occurring
7454 // between the shifts. We want to know the effect *after* the second
7455 // shift. We know that it is a logical shift by a constant, so adjust the
7456 // mask as appropriate.
7457 if (I.getOpcode() == Instruction::Shl)
7458 MaskV <<= Op1->getZExtValue();
7459 else {
7460 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7461 MaskV = MaskV.lshr(Op1->getZExtValue());
7462 }
7463
Owen Andersond672ecb2009-07-03 00:17:18 +00007464 Instruction *And =
7465 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7466 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007467 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7468
7469 // Return the value truncated to the interesting size.
7470 return new TruncInst(And, I.getType());
7471 }
7472 }
7473
Chris Lattner4d5542c2006-01-06 07:12:35 +00007474 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007475 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7476 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7477 Value *V1, *V2;
7478 ConstantInt *CC;
7479 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007480 default: break;
7481 case Instruction::Add:
7482 case Instruction::And:
7483 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007484 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007485 // These operators commute.
7486 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007487 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007488 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7489 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007490 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007491 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007492 Op0BO->getName());
7493 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007494 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007495 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007496 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007497 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007498 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007499 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007500 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007501 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007502
Chris Lattner150f12a2005-09-18 06:30:59 +00007503 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007504 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007505 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007506 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007507 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007508 m_ConstantInt(CC)), *Context) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007509 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007510 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007511 Op0BO->getOperand(0), Op1,
7512 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007513 InsertNewInstBefore(YS, I); // (Y << C)
7514 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007515 BinaryOperator::CreateAnd(V1,
7516 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007517 V1->getName()+".mask");
7518 InsertNewInstBefore(XM, I); // X & (CC << C)
7519
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007520 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007521 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007522 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007523
Reid Spencera07cb7d2007-02-02 14:41:37 +00007524 // FALL THROUGH.
7525 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007526 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007527 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007528 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7529 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007530 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007531 Op0BO->getOperand(1), Op1,
7532 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007533 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007534 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007535 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007536 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007537 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007538 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007539 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007540 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007541 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007542
Chris Lattner13d4ab42006-05-31 21:14:00 +00007543 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007544 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7545 match(Op0BO->getOperand(0),
7546 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007547 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007548 cast<BinaryOperator>(Op0BO->getOperand(0))
7549 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007550 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007551 Op0BO->getOperand(1), Op1,
7552 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007553 InsertNewInstBefore(YS, I); // (Y << C)
7554 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007555 BinaryOperator::CreateAnd(V1,
7556 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007557 V1->getName()+".mask");
7558 InsertNewInstBefore(XM, I); // X & (CC << C)
7559
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007560 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007561 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007562
Chris Lattner11021cb2005-09-18 05:12:10 +00007563 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007564 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007565 }
7566
7567
7568 // If the operand is an bitwise operator with a constant RHS, and the
7569 // shift is the only use, we can pull it out of the shift.
7570 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7571 bool isValid = true; // Valid only for And, Or, Xor
7572 bool highBitSet = false; // Transform if high bit of constant set?
7573
7574 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007575 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007576 case Instruction::Add:
7577 isValid = isLeftShift;
7578 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007579 case Instruction::Or:
7580 case Instruction::Xor:
7581 highBitSet = false;
7582 break;
7583 case Instruction::And:
7584 highBitSet = true;
7585 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007586 }
7587
7588 // If this is a signed shift right, and the high bit is modified
7589 // by the logical operation, do not perform the transformation.
7590 // The highBitSet boolean indicates the value of the high bit of
7591 // the constant which would cause it to be modified for this
7592 // operation.
7593 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007594 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007595 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007596
7597 if (isValid) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007598 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007599
7600 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007601 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007602 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007603 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007604
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007605 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007606 NewRHS);
7607 }
7608 }
7609 }
7610 }
7611
Chris Lattnerad0124c2006-01-06 07:52:12 +00007612 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007613 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7614 if (ShiftOp && !ShiftOp->isShift())
7615 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007616
Reid Spencerb83eb642006-10-20 07:07:24 +00007617 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007618 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007619 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7620 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007621 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7622 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7623 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007624
Zhou Sheng4351c642007-04-02 08:20:41 +00007625 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007626
7627 const IntegerType *Ty = cast<IntegerType>(I.getType());
7628
7629 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007630 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007631 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7632 // saturates.
7633 if (AmtSum >= TypeBits) {
7634 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007635 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007636 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7637 }
7638
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007639 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007640 Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007641 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7642 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007643 if (AmtSum >= TypeBits)
Owen Andersond672ecb2009-07-03 00:17:18 +00007644 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007645
Chris Lattnerb87056f2007-02-05 00:57:54 +00007646 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersond672ecb2009-07-03 00:17:18 +00007647 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007648 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7649 I.getOpcode() == Instruction::LShr) {
7650 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007651 if (AmtSum >= TypeBits)
7652 AmtSum = TypeBits-1;
7653
Chris Lattnerb87056f2007-02-05 00:57:54 +00007654 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007655 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007656 InsertNewInstBefore(Shift, I);
7657
Zhou Shenge9e03f62007-03-28 15:02:20 +00007658 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007659 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007660 }
7661
Chris Lattnerb87056f2007-02-05 00:57:54 +00007662 // Okay, if we get here, one shift must be left, and the other shift must be
7663 // right. See if the amounts are equal.
7664 if (ShiftAmt1 == ShiftAmt2) {
7665 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7666 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007667 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007668 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007669 }
7670 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7671 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007672 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007673 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007674 }
7675 // We can simplify ((X << C) >>s C) into a trunc + sext.
7676 // NOTE: we could do this for any C, but that would make 'unusual' integer
7677 // types. For now, just stick to ones well-supported by the code
7678 // generators.
7679 const Type *SExtType = 0;
7680 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007681 case 1 :
7682 case 8 :
7683 case 16 :
7684 case 32 :
7685 case 64 :
7686 case 128:
Owen Andersond672ecb2009-07-03 00:17:18 +00007687 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007688 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007689 default: break;
7690 }
7691 if (SExtType) {
7692 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7693 InsertNewInstBefore(NewTrunc, I);
7694 return new SExtInst(NewTrunc, Ty);
7695 }
7696 // Otherwise, we can't handle it yet.
7697 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007698 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007699
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007700 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007701 if (I.getOpcode() == Instruction::Shl) {
7702 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7703 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007704 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007705 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007706 InsertNewInstBefore(Shift, I);
7707
Reid Spencer55702aa2007-03-25 21:11:44 +00007708 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007709 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007710 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007711
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007712 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007713 if (I.getOpcode() == Instruction::LShr) {
7714 assert(ShiftOp->getOpcode() == Instruction::Shl);
7715 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007716 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007717 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007718
Reid Spencerd5e30f02007-03-26 17:18:58 +00007719 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007720 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007721 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007722
7723 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7724 } else {
7725 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007726 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007727
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007728 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007729 if (I.getOpcode() == Instruction::Shl) {
7730 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7731 ShiftOp->getOpcode() == Instruction::AShr);
7732 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007733 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007734 Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007735 InsertNewInstBefore(Shift, I);
7736
Reid Spencer55702aa2007-03-25 21:11:44 +00007737 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007738 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007739 }
7740
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007741 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007742 if (I.getOpcode() == Instruction::LShr) {
7743 assert(ShiftOp->getOpcode() == Instruction::Shl);
7744 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007745 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007746 InsertNewInstBefore(Shift, I);
7747
Reid Spencer68d27cf2007-03-26 23:45:51 +00007748 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007749 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007750 }
7751
7752 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007753 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007754 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007755 return 0;
7756}
7757
Chris Lattnera1be5662002-05-02 17:06:02 +00007758
Chris Lattnercfd65102005-10-29 04:36:15 +00007759/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7760/// expression. If so, decompose it, returning some value X, such that Val is
7761/// X*Scale+Offset.
7762///
7763static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007764 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007765 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007766 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007767 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007768 Scale = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00007769 return Context->getConstantInt(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007770 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7771 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7772 if (I->getOpcode() == Instruction::Shl) {
7773 // This is a value scaled by '1 << the shift amt'.
7774 Scale = 1U << RHS->getZExtValue();
7775 Offset = 0;
7776 return I->getOperand(0);
7777 } else if (I->getOpcode() == Instruction::Mul) {
7778 // This value is scaled by 'RHS'.
7779 Scale = RHS->getZExtValue();
7780 Offset = 0;
7781 return I->getOperand(0);
7782 } else if (I->getOpcode() == Instruction::Add) {
7783 // We have X+C. Check to see if we really have (X*C2)+C1,
7784 // where C1 is divisible by C2.
7785 unsigned SubScale;
7786 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007787 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7788 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007789 Offset += RHS->getZExtValue();
7790 Scale = SubScale;
7791 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007792 }
7793 }
7794 }
7795
7796 // Otherwise, we can't look past this.
7797 Scale = 1;
7798 Offset = 0;
7799 return Val;
7800}
7801
7802
Chris Lattnerb3f83972005-10-24 06:03:58 +00007803/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7804/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007805Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007806 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007807 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007808
Chris Lattnerb53c2382005-10-24 06:22:12 +00007809 // Remove any uses of AI that are dead.
7810 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007811
Chris Lattnerb53c2382005-10-24 06:22:12 +00007812 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7813 Instruction *User = cast<Instruction>(*UI++);
7814 if (isInstructionTriviallyDead(User)) {
7815 while (UI != E && *UI == User)
7816 ++UI; // If this instruction uses AI more than once, don't break UI.
7817
Chris Lattnerb53c2382005-10-24 06:22:12 +00007818 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007819 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007820 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007821 }
7822 }
7823
Chris Lattnerb3f83972005-10-24 06:03:58 +00007824 // Get the type really allocated and the type casted to.
7825 const Type *AllocElTy = AI.getAllocatedType();
7826 const Type *CastElTy = PTy->getElementType();
7827 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007828
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007829 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7830 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007831 if (CastElTyAlign < AllocElTyAlign) return 0;
7832
Chris Lattner39387a52005-10-24 06:35:18 +00007833 // If the allocation has multiple uses, only promote it if we are strictly
7834 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007835 // same, we open the door to infinite loops of various kinds. (A reference
7836 // from a dbg.declare doesn't count as a use for this purpose.)
7837 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7838 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007839
Duncan Sands777d2302009-05-09 07:06:46 +00007840 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7841 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007842 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007843
Chris Lattner455fcc82005-10-29 03:19:53 +00007844 // See if we can satisfy the modulus by pulling a scale out of the array
7845 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007846 unsigned ArraySizeScale;
7847 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007848 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007849 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7850 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007851
Chris Lattner455fcc82005-10-29 03:19:53 +00007852 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7853 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007854 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7855 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007856
Chris Lattner455fcc82005-10-29 03:19:53 +00007857 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7858 Value *Amt = 0;
7859 if (Scale == 1) {
7860 Amt = NumElements;
7861 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007862 // If the allocation size is constant, form a constant mul expression
Owen Andersond672ecb2009-07-03 00:17:18 +00007863 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007864 if (isa<ConstantInt>(NumElements))
Owen Andersond672ecb2009-07-03 00:17:18 +00007865 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007866 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007867 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007868 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007869 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007870 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007871 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007872 }
7873
Jeff Cohen86796be2007-04-04 16:58:57 +00007874 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007875 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007876 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007877 Amt = InsertNewInstBefore(Tmp, AI);
7878 }
7879
Chris Lattnerb3f83972005-10-24 06:03:58 +00007880 AllocationInst *New;
7881 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007882 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007883 else
Chris Lattner6934a042007-02-11 01:23:03 +00007884 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007885 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007886 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007887
Dale Johannesena0a66372009-03-05 00:39:02 +00007888 // If the allocation has one real use plus a dbg.declare, just remove the
7889 // declare.
7890 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7891 EraseInstFromFunction(*DI);
7892 }
7893 // If the allocation has multiple real uses, insert a cast and change all
7894 // things that used it to use the new cast. This will also hack on CI, but it
7895 // will die soon.
7896 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007897 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007898 // New is the allocation instruction, pointer typed. AI is the original
7899 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7900 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007901 InsertNewInstBefore(NewCast, AI);
7902 AI.replaceAllUsesWith(NewCast);
7903 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007904 return ReplaceInstUsesWith(CI, New);
7905}
7906
Chris Lattner70074e02006-05-13 02:06:03 +00007907/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007908/// and return it as type Ty without inserting any new casts and without
7909/// changing the computed value. This is used by code that tries to decide
7910/// whether promoting or shrinking integer operations to wider or smaller types
7911/// will allow us to eliminate a truncate or extend.
7912///
7913/// This is a truncation operation if Ty is smaller than V->getType(), or an
7914/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007915///
7916/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7917/// should return true if trunc(V) can be computed by computing V in the smaller
7918/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7919/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7920/// efficiently truncated.
7921///
7922/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7923/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7924/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007925bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007926 unsigned CastOpc,
7927 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007928 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007929 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007930 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007931
7932 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007933 if (!I) return false;
7934
Dan Gohman6de29f82009-06-15 22:12:54 +00007935 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007936
Chris Lattner951626b2007-08-02 06:11:14 +00007937 // If this is an extension or truncate, we can often eliminate it.
7938 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7939 // If this is a cast from the destination type, we can trivially eliminate
7940 // it, and this will remove a cast overall.
7941 if (I->getOperand(0)->getType() == Ty) {
7942 // If the first operand is itself a cast, and is eliminable, do not count
7943 // this as an eliminable cast. We would prefer to eliminate those two
7944 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007945 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007946 ++NumCastsRemoved;
7947 return true;
7948 }
7949 }
7950
7951 // We can't extend or shrink something that has multiple uses: doing so would
7952 // require duplicating the instruction in general, which isn't profitable.
7953 if (!I->hasOneUse()) return false;
7954
Evan Chengf35fd542009-01-15 17:01:23 +00007955 unsigned Opc = I->getOpcode();
7956 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007957 case Instruction::Add:
7958 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007959 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007960 case Instruction::And:
7961 case Instruction::Or:
7962 case Instruction::Xor:
7963 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007964 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007965 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007966 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007967 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007968
Chris Lattner46b96052006-11-29 07:18:39 +00007969 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007970 // If we are truncating the result of this SHL, and if it's a shift of a
7971 // constant amount, we can always perform a SHL in a smaller type.
7972 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007973 uint32_t BitWidth = Ty->getScalarSizeInBits();
7974 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007975 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007976 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007977 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007978 }
7979 break;
7980 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007981 // If this is a truncate of a logical shr, we can truncate it to a smaller
7982 // lshr iff we know that the bits we would otherwise be shifting in are
7983 // already zeros.
7984 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007985 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7986 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007987 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007988 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007989 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7990 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007991 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007992 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007993 }
7994 }
Chris Lattner46b96052006-11-29 07:18:39 +00007995 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007996 case Instruction::ZExt:
7997 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007998 case Instruction::Trunc:
7999 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008000 // can safely replace it. Note that replacing it does not reduce the number
8001 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008002 if (Opc == CastOpc)
8003 return true;
8004
8005 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008006 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008007 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008008 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008009 case Instruction::Select: {
8010 SelectInst *SI = cast<SelectInst>(I);
8011 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008012 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008013 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008014 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008015 }
Chris Lattner8114b712008-06-18 04:00:49 +00008016 case Instruction::PHI: {
8017 // We can change a phi if we can change all operands.
8018 PHINode *PN = cast<PHINode>(I);
8019 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8020 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008021 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008022 return false;
8023 return true;
8024 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008025 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008026 // TODO: Can handle more cases here.
8027 break;
8028 }
8029
8030 return false;
8031}
8032
8033/// EvaluateInDifferentType - Given an expression that
8034/// CanEvaluateInDifferentType returns true for, actually insert the code to
8035/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008036Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008037 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008038 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +00008039 return Context->getConstantExprIntegerCast(C, Ty,
8040 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008041
8042 // Otherwise, it must be an instruction.
8043 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008044 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008045 unsigned Opc = I->getOpcode();
8046 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008047 case Instruction::Add:
8048 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008049 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008050 case Instruction::And:
8051 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008052 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008053 case Instruction::AShr:
8054 case Instruction::LShr:
8055 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008056 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008057 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008058 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008059 break;
8060 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008061 case Instruction::Trunc:
8062 case Instruction::ZExt:
8063 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008064 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008065 // just return the source. There's no need to insert it because it is not
8066 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008067 if (I->getOperand(0)->getType() == Ty)
8068 return I->getOperand(0);
8069
Chris Lattner8114b712008-06-18 04:00:49 +00008070 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008071 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008072 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008073 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008074 case Instruction::Select: {
8075 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8076 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8077 Res = SelectInst::Create(I->getOperand(0), True, False);
8078 break;
8079 }
Chris Lattner8114b712008-06-18 04:00:49 +00008080 case Instruction::PHI: {
8081 PHINode *OPN = cast<PHINode>(I);
8082 PHINode *NPN = PHINode::Create(Ty);
8083 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8084 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8085 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8086 }
8087 Res = NPN;
8088 break;
8089 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008090 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008091 // TODO: Can handle more cases here.
Torok Edwinc25e7582009-07-11 20:10:48 +00008092 LLVM_UNREACHABLE("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008093 break;
8094 }
8095
Chris Lattner8114b712008-06-18 04:00:49 +00008096 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008097 return InsertNewInstBefore(Res, *I);
8098}
8099
Reid Spencer3da59db2006-11-27 01:05:10 +00008100/// @brief Implement the transforms common to all CastInst visitors.
8101Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008102 Value *Src = CI.getOperand(0);
8103
Dan Gohman23d9d272007-05-11 21:10:54 +00008104 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008105 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008106 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008107 if (Instruction::CastOps opc =
8108 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8109 // The first cast (CSrc) is eliminable so we need to fix up or replace
8110 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008111 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008112 }
8113 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008114
Reid Spencer3da59db2006-11-27 01:05:10 +00008115 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008116 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8117 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8118 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008119
8120 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008121 if (isa<PHINode>(Src))
8122 if (Instruction *NV = FoldOpIntoPhi(CI))
8123 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008124
Reid Spencer3da59db2006-11-27 01:05:10 +00008125 return 0;
8126}
8127
Chris Lattner46cd5a12009-01-09 05:44:56 +00008128/// FindElementAtOffset - Given a type and a constant offset, determine whether
8129/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008130/// the specified offset. If so, fill them into NewIndices and return the
8131/// resultant element type, otherwise return null.
8132static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8133 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008134 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008135 LLVMContext *Context) {
Chris Lattner3914f722009-01-24 01:00:13 +00008136 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008137
8138 // Start with the index over the outer type. Note that the type size
8139 // might be zero (even if the offset isn't zero) if the indexed type
8140 // is something like [0 x {int, int}]
8141 const Type *IntPtrTy = TD->getIntPtrType();
8142 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008143 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008144 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008145 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008146
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008147 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008148 if (Offset < 0) {
8149 --FirstIdx;
8150 Offset += TySize;
8151 assert(Offset >= 0);
8152 }
8153 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8154 }
8155
Owen Andersond672ecb2009-07-03 00:17:18 +00008156 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008157
8158 // Index into the types. If we fail, set OrigBase to null.
8159 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008160 // Indexing into tail padding between struct/array elements.
8161 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008162 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008163
Chris Lattner46cd5a12009-01-09 05:44:56 +00008164 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8165 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008166 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8167 "Offset must stay within the indexed type");
8168
Chris Lattner46cd5a12009-01-09 05:44:56 +00008169 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersond672ecb2009-07-03 00:17:18 +00008170 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008171
8172 Offset -= SL->getElementOffset(Elt);
8173 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008174 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008175 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008176 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersond672ecb2009-07-03 00:17:18 +00008177 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008178 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008179 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008180 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008181 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008182 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008183 }
8184 }
8185
Chris Lattner3914f722009-01-24 01:00:13 +00008186 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008187}
8188
Chris Lattnerd3e28342007-04-27 17:44:50 +00008189/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8190Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8191 Value *Src = CI.getOperand(0);
8192
Chris Lattnerd3e28342007-04-27 17:44:50 +00008193 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008194 // If casting the result of a getelementptr instruction with no offset, turn
8195 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008196 if (GEP->hasAllZeroIndices()) {
8197 // Changing the cast operand is usually not a good idea but it is safe
8198 // here because the pointer operand is being replaced with another
8199 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008200 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008201 CI.setOperand(0, GEP->getOperand(0));
8202 return &CI;
8203 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008204
8205 // If the GEP has a single use, and the base pointer is a bitcast, and the
8206 // GEP computes a constant offset, see if we can convert these three
8207 // instructions into fewer. This typically happens with unions and other
8208 // non-type-safe code.
8209 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8210 if (GEP->hasAllConstantIndices()) {
8211 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008212 ConstantInt *OffsetV =
8213 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008214 int64_t Offset = OffsetV->getSExtValue();
8215
8216 // Get the base pointer input of the bitcast, and the type it points to.
8217 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8218 const Type *GEPIdxTy =
8219 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008220 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008221 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008222 // If we were able to index down into an element, create the GEP
8223 // and bitcast the result. This eliminates one bitcast, potentially
8224 // two.
8225 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8226 NewIndices.begin(),
8227 NewIndices.end(), "");
8228 InsertNewInstBefore(NGEP, CI);
8229 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008230
Chris Lattner46cd5a12009-01-09 05:44:56 +00008231 if (isa<BitCastInst>(CI))
8232 return new BitCastInst(NGEP, CI.getType());
8233 assert(isa<PtrToIntInst>(CI));
8234 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008235 }
8236 }
8237 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008238 }
8239
8240 return commonCastTransforms(CI);
8241}
8242
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008243/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8244/// type like i42. We don't want to introduce operations on random non-legal
8245/// integer types where they don't already exist in the code. In the future,
8246/// we should consider making this based off target-data, so that 32-bit targets
8247/// won't get i64 operations etc.
8248static bool isSafeIntegerType(const Type *Ty) {
8249 switch (Ty->getPrimitiveSizeInBits()) {
8250 case 8:
8251 case 16:
8252 case 32:
8253 case 64:
8254 return true;
8255 default:
8256 return false;
8257 }
8258}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008259
Chris Lattnerc739cd62007-03-03 05:27:34 +00008260/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8261/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00008262/// cases.
8263/// @brief Implement the transforms common to CastInst with integer operands
8264Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8265 if (Instruction *Result = commonCastTransforms(CI))
8266 return Result;
8267
8268 Value *Src = CI.getOperand(0);
8269 const Type *SrcTy = Src->getType();
8270 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008271 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8272 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008273
Reid Spencer3da59db2006-11-27 01:05:10 +00008274 // See if we can simplify any instructions used by the LHS whose sole
8275 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008276 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008277 return &CI;
8278
8279 // If the source isn't an instruction or has more than one use then we
8280 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008281 Instruction *SrcI = dyn_cast<Instruction>(Src);
8282 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008283 return 0;
8284
Chris Lattnerc739cd62007-03-03 05:27:34 +00008285 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008286 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008287 if (!isa<BitCastInst>(CI) &&
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008288 // Only do this if the dest type is a simple type, don't convert the
8289 // expression tree to something weird like i93 unless the source is also
8290 // strange.
Dan Gohman6de29f82009-06-15 22:12:54 +00008291 (isSafeIntegerType(DestTy->getScalarType()) ||
8292 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8293 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008294 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008295 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008296 // eliminates the cast, so it is always a win. If this is a zero-extension,
8297 // we need to do an AND to maintain the clear top-part of the computation,
8298 // so we require that the input have eliminated at least one cast. If this
8299 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008300 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008301 bool DoXForm = false;
8302 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008303 switch (CI.getOpcode()) {
8304 default:
8305 // All the others use floating point so we shouldn't actually
8306 // get here because of the check above.
Torok Edwinc25e7582009-07-11 20:10:48 +00008307 LLVM_UNREACHABLE("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008308 case Instruction::Trunc:
8309 DoXForm = true;
8310 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008311 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008312 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008313 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008314 // If it's unnecessary to issue an AND to clear the high bits, it's
8315 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008316 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008317 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8318 if (MaskedValueIsZero(TryRes, Mask))
8319 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008320
8321 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008322 if (TryI->use_empty())
8323 EraseInstFromFunction(*TryI);
8324 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008325 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008326 }
Evan Chengf35fd542009-01-15 17:01:23 +00008327 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008328 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008329 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008330 // If we do not have to emit the truncate + sext pair, then it's always
8331 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008332 //
8333 // It's not safe to eliminate the trunc + sext pair if one of the
8334 // eliminated cast is a truncate. e.g.
8335 // t2 = trunc i32 t1 to i16
8336 // t3 = sext i16 t2 to i32
8337 // !=
8338 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008339 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008340 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8341 if (NumSignBits > (DestBitSize - SrcBitSize))
8342 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008343
8344 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008345 if (TryI->use_empty())
8346 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008347 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008348 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008349 }
Evan Chengf35fd542009-01-15 17:01:23 +00008350 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008351
8352 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008353 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8354 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008355 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8356 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008357 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008358 // Just replace this cast with the result.
8359 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008360
Reid Spencer3da59db2006-11-27 01:05:10 +00008361 assert(Res->getType() == DestTy);
8362 switch (CI.getOpcode()) {
Torok Edwinc25e7582009-07-11 20:10:48 +00008363 default: LLVM_UNREACHABLE("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008364 case Instruction::Trunc:
8365 case Instruction::BitCast:
8366 // Just replace this cast with the result.
8367 return ReplaceInstUsesWith(CI, Res);
8368 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008369 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008370
8371 // If the high bits are already zero, just replace this cast with the
8372 // result.
8373 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8374 if (MaskedValueIsZero(Res, Mask))
8375 return ReplaceInstUsesWith(CI, Res);
8376
8377 // We need to emit an AND to clear the high bits.
Owen Andersond672ecb2009-07-03 00:17:18 +00008378 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008379 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008380 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008381 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008382 case Instruction::SExt: {
8383 // If the high bits are already filled with sign bit, just replace this
8384 // cast with the result.
8385 unsigned NumSignBits = ComputeNumSignBits(Res);
8386 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008387 return ReplaceInstUsesWith(CI, Res);
8388
Reid Spencer3da59db2006-11-27 01:05:10 +00008389 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008390 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008391 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8392 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008393 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008394 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008395 }
8396 }
8397
8398 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8399 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8400
8401 switch (SrcI->getOpcode()) {
8402 case Instruction::Add:
8403 case Instruction::Mul:
8404 case Instruction::And:
8405 case Instruction::Or:
8406 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008407 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00008408 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8409 // Don't insert two casts if they cannot be eliminated. We allow
8410 // two casts to be inserted if the sizes are the same. This could
8411 // only be converting signedness, which is a noop.
8412 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008413 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8414 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00008415 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008416 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8417 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008418 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008419 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008420 }
8421 }
8422
8423 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8424 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8425 SrcI->getOpcode() == Instruction::Xor &&
Owen Andersond672ecb2009-07-03 00:17:18 +00008426 Op1 == Context->getConstantIntTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008427 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008428 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008429 return BinaryOperator::CreateXor(New,
8430 Context->getConstantInt(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008431 }
8432 break;
8433 case Instruction::SDiv:
8434 case Instruction::UDiv:
8435 case Instruction::SRem:
8436 case Instruction::URem:
8437 // If we are just changing the sign, rewrite.
8438 if (DestBitSize == SrcBitSize) {
8439 // Don't insert two casts if they cannot be eliminated. We allow
8440 // two casts to be inserted if the sizes are the same. This could
8441 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008442 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8443 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008444 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8445 Op0, DestTy, *SrcI);
8446 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8447 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008448 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00008449 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8450 }
8451 }
8452 break;
8453
8454 case Instruction::Shl:
8455 // Allow changing the sign of the source operand. Do not allow
8456 // changing the size of the shift, UNLESS the shift amount is a
8457 // constant. We must not change variable sized shifts to a smaller
8458 // size, because it is undefined to shift more bits out than exist
8459 // in the value.
8460 if (DestBitSize == SrcBitSize ||
8461 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00008462 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8463 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008464 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8465 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008466 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008467 }
8468 break;
8469 case Instruction::AShr:
8470 // If this is a signed shr, and if all bits shifted in are about to be
8471 // truncated off, turn it into an unsigned shr to allow greater
8472 // simplifications.
8473 if (DestBitSize < SrcBitSize &&
8474 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008475 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00008476 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8477 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008478 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008479 }
8480 }
8481 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008482 }
8483 return 0;
8484}
8485
Chris Lattner8a9f5712007-04-11 06:57:46 +00008486Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008487 if (Instruction *Result = commonIntCastTransforms(CI))
8488 return Result;
8489
8490 Value *Src = CI.getOperand(0);
8491 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008492 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8493 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008494
8495 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00008496 if (DestBitWidth == 1 &&
8497 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008498 Constant *One = Context->getConstantInt(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008499 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008500 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008501 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008502 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008503
Chris Lattner4f9797d2009-03-24 18:15:30 +00008504 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8505 ConstantInt *ShAmtV = 0;
8506 Value *ShiftOp = 0;
8507 if (Src->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008508 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008509 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8510
8511 // Get a mask for the bits shifting in.
8512 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8513 if (MaskedValueIsZero(ShiftOp, Mask)) {
8514 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersond672ecb2009-07-03 00:17:18 +00008515 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008516
8517 // Okay, we can shrink this. Truncate the input, then return a new
8518 // shift.
8519 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008520 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008521 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008522 }
8523 }
8524
8525 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008526}
8527
Evan Chengb98a10e2008-03-24 00:21:34 +00008528/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8529/// in order to eliminate the icmp.
8530Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8531 bool DoXform) {
8532 // If we are just checking for a icmp eq of a single bit and zext'ing it
8533 // to an integer, then shift the bit to the appropriate place and then
8534 // cast to integer to avoid the comparison.
8535 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8536 const APInt &Op1CV = Op1C->getValue();
8537
8538 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8539 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8540 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8541 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8542 if (!DoXform) return ICI;
8543
8544 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00008545 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008546 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008547 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008548 In->getName()+".lobit"),
8549 CI);
8550 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008551 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008552 false/*ZExt*/, "tmp", &CI);
8553
8554 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008555 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008556 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008557 In->getName()+".not"),
8558 CI);
8559 }
8560
8561 return ReplaceInstUsesWith(CI, In);
8562 }
8563
8564
8565
8566 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8567 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8568 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8569 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8570 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8571 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8572 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8573 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8574 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8575 // This only works for EQ and NE
8576 ICI->isEquality()) {
8577 // If Op1C some other power of two, convert:
8578 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8579 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8580 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8581 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8582
8583 APInt KnownZeroMask(~KnownZero);
8584 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8585 if (!DoXform) return ICI;
8586
8587 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8588 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8589 // (X&4) == 2 --> false
8590 // (X&4) != 2 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00008591 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8592 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008593 return ReplaceInstUsesWith(CI, Res);
8594 }
8595
8596 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8597 Value *In = ICI->getOperand(0);
8598 if (ShiftAmt) {
8599 // Perform a logical shr by shiftamt.
8600 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008601 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersond672ecb2009-07-03 00:17:18 +00008602 Context->getConstantInt(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008603 In->getName()+".lobit"), CI);
8604 }
8605
8606 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersond672ecb2009-07-03 00:17:18 +00008607 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008608 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008609 InsertNewInstBefore(cast<Instruction>(In), CI);
8610 }
8611
8612 if (CI.getType() == In->getType())
8613 return ReplaceInstUsesWith(CI, In);
8614 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008615 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008616 }
8617 }
8618 }
8619
8620 return 0;
8621}
8622
Chris Lattner8a9f5712007-04-11 06:57:46 +00008623Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008624 // If one of the common conversion will work ..
8625 if (Instruction *Result = commonIntCastTransforms(CI))
8626 return Result;
8627
8628 Value *Src = CI.getOperand(0);
8629
Chris Lattnera84f47c2009-02-17 20:47:23 +00008630 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8631 // types and if the sizes are just right we can convert this into a logical
8632 // 'and' which will be much cheaper than the pair of casts.
8633 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8634 // Get the sizes of the types involved. We know that the intermediate type
8635 // will be smaller than A or C, but don't know the relation between A and C.
8636 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008637 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8638 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8639 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008640 // If we're actually extending zero bits, then if
8641 // SrcSize < DstSize: zext(a & mask)
8642 // SrcSize == DstSize: a & mask
8643 // SrcSize > DstSize: trunc(a) & mask
8644 if (SrcSize < DstSize) {
8645 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008646 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008647 Instruction *And =
8648 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8649 InsertNewInstBefore(And, CI);
8650 return new ZExtInst(And, CI.getType());
8651 } else if (SrcSize == DstSize) {
8652 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008653 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008654 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008655 } else if (SrcSize > DstSize) {
8656 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8657 InsertNewInstBefore(Trunc, CI);
8658 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008659 return BinaryOperator::CreateAnd(Trunc,
8660 Context->getConstantInt(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008661 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008662 }
8663 }
8664
Evan Chengb98a10e2008-03-24 00:21:34 +00008665 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8666 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008667
Evan Chengb98a10e2008-03-24 00:21:34 +00008668 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8669 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8670 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8671 // of the (zext icmp) will be transformed.
8672 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8673 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8674 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8675 (transformZExtICmp(LHS, CI, false) ||
8676 transformZExtICmp(RHS, CI, false))) {
8677 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8678 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008679 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008680 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008681 }
8682
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008683 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008684 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8685 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8686 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8687 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008688 if (TI0->getType() == CI.getType())
8689 return
8690 BinaryOperator::CreateAnd(TI0,
Owen Andersond672ecb2009-07-03 00:17:18 +00008691 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008692 }
8693
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008694 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8695 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8696 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8697 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8698 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8699 And->getOperand(1) == C)
8700 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8701 Value *TI0 = TI->getOperand(0);
8702 if (TI0->getType() == CI.getType()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008703 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008704 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8705 InsertNewInstBefore(NewAnd, *And);
8706 return BinaryOperator::CreateXor(NewAnd, ZC);
8707 }
8708 }
8709
Reid Spencer3da59db2006-11-27 01:05:10 +00008710 return 0;
8711}
8712
Chris Lattner8a9f5712007-04-11 06:57:46 +00008713Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008714 if (Instruction *I = commonIntCastTransforms(CI))
8715 return I;
8716
Chris Lattner8a9f5712007-04-11 06:57:46 +00008717 Value *Src = CI.getOperand(0);
8718
Dan Gohman1975d032008-10-30 20:40:10 +00008719 // Canonicalize sign-extend from i1 to a select.
8720 if (Src->getType() == Type::Int1Ty)
8721 return SelectInst::Create(Src,
Owen Andersond672ecb2009-07-03 00:17:18 +00008722 Context->getConstantIntAllOnesValue(CI.getType()),
8723 Context->getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008724
8725 // See if the value being truncated is already sign extended. If so, just
8726 // eliminate the trunc/sext pair.
8727 if (getOpcode(Src) == Instruction::Trunc) {
8728 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008729 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8730 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8731 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008732 unsigned NumSignBits = ComputeNumSignBits(Op);
8733
8734 if (OpBits == DestBits) {
8735 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8736 // bits, it is already ready.
8737 if (NumSignBits > DestBits-MidBits)
8738 return ReplaceInstUsesWith(CI, Op);
8739 } else if (OpBits < DestBits) {
8740 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8741 // bits, just sext from i32.
8742 if (NumSignBits > OpBits-MidBits)
8743 return new SExtInst(Op, CI.getType(), "tmp");
8744 } else {
8745 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8746 // bits, just truncate to i32.
8747 if (NumSignBits > OpBits-MidBits)
8748 return new TruncInst(Op, CI.getType(), "tmp");
8749 }
8750 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008751
8752 // If the input is a shl/ashr pair of a same constant, then this is a sign
8753 // extension from a smaller value. If we could trust arbitrary bitwidth
8754 // integers, we could turn this into a truncate to the smaller bit and then
8755 // use a sext for the whole extension. Since we don't, look deeper and check
8756 // for a truncate. If the source and dest are the same type, eliminate the
8757 // trunc and extend and just do shifts. For example, turn:
8758 // %a = trunc i32 %i to i8
8759 // %b = shl i8 %a, 6
8760 // %c = ashr i8 %b, 6
8761 // %d = sext i8 %c to i32
8762 // into:
8763 // %a = shl i32 %i, 30
8764 // %d = ashr i32 %a, 30
8765 Value *A = 0;
8766 ConstantInt *BA = 0, *CA = 0;
8767 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008768 m_ConstantInt(CA)), *Context) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008769 BA == CA && isa<TruncInst>(A)) {
8770 Value *I = cast<TruncInst>(A)->getOperand(0);
8771 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008772 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8773 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008774 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersond672ecb2009-07-03 00:17:18 +00008775 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008776 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8777 CI.getName()), CI);
8778 return BinaryOperator::CreateAShr(I, ShAmtV);
8779 }
8780 }
8781
Chris Lattnerba417832007-04-11 06:12:58 +00008782 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008783}
8784
Chris Lattnerb7530652008-01-27 05:29:54 +00008785/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8786/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008787static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008788 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008789 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008790 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008791 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8792 if (!losesInfo)
Owen Andersond672ecb2009-07-03 00:17:18 +00008793 return Context->getConstantFP(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008794 return 0;
8795}
8796
8797/// LookThroughFPExtensions - If this is an fp extension instruction, look
8798/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008799static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008800 if (Instruction *I = dyn_cast<Instruction>(V))
8801 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008802 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008803
8804 // If this value is a constant, return the constant in the smallest FP type
8805 // that can accurately represent it. This allows us to turn
8806 // (float)((double)X+2.0) into x+2.0f.
8807 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8808 if (CFP->getType() == Type::PPC_FP128Ty)
8809 return V; // No constant folding of this.
8810 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008811 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008812 return V;
8813 if (CFP->getType() == Type::DoubleTy)
8814 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008815 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008816 return V;
8817 // Don't try to shrink to various long double types.
8818 }
8819
8820 return V;
8821}
8822
8823Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8824 if (Instruction *I = commonCastTransforms(CI))
8825 return I;
8826
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008827 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008828 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008829 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008830 // many builtins (sqrt, etc).
8831 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8832 if (OpI && OpI->hasOneUse()) {
8833 switch (OpI->getOpcode()) {
8834 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008835 case Instruction::FAdd:
8836 case Instruction::FSub:
8837 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008838 case Instruction::FDiv:
8839 case Instruction::FRem:
8840 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008841 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8842 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008843 if (LHSTrunc->getType() != SrcTy &&
8844 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008845 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008846 // If the source types were both smaller than the destination type of
8847 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008848 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8849 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008850 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8851 CI.getType(), CI);
8852 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8853 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008854 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008855 }
8856 }
8857 break;
8858 }
8859 }
8860 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008861}
8862
8863Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8864 return commonCastTransforms(CI);
8865}
8866
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008867Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008868 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8869 if (OpI == 0)
8870 return commonCastTransforms(FI);
8871
8872 // fptoui(uitofp(X)) --> X
8873 // fptoui(sitofp(X)) --> X
8874 // This is safe if the intermediate type has enough bits in its mantissa to
8875 // accurately represent all values of X. For example, do not do this with
8876 // i64->float->i64. This is also safe for sitofp case, because any negative
8877 // 'X' value would cause an undefined result for the fptoui.
8878 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8879 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008880 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008881 OpI->getType()->getFPMantissaWidth())
8882 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008883
8884 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008885}
8886
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008887Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008888 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8889 if (OpI == 0)
8890 return commonCastTransforms(FI);
8891
8892 // fptosi(sitofp(X)) --> X
8893 // fptosi(uitofp(X)) --> X
8894 // This is safe if the intermediate type has enough bits in its mantissa to
8895 // accurately represent all values of X. For example, do not do this with
8896 // i64->float->i64. This is also safe for sitofp case, because any negative
8897 // 'X' value would cause an undefined result for the fptoui.
8898 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8899 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008900 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008901 OpI->getType()->getFPMantissaWidth())
8902 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008903
8904 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008905}
8906
8907Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8908 return commonCastTransforms(CI);
8909}
8910
8911Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8912 return commonCastTransforms(CI);
8913}
8914
Chris Lattnera0e69692009-03-24 18:35:40 +00008915Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8916 // If the destination integer type is smaller than the intptr_t type for
8917 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8918 // trunc to be exposed to other transforms. Don't do this for extending
8919 // ptrtoint's, because we don't know if the target sign or zero extends its
8920 // pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008921 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008922 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8923 TD->getIntPtrType(),
8924 "tmp"), CI);
8925 return new TruncInst(P, CI.getType());
8926 }
8927
Chris Lattnerd3e28342007-04-27 17:44:50 +00008928 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008929}
8930
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008931Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008932 // If the source integer type is larger than the intptr_t type for
8933 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8934 // allows the trunc to be exposed to other transforms. Don't do this for
8935 // extending inttoptr's, because we don't know if the target sign or zero
8936 // extends to pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008937 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008938 TD->getPointerSizeInBits()) {
8939 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8940 TD->getIntPtrType(),
8941 "tmp"), CI);
8942 return new IntToPtrInst(P, CI.getType());
8943 }
8944
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008945 if (Instruction *I = commonCastTransforms(CI))
8946 return I;
8947
8948 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8949 if (!DestPointee->isSized()) return 0;
8950
8951 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8952 ConstantInt *Cst;
8953 Value *X;
8954 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008955 m_ConstantInt(Cst)), *Context)) {
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008956 // If the source and destination operands have the same type, see if this
8957 // is a single-index GEP.
8958 if (X->getType() == CI.getType()) {
8959 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008960 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008961
8962 // Convert the constant to intptr type.
8963 APInt Offset = Cst->getValue();
8964 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8965
8966 // If Offset is evenly divisible by Size, we can do this xform.
8967 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8968 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Owen Andersond672ecb2009-07-03 00:17:18 +00008969 return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008970 }
8971 }
8972 // TODO: Could handle other cases, e.g. where add is indexing into field of
8973 // struct etc.
8974 } else if (CI.getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008975 match(CI.getOperand(0), m_Add(m_Value(X),
8976 m_ConstantInt(Cst)), *Context)) {
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008977 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8978 // "inttoptr+GEP" instead of "add+intptr".
8979
8980 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008981 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008982
8983 // Convert the constant to intptr type.
8984 APInt Offset = Cst->getValue();
8985 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8986
8987 // If Offset is evenly divisible by Size, we can do this xform.
8988 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8989 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8990
8991 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8992 "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008993 return GetElementPtrInst::Create(P,
8994 Context->getConstantInt(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008995 }
8996 }
8997 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008998}
8999
Chris Lattnerd3e28342007-04-27 17:44:50 +00009000Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009001 // If the operands are integer typed then apply the integer transforms,
9002 // otherwise just apply the common ones.
9003 Value *Src = CI.getOperand(0);
9004 const Type *SrcTy = Src->getType();
9005 const Type *DestTy = CI.getType();
9006
Chris Lattner42a75512007-01-15 02:27:26 +00009007 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009008 if (Instruction *Result = commonIntCastTransforms(CI))
9009 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00009010 } else if (isa<PointerType>(SrcTy)) {
9011 if (Instruction *I = commonPointerCastTransforms(CI))
9012 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00009013 } else {
9014 if (Instruction *Result = commonCastTransforms(CI))
9015 return Result;
9016 }
9017
9018
9019 // Get rid of casts from one type to the same type. These are useless and can
9020 // be replaced by the operand.
9021 if (DestTy == Src->getType())
9022 return ReplaceInstUsesWith(CI, Src);
9023
Reid Spencer3da59db2006-11-27 01:05:10 +00009024 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009025 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9026 const Type *DstElTy = DstPTy->getElementType();
9027 const Type *SrcElTy = SrcPTy->getElementType();
9028
Nate Begeman83ad90a2008-03-31 00:22:16 +00009029 // If the address spaces don't match, don't eliminate the bitcast, which is
9030 // required for changing types.
9031 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9032 return 0;
9033
Chris Lattnerd3e28342007-04-27 17:44:50 +00009034 // If we are casting a malloc or alloca to a pointer to a type of the same
9035 // size, rewrite the allocation instruction to allocate the "right" type.
9036 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9037 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9038 return V;
9039
Chris Lattnerd717c182007-05-05 22:32:24 +00009040 // If the source and destination are pointers, and this cast is equivalent
9041 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009042 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersond672ecb2009-07-03 00:17:18 +00009043 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00009044 unsigned NumZeros = 0;
9045 while (SrcElTy != DstElTy &&
9046 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9047 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9048 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9049 ++NumZeros;
9050 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009051
Chris Lattnerd3e28342007-04-27 17:44:50 +00009052 // If we found a path from the src to dest, create the getelementptr now.
9053 if (SrcElTy == DstElTy) {
9054 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00009055 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
9056 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009057 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009058 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009059
Reid Spencer3da59db2006-11-27 01:05:10 +00009060 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9061 if (SVI->hasOneUse()) {
9062 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9063 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009064 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009065 cast<VectorType>(DestTy)->getNumElements() ==
9066 SVI->getType()->getNumElements() &&
9067 SVI->getType()->getNumElements() ==
9068 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009069 CastInst *Tmp;
9070 // If either of the operands is a cast from CI.getType(), then
9071 // evaluating the shuffle in the casted destination's type will allow
9072 // us to eliminate at least one cast.
9073 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9074 Tmp->getOperand(0)->getType() == DestTy) ||
9075 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9076 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009077 Value *LHS = InsertCastBefore(Instruction::BitCast,
9078 SVI->getOperand(0), DestTy, CI);
9079 Value *RHS = InsertCastBefore(Instruction::BitCast,
9080 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009081 // Return a new shuffle vector. Use the same element ID's, as we
9082 // know the vector types match #elts.
9083 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009084 }
9085 }
9086 }
9087 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009088 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009089}
9090
Chris Lattnere576b912004-04-09 23:46:01 +00009091/// GetSelectFoldableOperands - We want to turn code that looks like this:
9092/// %C = or %A, %B
9093/// %D = select %cond, %C, %A
9094/// into:
9095/// %C = select %cond, %B, 0
9096/// %D = or %A, %C
9097///
9098/// Assuming that the specified instruction is an operand to the select, return
9099/// a bitmask indicating which operands of this instruction are foldable if they
9100/// equal the other incoming value of the select.
9101///
9102static unsigned GetSelectFoldableOperands(Instruction *I) {
9103 switch (I->getOpcode()) {
9104 case Instruction::Add:
9105 case Instruction::Mul:
9106 case Instruction::And:
9107 case Instruction::Or:
9108 case Instruction::Xor:
9109 return 3; // Can fold through either operand.
9110 case Instruction::Sub: // Can only fold on the amount subtracted.
9111 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009112 case Instruction::LShr:
9113 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009114 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009115 default:
9116 return 0; // Cannot fold
9117 }
9118}
9119
9120/// GetSelectFoldableConstant - For the same transformation as the previous
9121/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009122static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009123 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009124 switch (I->getOpcode()) {
Torok Edwin7d696d82009-07-11 13:10:19 +00009125 default: LLVM_UNREACHABLE("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009126 case Instruction::Add:
9127 case Instruction::Sub:
9128 case Instruction::Or:
9129 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009130 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009131 case Instruction::LShr:
9132 case Instruction::AShr:
Owen Andersond672ecb2009-07-03 00:17:18 +00009133 return Context->getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009134 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00009135 return Context->getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009136 case Instruction::Mul:
Owen Andersond672ecb2009-07-03 00:17:18 +00009137 return Context->getConstantInt(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009138 }
9139}
9140
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009141/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9142/// have the same opcode and only one use each. Try to simplify this.
9143Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9144 Instruction *FI) {
9145 if (TI->getNumOperands() == 1) {
9146 // If this is a non-volatile load or a cast from the same type,
9147 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009148 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009149 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9150 return 0;
9151 } else {
9152 return 0; // unknown unary op.
9153 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009154
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009155 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009156 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9157 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009158 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009159 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009160 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009161 }
9162
Reid Spencer832254e2007-02-02 02:16:23 +00009163 // Only handle binary operators here.
9164 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009165 return 0;
9166
9167 // Figure out if the operations have any operands in common.
9168 Value *MatchOp, *OtherOpT, *OtherOpF;
9169 bool MatchIsOpZero;
9170 if (TI->getOperand(0) == FI->getOperand(0)) {
9171 MatchOp = TI->getOperand(0);
9172 OtherOpT = TI->getOperand(1);
9173 OtherOpF = FI->getOperand(1);
9174 MatchIsOpZero = true;
9175 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9176 MatchOp = TI->getOperand(1);
9177 OtherOpT = TI->getOperand(0);
9178 OtherOpF = FI->getOperand(0);
9179 MatchIsOpZero = false;
9180 } else if (!TI->isCommutative()) {
9181 return 0;
9182 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9183 MatchOp = TI->getOperand(0);
9184 OtherOpT = TI->getOperand(1);
9185 OtherOpF = FI->getOperand(0);
9186 MatchIsOpZero = true;
9187 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9188 MatchOp = TI->getOperand(1);
9189 OtherOpT = TI->getOperand(0);
9190 OtherOpF = FI->getOperand(1);
9191 MatchIsOpZero = true;
9192 } else {
9193 return 0;
9194 }
9195
9196 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009197 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9198 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009199 InsertNewInstBefore(NewSI, SI);
9200
9201 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9202 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009203 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009204 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009205 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009206 }
Torok Edwinc25e7582009-07-11 20:10:48 +00009207 LLVM_UNREACHABLE("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009208 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009209}
9210
Evan Chengde621922009-03-31 20:42:45 +00009211static bool isSelect01(Constant *C1, Constant *C2) {
9212 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9213 if (!C1I)
9214 return false;
9215 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9216 if (!C2I)
9217 return false;
9218 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9219}
9220
9221/// FoldSelectIntoOp - Try fold the select into one of the operands to
9222/// facilitate further optimization.
9223Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9224 Value *FalseVal) {
9225 // See the comment above GetSelectFoldableOperands for a description of the
9226 // transformation we are doing here.
9227 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9228 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9229 !isa<Constant>(FalseVal)) {
9230 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9231 unsigned OpToFold = 0;
9232 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9233 OpToFold = 1;
9234 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9235 OpToFold = 2;
9236 }
9237
9238 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009239 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009240 Value *OOp = TVI->getOperand(2-OpToFold);
9241 // Avoid creating select between 2 constants unless it's selecting
9242 // between 0 and 1.
9243 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9244 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9245 InsertNewInstBefore(NewSel, SI);
9246 NewSel->takeName(TVI);
9247 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9248 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc25e7582009-07-11 20:10:48 +00009249 LLVM_UNREACHABLE("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009250 }
9251 }
9252 }
9253 }
9254 }
9255
9256 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9257 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9258 !isa<Constant>(TrueVal)) {
9259 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9260 unsigned OpToFold = 0;
9261 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9262 OpToFold = 1;
9263 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9264 OpToFold = 2;
9265 }
9266
9267 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009268 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009269 Value *OOp = FVI->getOperand(2-OpToFold);
9270 // Avoid creating select between 2 constants unless it's selecting
9271 // between 0 and 1.
9272 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9273 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9274 InsertNewInstBefore(NewSel, SI);
9275 NewSel->takeName(FVI);
9276 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9277 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc25e7582009-07-11 20:10:48 +00009278 LLVM_UNREACHABLE("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009279 }
9280 }
9281 }
9282 }
9283 }
9284
9285 return 0;
9286}
9287
Dan Gohman81b28ce2008-09-16 18:46:06 +00009288/// visitSelectInstWithICmp - Visit a SelectInst that has an
9289/// ICmpInst as its first operand.
9290///
9291Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9292 ICmpInst *ICI) {
9293 bool Changed = false;
9294 ICmpInst::Predicate Pred = ICI->getPredicate();
9295 Value *CmpLHS = ICI->getOperand(0);
9296 Value *CmpRHS = ICI->getOperand(1);
9297 Value *TrueVal = SI.getTrueValue();
9298 Value *FalseVal = SI.getFalseValue();
9299
9300 // Check cases where the comparison is with a constant that
9301 // can be adjusted to fit the min/max idiom. We may edit ICI in
9302 // place here, so make sure the select is the only user.
9303 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009304 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009305 switch (Pred) {
9306 default: break;
9307 case ICmpInst::ICMP_ULT:
9308 case ICmpInst::ICMP_SLT: {
9309 // X < MIN ? T : F --> F
9310 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9311 return ReplaceInstUsesWith(SI, FalseVal);
9312 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009313 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009314 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9315 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9316 Pred = ICmpInst::getSwappedPredicate(Pred);
9317 CmpRHS = AdjustedRHS;
9318 std::swap(FalseVal, TrueVal);
9319 ICI->setPredicate(Pred);
9320 ICI->setOperand(1, CmpRHS);
9321 SI.setOperand(1, TrueVal);
9322 SI.setOperand(2, FalseVal);
9323 Changed = true;
9324 }
9325 break;
9326 }
9327 case ICmpInst::ICMP_UGT:
9328 case ICmpInst::ICMP_SGT: {
9329 // X > MAX ? T : F --> F
9330 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9331 return ReplaceInstUsesWith(SI, FalseVal);
9332 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009333 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009334 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9335 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9336 Pred = ICmpInst::getSwappedPredicate(Pred);
9337 CmpRHS = AdjustedRHS;
9338 std::swap(FalseVal, TrueVal);
9339 ICI->setPredicate(Pred);
9340 ICI->setOperand(1, CmpRHS);
9341 SI.setOperand(1, TrueVal);
9342 SI.setOperand(2, FalseVal);
9343 Changed = true;
9344 }
9345 break;
9346 }
9347 }
9348
Dan Gohman1975d032008-10-30 20:40:10 +00009349 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9350 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009351 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009352 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9353 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009354 Pred = ICI->getPredicate();
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009355 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9356 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009357 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9358
Dan Gohman1975d032008-10-30 20:40:10 +00009359 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9360 // If we are just checking for a icmp eq of a single bit and zext'ing it
9361 // to an integer, then shift the bit to the appropriate place and then
9362 // cast to integer to avoid the comparison.
9363 const APInt &Op1CV = CI->getValue();
9364
9365 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9366 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9367 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009368 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009369 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00009370 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009371 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009372 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9373 In->getName()+".lobit"),
9374 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009375 if (In->getType() != SI.getType())
9376 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009377 true/*SExt*/, "tmp", ICI);
9378
9379 if (Pred == ICmpInst::ICMP_SGT)
9380 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9381 In->getName()+".not"), *ICI);
9382
9383 return ReplaceInstUsesWith(SI, In);
9384 }
9385 }
9386 }
9387
Dan Gohman81b28ce2008-09-16 18:46:06 +00009388 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9389 // Transform (X == Y) ? X : Y -> Y
9390 if (Pred == ICmpInst::ICMP_EQ)
9391 return ReplaceInstUsesWith(SI, FalseVal);
9392 // Transform (X != Y) ? X : Y -> X
9393 if (Pred == ICmpInst::ICMP_NE)
9394 return ReplaceInstUsesWith(SI, TrueVal);
9395 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9396
9397 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9398 // Transform (X == Y) ? Y : X -> X
9399 if (Pred == ICmpInst::ICMP_EQ)
9400 return ReplaceInstUsesWith(SI, FalseVal);
9401 // Transform (X != Y) ? Y : X -> Y
9402 if (Pred == ICmpInst::ICMP_NE)
9403 return ReplaceInstUsesWith(SI, TrueVal);
9404 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9405 }
9406
9407 /// NOTE: if we wanted to, this is where to detect integer ABS
9408
9409 return Changed ? &SI : 0;
9410}
9411
Chris Lattner3d69f462004-03-12 05:52:32 +00009412Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009413 Value *CondVal = SI.getCondition();
9414 Value *TrueVal = SI.getTrueValue();
9415 Value *FalseVal = SI.getFalseValue();
9416
9417 // select true, X, Y -> X
9418 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009419 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009420 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009421
9422 // select C, X, X -> X
9423 if (TrueVal == FalseVal)
9424 return ReplaceInstUsesWith(SI, TrueVal);
9425
Chris Lattnere87597f2004-10-16 18:11:37 +00009426 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9427 return ReplaceInstUsesWith(SI, FalseVal);
9428 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9429 return ReplaceInstUsesWith(SI, TrueVal);
9430 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9431 if (isa<Constant>(TrueVal))
9432 return ReplaceInstUsesWith(SI, TrueVal);
9433 else
9434 return ReplaceInstUsesWith(SI, FalseVal);
9435 }
9436
Reid Spencer4fe16d62007-01-11 18:21:29 +00009437 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009438 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009439 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009440 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009441 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009442 } else {
9443 // Change: A = select B, false, C --> A = and !B, C
9444 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009445 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009446 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009447 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009448 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009449 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009450 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009451 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009452 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009453 } else {
9454 // Change: A = select B, C, true --> A = or !B, C
9455 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009456 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009457 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009458 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009459 }
9460 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009461
9462 // select a, b, a -> a&b
9463 // select a, a, b -> a|b
9464 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009465 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009466 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009467 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009468 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009469
Chris Lattner2eefe512004-04-09 19:05:30 +00009470 // Selecting between two integer constants?
9471 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9472 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009473 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009474 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009475 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009476 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009477 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009478 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009479 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009480 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009481 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009482 }
Chris Lattner457dd822004-06-09 07:59:58 +00009483
Reid Spencere4d87aa2006-12-23 06:05:41 +00009484 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009485 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009486 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009487 // non-constant value, eliminate this whole mess. This corresponds to
9488 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009489 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009490 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009491 cast<Constant>(IC->getOperand(1))->isNullValue())
9492 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9493 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009494 isa<ConstantInt>(ICA->getOperand(1)) &&
9495 (ICA->getOperand(1) == TrueValC ||
9496 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009497 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9498 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009499 // know whether we have a icmp_ne or icmp_eq and whether the
9500 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009501 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009502 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009503 Value *V = ICA;
9504 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009505 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009506 Instruction::Xor, V, ICA->getOperand(1)), SI);
9507 return ReplaceInstUsesWith(SI, V);
9508 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009509 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009510 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009511
9512 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009513 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9514 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009515 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009516 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9517 // This is not safe in general for floating point:
9518 // consider X== -0, Y== +0.
9519 // It becomes safe if either operand is a nonzero constant.
9520 ConstantFP *CFPt, *CFPf;
9521 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9522 !CFPt->getValueAPF().isZero()) ||
9523 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9524 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009525 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009526 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009527 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009528 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009529 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009530 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009531
Reid Spencere4d87aa2006-12-23 06:05:41 +00009532 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009533 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009534 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9535 // This is not safe in general for floating point:
9536 // consider X== -0, Y== +0.
9537 // It becomes safe if either operand is a nonzero constant.
9538 ConstantFP *CFPt, *CFPf;
9539 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9540 !CFPt->getValueAPF().isZero()) ||
9541 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9542 !CFPf->getValueAPF().isZero()))
9543 return ReplaceInstUsesWith(SI, FalseVal);
9544 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009545 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009546 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9547 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009548 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009549 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009550 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009551 }
9552
9553 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009554 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9555 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9556 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009557
Chris Lattner87875da2005-01-13 22:52:24 +00009558 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9559 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9560 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009561 Instruction *AddOp = 0, *SubOp = 0;
9562
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009563 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9564 if (TI->getOpcode() == FI->getOpcode())
9565 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9566 return IV;
9567
9568 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9569 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009570 if ((TI->getOpcode() == Instruction::Sub &&
9571 FI->getOpcode() == Instruction::Add) ||
9572 (TI->getOpcode() == Instruction::FSub &&
9573 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009574 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009575 } else if ((FI->getOpcode() == Instruction::Sub &&
9576 TI->getOpcode() == Instruction::Add) ||
9577 (FI->getOpcode() == Instruction::FSub &&
9578 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009579 AddOp = TI; SubOp = FI;
9580 }
9581
9582 if (AddOp) {
9583 Value *OtherAddOp = 0;
9584 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9585 OtherAddOp = AddOp->getOperand(1);
9586 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9587 OtherAddOp = AddOp->getOperand(0);
9588 }
9589
9590 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009591 // So at this point we know we have (Y -> OtherAddOp):
9592 // select C, (add X, Y), (sub X, Z)
9593 Value *NegVal; // Compute -Z
9594 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009595 NegVal = Context->getConstantExprNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009596 } else {
9597 NegVal = InsertNewInstBefore(
Owen Anderson0a5372e2009-07-13 04:09:18 +00009598 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9599 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009600 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009601
9602 Value *NewTrueOp = OtherAddOp;
9603 Value *NewFalseOp = NegVal;
9604 if (AddOp != TI)
9605 std::swap(NewTrueOp, NewFalseOp);
9606 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009607 SelectInst::Create(CondVal, NewTrueOp,
9608 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009609
9610 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009611 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009612 }
9613 }
9614 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009615
Chris Lattnere576b912004-04-09 23:46:01 +00009616 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009617 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009618 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9619 if (FoldI)
9620 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009621 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009622
9623 if (BinaryOperator::isNot(CondVal)) {
9624 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9625 SI.setOperand(1, FalseVal);
9626 SI.setOperand(2, TrueVal);
9627 return &SI;
9628 }
9629
Chris Lattner3d69f462004-03-12 05:52:32 +00009630 return 0;
9631}
9632
Dan Gohmaneee962e2008-04-10 18:43:06 +00009633/// EnforceKnownAlignment - If the specified pointer points to an object that
9634/// we control, modify the object's alignment to PrefAlign. This isn't
9635/// often possible though. If alignment is important, a more reliable approach
9636/// is to simply align all global variables and allocation instructions to
9637/// their preferred alignment from the beginning.
9638///
9639static unsigned EnforceKnownAlignment(Value *V,
9640 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009641
Dan Gohmaneee962e2008-04-10 18:43:06 +00009642 User *U = dyn_cast<User>(V);
9643 if (!U) return Align;
9644
9645 switch (getOpcode(U)) {
9646 default: break;
9647 case Instruction::BitCast:
9648 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9649 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009650 // If all indexes are zero, it is just the alignment of the base pointer.
9651 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009652 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009653 if (!isa<Constant>(*i) ||
9654 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009655 AllZeroOperands = false;
9656 break;
9657 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009658
9659 if (AllZeroOperands) {
9660 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009661 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009662 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009663 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009664 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009665 }
9666
9667 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9668 // If there is a large requested alignment and we can, bump up the alignment
9669 // of the global.
9670 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009671 if (GV->getAlignment() >= PrefAlign)
9672 Align = GV->getAlignment();
9673 else {
9674 GV->setAlignment(PrefAlign);
9675 Align = PrefAlign;
9676 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009677 }
9678 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9679 // If there is a requested alignment and if this is an alloca, round up. We
9680 // don't do this for malloc, because some systems can't respect the request.
9681 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009682 if (AI->getAlignment() >= PrefAlign)
9683 Align = AI->getAlignment();
9684 else {
9685 AI->setAlignment(PrefAlign);
9686 Align = PrefAlign;
9687 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009688 }
9689 }
9690
9691 return Align;
9692}
9693
9694/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9695/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9696/// and it is more than the alignment of the ultimate object, see if we can
9697/// increase the alignment of the ultimate object, making this check succeed.
9698unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9699 unsigned PrefAlign) {
9700 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9701 sizeof(PrefAlign) * CHAR_BIT;
9702 APInt Mask = APInt::getAllOnesValue(BitWidth);
9703 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9704 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9705 unsigned TrailZ = KnownZero.countTrailingOnes();
9706 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9707
9708 if (PrefAlign > Align)
9709 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9710
9711 // We don't need to make any adjustment.
9712 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009713}
9714
Chris Lattnerf497b022008-01-13 23:50:23 +00009715Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009716 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009717 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009718 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009719 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009720
9721 if (CopyAlign < MinAlign) {
Owen Andersona547b472009-07-09 18:36:20 +00009722 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9723 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009724 return MI;
9725 }
9726
9727 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9728 // load/store.
9729 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9730 if (MemOpLength == 0) return 0;
9731
Chris Lattner37ac6082008-01-14 00:28:35 +00009732 // Source and destination pointer types are always "i8*" for intrinsic. See
9733 // if the size is something we can handle with a single primitive load/store.
9734 // A single load+store correctly handles overlapping memory in the memmove
9735 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009736 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009737 if (Size == 0) return MI; // Delete this mem transfer.
9738
9739 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009740 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009741
Chris Lattner37ac6082008-01-14 00:28:35 +00009742 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009743 Type *NewPtrTy =
9744 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009745
9746 // Memcpy forces the use of i8* for the source and destination. That means
9747 // that if you're using memcpy to move one double around, you'll get a cast
9748 // from double* to i8*. We'd much rather use a double load+store rather than
9749 // an i64 load+store, here because this improves the odds that the source or
9750 // dest address will be promotable. See if we can find a better type than the
9751 // integer datatype.
9752 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9753 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9754 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9755 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9756 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009757 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009758 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9759 if (STy->getNumElements() == 1)
9760 SrcETy = STy->getElementType(0);
9761 else
9762 break;
9763 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9764 if (ATy->getNumElements() == 1)
9765 SrcETy = ATy->getElementType();
9766 else
9767 break;
9768 } else
9769 break;
9770 }
9771
Dan Gohman8f8e2692008-05-23 01:52:21 +00009772 if (SrcETy->isSingleValueType())
Owen Andersond672ecb2009-07-03 00:17:18 +00009773 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009774 }
9775 }
9776
9777
Chris Lattnerf497b022008-01-13 23:50:23 +00009778 // If the memcpy/memmove provides better alignment info than we can
9779 // infer, use it.
9780 SrcAlign = std::max(SrcAlign, CopyAlign);
9781 DstAlign = std::max(DstAlign, CopyAlign);
9782
9783 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9784 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009785 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9786 InsertNewInstBefore(L, *MI);
9787 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9788
9789 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009790 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009791 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009792}
Chris Lattner3d69f462004-03-12 05:52:32 +00009793
Chris Lattner69ea9d22008-04-30 06:39:11 +00009794Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9795 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009796 if (MI->getAlignment() < Alignment) {
Owen Andersona547b472009-07-09 18:36:20 +00009797 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9798 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009799 return MI;
9800 }
9801
9802 // Extract the length and alignment and fill if they are constant.
9803 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9804 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9805 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9806 return 0;
9807 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009808 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009809
9810 // If the length is zero, this is a no-op
9811 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9812
9813 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9814 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009815 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009816
9817 Value *Dest = MI->getDest();
Owen Andersond672ecb2009-07-03 00:17:18 +00009818 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009819
9820 // Alignment 0 is identity for alignment 1 for memset, but not store.
9821 if (Alignment == 0) Alignment = 1;
9822
9823 // Extract the fill value and store.
9824 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersond672ecb2009-07-03 00:17:18 +00009825 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9826 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009827
9828 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009829 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009830 return MI;
9831 }
9832
9833 return 0;
9834}
9835
9836
Chris Lattner8b0ea312006-01-13 20:11:04 +00009837/// visitCallInst - CallInst simplification. This mostly only handles folding
9838/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9839/// the heavy lifting.
9840///
Chris Lattner9fe38862003-06-19 17:00:31 +00009841Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009842 // If the caller function is nounwind, mark the call as nounwind, even if the
9843 // callee isn't.
9844 if (CI.getParent()->getParent()->doesNotThrow() &&
9845 !CI.doesNotThrow()) {
9846 CI.setDoesNotThrow();
9847 return &CI;
9848 }
9849
9850
9851
Chris Lattner8b0ea312006-01-13 20:11:04 +00009852 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9853 if (!II) return visitCallSite(&CI);
9854
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009855 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9856 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009857 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009858 bool Changed = false;
9859
9860 // memmove/cpy/set of zero bytes is a noop.
9861 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9862 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9863
Chris Lattner35b9e482004-10-12 04:52:52 +00009864 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009865 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009866 // Replace the instruction with just byte operations. We would
9867 // transform other cases to loads/stores, but we don't know if
9868 // alignment is sufficient.
9869 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009870 }
9871
Chris Lattner35b9e482004-10-12 04:52:52 +00009872 // If we have a memmove and the source operation is a constant global,
9873 // then the source and dest pointers can't alias, so we can change this
9874 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009875 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009876 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9877 if (GVSrc->isConstant()) {
9878 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009879 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9880 const Type *Tys[1];
9881 Tys[0] = CI.getOperand(3)->getType();
9882 CI.setOperand(0,
9883 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009884 Changed = true;
9885 }
Chris Lattnera935db82008-05-28 05:30:41 +00009886
9887 // memmove(x,x,size) -> noop.
9888 if (MMI->getSource() == MMI->getDest())
9889 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009890 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009891
Chris Lattner95a959d2006-03-06 20:18:44 +00009892 // If we can determine a pointer alignment that is bigger than currently
9893 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009894 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009895 if (Instruction *I = SimplifyMemTransfer(MI))
9896 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009897 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9898 if (Instruction *I = SimplifyMemSet(MSI))
9899 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009900 }
9901
Chris Lattner8b0ea312006-01-13 20:11:04 +00009902 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009903 }
9904
9905 switch (II->getIntrinsicID()) {
9906 default: break;
9907 case Intrinsic::bswap:
9908 // bswap(bswap(x)) -> x
9909 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9910 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9911 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9912 break;
9913 case Intrinsic::ppc_altivec_lvx:
9914 case Intrinsic::ppc_altivec_lvxl:
9915 case Intrinsic::x86_sse_loadu_ps:
9916 case Intrinsic::x86_sse2_loadu_pd:
9917 case Intrinsic::x86_sse2_loadu_dq:
9918 // Turn PPC lvx -> load if the pointer is known aligned.
9919 // Turn X86 loadups -> load if the pointer is known aligned.
9920 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9921 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00009922 Context->getPointerTypeUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009923 CI);
9924 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009925 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009926 break;
9927 case Intrinsic::ppc_altivec_stvx:
9928 case Intrinsic::ppc_altivec_stvxl:
9929 // Turn stvx -> store if the pointer is known aligned.
9930 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9931 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009932 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009933 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9934 return new StoreInst(II->getOperand(1), Ptr);
9935 }
9936 break;
9937 case Intrinsic::x86_sse_storeu_ps:
9938 case Intrinsic::x86_sse2_storeu_pd:
9939 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009940 // Turn X86 storeu -> store if the pointer is known aligned.
9941 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9942 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009943 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009944 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9945 return new StoreInst(II->getOperand(2), Ptr);
9946 }
9947 break;
9948
9949 case Intrinsic::x86_sse_cvttss2si: {
9950 // These intrinsics only demands the 0th element of its input vector. If
9951 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009952 unsigned VWidth =
9953 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9954 APInt DemandedElts(VWidth, 1);
9955 APInt UndefElts(VWidth, 0);
9956 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009957 UndefElts)) {
9958 II->setOperand(1, V);
9959 return II;
9960 }
9961 break;
9962 }
9963
9964 case Intrinsic::ppc_altivec_vperm:
9965 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9966 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9967 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009968
Chris Lattner0521e3c2008-06-18 04:33:20 +00009969 // Check that all of the elements are integer constants or undefs.
9970 bool AllEltsOk = true;
9971 for (unsigned i = 0; i != 16; ++i) {
9972 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9973 !isa<UndefValue>(Mask->getOperand(i))) {
9974 AllEltsOk = false;
9975 break;
9976 }
9977 }
9978
9979 if (AllEltsOk) {
9980 // Cast the input vectors to byte vectors.
9981 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9982 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00009983 Value *Result = Context->getUndef(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009984
Chris Lattner0521e3c2008-06-18 04:33:20 +00009985 // Only extract each element once.
9986 Value *ExtractedElts[32];
9987 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9988
Chris Lattnere2ed0572006-04-06 19:19:17 +00009989 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009990 if (isa<UndefValue>(Mask->getOperand(i)))
9991 continue;
9992 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9993 Idx &= 31; // Match the hardware behavior.
9994
9995 if (ExtractedElts[Idx] == 0) {
9996 Instruction *Elt =
9997 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9998 InsertNewInstBefore(Elt, CI);
9999 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010000 }
Chris Lattnere2ed0572006-04-06 19:19:17 +000010001
Chris Lattner0521e3c2008-06-18 04:33:20 +000010002 // Insert this value into the result vector.
10003 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
10004 i, "tmp");
10005 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +000010006 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010007 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010008 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010009 }
10010 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010011
Chris Lattner0521e3c2008-06-18 04:33:20 +000010012 case Intrinsic::stackrestore: {
10013 // If the save is right next to the restore, remove the restore. This can
10014 // happen when variable allocas are DCE'd.
10015 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10016 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10017 BasicBlock::iterator BI = SS;
10018 if (&*++BI == II)
10019 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010020 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010021 }
10022
10023 // Scan down this block to see if there is another stack restore in the
10024 // same block without an intervening call/alloca.
10025 BasicBlock::iterator BI = II;
10026 TerminatorInst *TI = II->getParent()->getTerminator();
10027 bool CannotRemove = false;
10028 for (++BI; &*BI != TI; ++BI) {
10029 if (isa<AllocaInst>(BI)) {
10030 CannotRemove = true;
10031 break;
10032 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010033 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10034 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10035 // If there is a stackrestore below this one, remove this one.
10036 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10037 return EraseInstFromFunction(CI);
10038 // Otherwise, ignore the intrinsic.
10039 } else {
10040 // If we found a non-intrinsic call, we can't remove the stack
10041 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010042 CannotRemove = true;
10043 break;
10044 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010045 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010046 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010047
10048 // If the stack restore is in a return/unwind block and if there are no
10049 // allocas or calls between the restore and the return, nuke the restore.
10050 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10051 return EraseInstFromFunction(CI);
10052 break;
10053 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010054 }
10055
Chris Lattner8b0ea312006-01-13 20:11:04 +000010056 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010057}
10058
10059// InvokeInst simplification
10060//
10061Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010062 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010063}
10064
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010065/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10066/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010067static bool isSafeToEliminateVarargsCast(const CallSite CS,
10068 const CastInst * const CI,
10069 const TargetData * const TD,
10070 const int ix) {
10071 if (!CI->isLosslessCast())
10072 return false;
10073
10074 // The size of ByVal arguments is derived from the type, so we
10075 // can't change to a type with a different size. If the size were
10076 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010077 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010078 return true;
10079
10080 const Type* SrcTy =
10081 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10082 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10083 if (!SrcTy->isSized() || !DstTy->isSized())
10084 return false;
Duncan Sands777d2302009-05-09 07:06:46 +000010085 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010086 return false;
10087 return true;
10088}
10089
Chris Lattnera44d8a22003-10-07 22:32:43 +000010090// visitCallSite - Improvements for call and invoke instructions.
10091//
10092Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010093 bool Changed = false;
10094
10095 // If the callee is a constexpr cast of a function, attempt to move the cast
10096 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010097 if (transformConstExprCastCall(CS)) return 0;
10098
Chris Lattner6c266db2003-10-07 22:54:13 +000010099 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010100
Chris Lattner08b22ec2005-05-13 07:09:09 +000010101 if (Function *CalleeF = dyn_cast<Function>(Callee))
10102 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10103 Instruction *OldCall = CS.getInstruction();
10104 // If the call and callee calling conventions don't match, this call must
10105 // be unreachable, as the call is undefined.
Owen Andersond672ecb2009-07-03 00:17:18 +000010106 new StoreInst(Context->getConstantIntTrue(),
10107 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10108 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010109 if (!OldCall->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000010110 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010111 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10112 return EraseInstFromFunction(*OldCall);
10113 return 0;
10114 }
10115
Chris Lattner17be6352004-10-18 02:59:09 +000010116 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10117 // This instruction is not reachable, just remove it. We insert a store to
10118 // undef so that we know that this code is not reachable, despite the fact
10119 // that we can't modify the CFG here.
Owen Andersond672ecb2009-07-03 00:17:18 +000010120 new StoreInst(Context->getConstantIntTrue(),
10121 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010122 CS.getInstruction());
10123
10124 if (!CS.getInstruction()->use_empty())
10125 CS.getInstruction()->
Owen Andersond672ecb2009-07-03 00:17:18 +000010126 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010127
10128 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10129 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010130 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010131 Context->getConstantIntTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010132 }
Chris Lattner17be6352004-10-18 02:59:09 +000010133 return EraseInstFromFunction(*CS.getInstruction());
10134 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010135
Duncan Sandscdb6d922007-09-17 10:26:40 +000010136 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10137 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10138 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10139 return transformCallThroughTrampoline(CS);
10140
Chris Lattner6c266db2003-10-07 22:54:13 +000010141 const PointerType *PTy = cast<PointerType>(Callee->getType());
10142 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10143 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010144 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010145 // See if we can optimize any arguments passed through the varargs area of
10146 // the call.
10147 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010148 E = CS.arg_end(); I != E; ++I, ++ix) {
10149 CastInst *CI = dyn_cast<CastInst>(*I);
10150 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10151 *I = CI->getOperand(0);
10152 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010153 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010154 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010155 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010156
Duncan Sandsf0c33542007-12-19 21:13:37 +000010157 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010158 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010159 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010160 Changed = true;
10161 }
10162
Chris Lattner6c266db2003-10-07 22:54:13 +000010163 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010164}
10165
Chris Lattner9fe38862003-06-19 17:00:31 +000010166// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10167// attempt to move the cast to the arguments of the call/invoke.
10168//
10169bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10170 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10171 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010172 if (CE->getOpcode() != Instruction::BitCast ||
10173 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010174 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010175 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010176 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010177 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010178
10179 // Okay, this is a cast from a function to a different type. Unless doing so
10180 // would cause a type conversion of one of our arguments, change this call to
10181 // be a direct call with arguments casted to the appropriate types.
10182 //
10183 const FunctionType *FT = Callee->getFunctionType();
10184 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010185 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010186
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010187 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010188 return false; // TODO: Handle multiple return values.
10189
Chris Lattnerf78616b2004-01-14 06:06:08 +000010190 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010191 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010192 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010193 // Conversion is ok if changing from one pointer type to another or from
10194 // a pointer to an integer of the same size.
10195 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +000010196 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010197 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010198
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010199 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010200 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010201 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010202 return false; // Cannot transform this return value.
10203
Chris Lattner58d74912008-03-12 17:45:29 +000010204 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010205 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010206 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010207 return false; // Attribute not compatible with transformed value.
10208 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010209
Chris Lattnerf78616b2004-01-14 06:06:08 +000010210 // If the callsite is an invoke instruction, and the return value is used by
10211 // a PHI node in a successor, we cannot change the return type of the call
10212 // because there is no place to put the cast instruction (without breaking
10213 // the critical edge). Bail out in this case.
10214 if (!Caller->use_empty())
10215 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10216 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10217 UI != E; ++UI)
10218 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10219 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010220 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010221 return false;
10222 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010223
10224 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10225 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010226
Chris Lattner9fe38862003-06-19 17:00:31 +000010227 CallSite::arg_iterator AI = CS.arg_begin();
10228 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10229 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010230 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010231
10232 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010233 return false; // Cannot transform this parameter value.
10234
Devang Patel19c87462008-09-26 22:53:05 +000010235 if (CallerPAL.getParamAttributes(i + 1)
10236 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010237 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010238
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010239 // Converting from one pointer type to another or between a pointer and an
10240 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010241 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010242 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10243 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010244 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010245 }
10246
10247 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010248 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010249 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010250
Chris Lattner58d74912008-03-12 17:45:29 +000010251 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10252 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010253 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010254 // won't be dropping them. Check that these extra arguments have attributes
10255 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010256 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10257 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010258 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010259 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010260 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010261 return false;
10262 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010263
Chris Lattner9fe38862003-06-19 17:00:31 +000010264 // Okay, we decided that this is a safe thing to do: go ahead and start
10265 // inserting cast instructions as necessary...
10266 std::vector<Value*> Args;
10267 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010268 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010269 attrVec.reserve(NumCommonArgs);
10270
10271 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010272 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010273
10274 // If the return value is not being used, the type may not be compatible
10275 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010276 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010277
10278 // Add the new return attributes.
10279 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010280 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010281
10282 AI = CS.arg_begin();
10283 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10284 const Type *ParamTy = FT->getParamType(i);
10285 if ((*AI)->getType() == ParamTy) {
10286 Args.push_back(*AI);
10287 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010288 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010289 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010290 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010291 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010292 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010293
10294 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010295 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010296 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010297 }
10298
10299 // If the function takes more arguments than the call was taking, add them
10300 // now...
10301 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000010302 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010303
10304 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010305 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010306 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010307 cerr << "WARNING: While resolving call to function '"
10308 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010309 } else {
10310 // Add all of the arguments in their promoted form to the arg list...
10311 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10312 const Type *PTy = getPromotedType((*AI)->getType());
10313 if (PTy != (*AI)->getType()) {
10314 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010315 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10316 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010317 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010318 InsertNewInstBefore(Cast, *Caller);
10319 Args.push_back(Cast);
10320 } else {
10321 Args.push_back(*AI);
10322 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010323
Duncan Sandse1e520f2008-01-13 08:02:44 +000010324 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010325 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010326 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010327 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010328 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010329 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010330
Devang Patel19c87462008-09-26 22:53:05 +000010331 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10332 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10333
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010334 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010335 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010336
Devang Patel05988662008-09-25 21:00:45 +000010337 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010338
Chris Lattner9fe38862003-06-19 17:00:31 +000010339 Instruction *NC;
10340 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010341 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010342 Args.begin(), Args.end(),
10343 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010344 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010345 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010346 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010347 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10348 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010349 CallInst *CI = cast<CallInst>(Caller);
10350 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010351 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010352 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010353 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010354 }
10355
Chris Lattner6934a042007-02-11 01:23:03 +000010356 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010357 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010358 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010359 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010360 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010361 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010362 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010363
10364 // If this is an invoke instruction, we should insert it after the first
10365 // non-phi, instruction in the normal successor block.
10366 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010367 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010368 InsertNewInstBefore(NC, *I);
10369 } else {
10370 // Otherwise, it's a call, just insert cast right after the call instr
10371 InsertNewInstBefore(NC, *Caller);
10372 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010373 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010374 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000010375 NV = Context->getUndef(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010376 }
10377 }
10378
10379 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10380 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010381 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010382 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010383 return true;
10384}
10385
Duncan Sandscdb6d922007-09-17 10:26:40 +000010386// transformCallThroughTrampoline - Turn a call to a function created by the
10387// init_trampoline intrinsic into a direct call to the underlying function.
10388//
10389Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10390 Value *Callee = CS.getCalledValue();
10391 const PointerType *PTy = cast<PointerType>(Callee->getType());
10392 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010393 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010394
10395 // If the call already has the 'nest' attribute somewhere then give up -
10396 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010397 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010398 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010399
10400 IntrinsicInst *Tramp =
10401 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10402
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010403 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010404 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10405 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10406
Devang Patel05988662008-09-25 21:00:45 +000010407 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010408 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010409 unsigned NestIdx = 1;
10410 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010411 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010412
10413 // Look for a parameter marked with the 'nest' attribute.
10414 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10415 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010416 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010417 // Record the parameter type and any other attributes.
10418 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010419 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010420 break;
10421 }
10422
10423 if (NestTy) {
10424 Instruction *Caller = CS.getInstruction();
10425 std::vector<Value*> NewArgs;
10426 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10427
Devang Patel05988662008-09-25 21:00:45 +000010428 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010429 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010430
Duncan Sandscdb6d922007-09-17 10:26:40 +000010431 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010432 // mean appending it. Likewise for attributes.
10433
Devang Patel19c87462008-09-26 22:53:05 +000010434 // Add any result attributes.
10435 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010436 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010437
Duncan Sandscdb6d922007-09-17 10:26:40 +000010438 {
10439 unsigned Idx = 1;
10440 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10441 do {
10442 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010443 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010444 Value *NestVal = Tramp->getOperand(3);
10445 if (NestVal->getType() != NestTy)
10446 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10447 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010448 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010449 }
10450
10451 if (I == E)
10452 break;
10453
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010454 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010455 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010456 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010457 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010458 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010459
10460 ++Idx, ++I;
10461 } while (1);
10462 }
10463
Devang Patel19c87462008-09-26 22:53:05 +000010464 // Add any function attributes.
10465 if (Attributes Attr = Attrs.getFnAttributes())
10466 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10467
Duncan Sandscdb6d922007-09-17 10:26:40 +000010468 // The trampoline may have been bitcast to a bogus type (FTy).
10469 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010470 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010471
Duncan Sandscdb6d922007-09-17 10:26:40 +000010472 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010473 NewTypes.reserve(FTy->getNumParams()+1);
10474
Duncan Sandscdb6d922007-09-17 10:26:40 +000010475 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010476 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010477 {
10478 unsigned Idx = 1;
10479 FunctionType::param_iterator I = FTy->param_begin(),
10480 E = FTy->param_end();
10481
10482 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010483 if (Idx == NestIdx)
10484 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010485 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010486
10487 if (I == E)
10488 break;
10489
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010490 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010491 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010492
10493 ++Idx, ++I;
10494 } while (1);
10495 }
10496
10497 // Replace the trampoline call with a direct call. Let the generic
10498 // code sort out any function type mismatches.
10499 FunctionType *NewFTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000010500 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10501 FTy->isVarArg());
10502 Constant *NewCallee =
10503 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10504 NestF : Context->getConstantExprBitCast(NestF,
10505 Context->getPointerTypeUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010506 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010507
10508 Instruction *NewCaller;
10509 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010510 NewCaller = InvokeInst::Create(NewCallee,
10511 II->getNormalDest(), II->getUnwindDest(),
10512 NewArgs.begin(), NewArgs.end(),
10513 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010514 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010515 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010516 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010517 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10518 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010519 if (cast<CallInst>(Caller)->isTailCall())
10520 cast<CallInst>(NewCaller)->setTailCall();
10521 cast<CallInst>(NewCaller)->
10522 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010523 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010524 }
10525 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10526 Caller->replaceAllUsesWith(NewCaller);
10527 Caller->eraseFromParent();
10528 RemoveFromWorkList(Caller);
10529 return 0;
10530 }
10531 }
10532
10533 // Replace the trampoline call with a direct call. Since there is no 'nest'
10534 // parameter, there is no need to adjust the argument list. Let the generic
10535 // code sort out any function type mismatches.
10536 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010537 NestF->getType() == PTy ? NestF :
10538 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010539 CS.setCalledFunction(NewCallee);
10540 return CS.getInstruction();
10541}
10542
Chris Lattner7da52b22006-11-01 04:51:18 +000010543/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10544/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10545/// and a single binop.
10546Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10547 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010548 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010549 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010550 Value *LHSVal = FirstInst->getOperand(0);
10551 Value *RHSVal = FirstInst->getOperand(1);
10552
10553 const Type *LHSType = LHSVal->getType();
10554 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010555
10556 // Scan to see if all operands are the same opcode, all have one use, and all
10557 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010558 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010559 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010560 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010561 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010562 // types or GEP's with different index types.
10563 I->getOperand(0)->getType() != LHSType ||
10564 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010565 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010566
10567 // If they are CmpInst instructions, check their predicates
10568 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10569 if (cast<CmpInst>(I)->getPredicate() !=
10570 cast<CmpInst>(FirstInst)->getPredicate())
10571 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010572
10573 // Keep track of which operand needs a phi node.
10574 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10575 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010576 }
10577
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010578 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010579
Chris Lattner7da52b22006-11-01 04:51:18 +000010580 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010581 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010582 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010583 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010584 NewLHS = PHINode::Create(LHSType,
10585 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010586 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10587 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010588 InsertNewInstBefore(NewLHS, PN);
10589 LHSVal = NewLHS;
10590 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010591
10592 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010593 NewRHS = PHINode::Create(RHSType,
10594 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010595 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10596 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010597 InsertNewInstBefore(NewRHS, PN);
10598 RHSVal = NewRHS;
10599 }
10600
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010601 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010602 if (NewLHS || NewRHS) {
10603 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10604 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10605 if (NewLHS) {
10606 Value *NewInLHS = InInst->getOperand(0);
10607 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10608 }
10609 if (NewRHS) {
10610 Value *NewInRHS = InInst->getOperand(1);
10611 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10612 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010613 }
10614 }
10615
Chris Lattner7da52b22006-11-01 04:51:18 +000010616 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010617 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010618 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010619 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10620 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010621}
10622
Chris Lattner05f18922008-12-01 02:34:36 +000010623Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10624 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10625
10626 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10627 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010628 // This is true if all GEP bases are allocas and if all indices into them are
10629 // constants.
10630 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010631
10632 // Scan to see if all operands are the same opcode, all have one use, and all
10633 // kill their operands (i.e. the operands have one use).
10634 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10635 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10636 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10637 GEP->getNumOperands() != FirstInst->getNumOperands())
10638 return 0;
10639
Chris Lattner36d3e322009-02-21 00:46:50 +000010640 // Keep track of whether or not all GEPs are of alloca pointers.
10641 if (AllBasePointersAreAllocas &&
10642 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10643 !GEP->hasAllConstantIndices()))
10644 AllBasePointersAreAllocas = false;
10645
Chris Lattner05f18922008-12-01 02:34:36 +000010646 // Compare the operand lists.
10647 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10648 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10649 continue;
10650
10651 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10652 // if one of the PHIs has a constant for the index. The index may be
10653 // substantially cheaper to compute for the constants, so making it a
10654 // variable index could pessimize the path. This also handles the case
10655 // for struct indices, which must always be constant.
10656 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10657 isa<ConstantInt>(GEP->getOperand(op)))
10658 return 0;
10659
10660 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10661 return 0;
10662 FixedOperands[op] = 0; // Needs a PHI.
10663 }
10664 }
10665
Chris Lattner36d3e322009-02-21 00:46:50 +000010666 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010667 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010668 // offset calculation, but all the predecessors will have to materialize the
10669 // stack address into a register anyway. We'd actually rather *clone* the
10670 // load up into the predecessors so that we have a load of a gep of an alloca,
10671 // which can usually all be folded into the load.
10672 if (AllBasePointersAreAllocas)
10673 return 0;
10674
Chris Lattner05f18922008-12-01 02:34:36 +000010675 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10676 // that is variable.
10677 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10678
10679 bool HasAnyPHIs = false;
10680 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10681 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10682 Value *FirstOp = FirstInst->getOperand(i);
10683 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10684 FirstOp->getName()+".pn");
10685 InsertNewInstBefore(NewPN, PN);
10686
10687 NewPN->reserveOperandSpace(e);
10688 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10689 OperandPhis[i] = NewPN;
10690 FixedOperands[i] = NewPN;
10691 HasAnyPHIs = true;
10692 }
10693
10694
10695 // Add all operands to the new PHIs.
10696 if (HasAnyPHIs) {
10697 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10698 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10699 BasicBlock *InBB = PN.getIncomingBlock(i);
10700
10701 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10702 if (PHINode *OpPhi = OperandPhis[op])
10703 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10704 }
10705 }
10706
10707 Value *Base = FixedOperands[0];
10708 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10709 FixedOperands.end());
10710}
10711
10712
Chris Lattner21550882009-02-23 05:56:17 +000010713/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10714/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010715/// obvious the value of the load is not changed from the point of the load to
10716/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010717///
10718/// Finally, it is safe, but not profitable, to sink a load targetting a
10719/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10720/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010721static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010722 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10723
10724 for (++BBI; BBI != E; ++BBI)
10725 if (BBI->mayWriteToMemory())
10726 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010727
10728 // Check for non-address taken alloca. If not address-taken already, it isn't
10729 // profitable to do this xform.
10730 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10731 bool isAddressTaken = false;
10732 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10733 UI != E; ++UI) {
10734 if (isa<LoadInst>(UI)) continue;
10735 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10736 // If storing TO the alloca, then the address isn't taken.
10737 if (SI->getOperand(1) == AI) continue;
10738 }
10739 isAddressTaken = true;
10740 break;
10741 }
10742
Chris Lattner36d3e322009-02-21 00:46:50 +000010743 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010744 return false;
10745 }
10746
Chris Lattner36d3e322009-02-21 00:46:50 +000010747 // If this load is a load from a GEP with a constant offset from an alloca,
10748 // then we don't want to sink it. In its present form, it will be
10749 // load [constant stack offset]. Sinking it will cause us to have to
10750 // materialize the stack addresses in each predecessor in a register only to
10751 // do a shared load from register in the successor.
10752 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10753 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10754 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10755 return false;
10756
Chris Lattner76c73142006-11-01 07:13:54 +000010757 return true;
10758}
10759
Chris Lattner9fe38862003-06-19 17:00:31 +000010760
Chris Lattnerbac32862004-11-14 19:13:23 +000010761// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10762// operator and they all are only used by the PHI, PHI together their
10763// inputs, and do the operation once, to the result of the PHI.
10764Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10765 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10766
10767 // Scan the instruction, looking for input operations that can be folded away.
10768 // If all input operands to the phi are the same instruction (e.g. a cast from
10769 // the same type or "+42") we can pull the operation through the PHI, reducing
10770 // code size and simplifying code.
10771 Constant *ConstantOp = 0;
10772 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010773 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010774 if (isa<CastInst>(FirstInst)) {
10775 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010776 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010777 // Can fold binop, compare or shift here if the RHS is a constant,
10778 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010779 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010780 if (ConstantOp == 0)
10781 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010782 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10783 isVolatile = LI->isVolatile();
10784 // We can't sink the load if the loaded value could be modified between the
10785 // load and the PHI.
10786 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010787 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010788 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010789
10790 // If the PHI is of volatile loads and the load block has multiple
10791 // successors, sinking it would remove a load of the volatile value from
10792 // the path through the other successor.
10793 if (isVolatile &&
10794 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10795 return 0;
10796
Chris Lattner9c080502006-11-01 07:43:41 +000010797 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010798 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010799 } else {
10800 return 0; // Cannot fold this operation.
10801 }
10802
10803 // Check to see if all arguments are the same operation.
10804 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10805 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10806 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010807 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010808 return 0;
10809 if (CastSrcTy) {
10810 if (I->getOperand(0)->getType() != CastSrcTy)
10811 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010812 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010813 // We can't sink the load if the loaded value could be modified between
10814 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010815 if (LI->isVolatile() != isVolatile ||
10816 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010817 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010818 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010819
Chris Lattner71042962008-07-08 17:18:32 +000010820 // If the PHI is of volatile loads and the load block has multiple
10821 // successors, sinking it would remove a load of the volatile value from
10822 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010823 if (isVolatile &&
10824 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10825 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010826
Chris Lattnerbac32862004-11-14 19:13:23 +000010827 } else if (I->getOperand(1) != ConstantOp) {
10828 return 0;
10829 }
10830 }
10831
10832 // Okay, they are all the same operation. Create a new PHI node of the
10833 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010834 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10835 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010836 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010837
10838 Value *InVal = FirstInst->getOperand(0);
10839 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010840
10841 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010842 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10843 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10844 if (NewInVal != InVal)
10845 InVal = 0;
10846 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10847 }
10848
10849 Value *PhiVal;
10850 if (InVal) {
10851 // The new PHI unions all of the same values together. This is really
10852 // common, so we handle it intelligently here for compile-time speed.
10853 PhiVal = InVal;
10854 delete NewPN;
10855 } else {
10856 InsertNewInstBefore(NewPN, PN);
10857 PhiVal = NewPN;
10858 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010859
Chris Lattnerbac32862004-11-14 19:13:23 +000010860 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010861 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010862 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010863 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010864 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010865 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010866 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010867 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010868 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10869
10870 // If this was a volatile load that we are merging, make sure to loop through
10871 // and mark all the input loads as non-volatile. If we don't do this, we will
10872 // insert a new volatile load and the old ones will not be deletable.
10873 if (isVolatile)
10874 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10875 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10876
10877 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010878}
Chris Lattnera1be5662002-05-02 17:06:02 +000010879
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010880/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10881/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010882static bool DeadPHICycle(PHINode *PN,
10883 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010884 if (PN->use_empty()) return true;
10885 if (!PN->hasOneUse()) return false;
10886
10887 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010888 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010889 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010890
10891 // Don't scan crazily complex things.
10892 if (PotentiallyDeadPHIs.size() == 16)
10893 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010894
10895 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10896 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010897
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010898 return false;
10899}
10900
Chris Lattnercf5008a2007-11-06 21:52:06 +000010901/// PHIsEqualValue - Return true if this phi node is always equal to
10902/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10903/// z = some value; x = phi (y, z); y = phi (x, z)
10904static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10905 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10906 // See if we already saw this PHI node.
10907 if (!ValueEqualPHIs.insert(PN))
10908 return true;
10909
10910 // Don't scan crazily complex things.
10911 if (ValueEqualPHIs.size() == 16)
10912 return false;
10913
10914 // Scan the operands to see if they are either phi nodes or are equal to
10915 // the value.
10916 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10917 Value *Op = PN->getIncomingValue(i);
10918 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10919 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10920 return false;
10921 } else if (Op != NonPhiInVal)
10922 return false;
10923 }
10924
10925 return true;
10926}
10927
10928
Chris Lattner473945d2002-05-06 18:06:38 +000010929// PHINode simplification
10930//
Chris Lattner7e708292002-06-25 16:13:24 +000010931Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010932 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010933 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010934
Owen Anderson7e057142006-07-10 22:03:18 +000010935 if (Value *V = PN.hasConstantValue())
10936 return ReplaceInstUsesWith(PN, V);
10937
Owen Anderson7e057142006-07-10 22:03:18 +000010938 // If all PHI operands are the same operation, pull them through the PHI,
10939 // reducing code size.
10940 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010941 isa<Instruction>(PN.getIncomingValue(1)) &&
10942 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10943 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10944 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10945 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010946 PN.getIncomingValue(0)->hasOneUse())
10947 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10948 return Result;
10949
10950 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10951 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10952 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010953 if (PN.hasOneUse()) {
10954 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10955 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010956 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010957 PotentiallyDeadPHIs.insert(&PN);
10958 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersond672ecb2009-07-03 00:17:18 +000010959 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010960 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010961
10962 // If this phi has a single use, and if that use just computes a value for
10963 // the next iteration of a loop, delete the phi. This occurs with unused
10964 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10965 // common case here is good because the only other things that catch this
10966 // are induction variable analysis (sometimes) and ADCE, which is only run
10967 // late.
10968 if (PHIUser->hasOneUse() &&
10969 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10970 PHIUser->use_back() == &PN) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010971 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010972 }
10973 }
Owen Anderson7e057142006-07-10 22:03:18 +000010974
Chris Lattnercf5008a2007-11-06 21:52:06 +000010975 // We sometimes end up with phi cycles that non-obviously end up being the
10976 // same value, for example:
10977 // z = some value; x = phi (y, z); y = phi (x, z)
10978 // where the phi nodes don't necessarily need to be in the same block. Do a
10979 // quick check to see if the PHI node only contains a single non-phi value, if
10980 // so, scan to see if the phi cycle is actually equal to that value.
10981 {
10982 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10983 // Scan for the first non-phi operand.
10984 while (InValNo != NumOperandVals &&
10985 isa<PHINode>(PN.getIncomingValue(InValNo)))
10986 ++InValNo;
10987
10988 if (InValNo != NumOperandVals) {
10989 Value *NonPhiInVal = PN.getOperand(InValNo);
10990
10991 // Scan the rest of the operands to see if there are any conflicts, if so
10992 // there is no need to recursively scan other phis.
10993 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10994 Value *OpVal = PN.getIncomingValue(InValNo);
10995 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10996 break;
10997 }
10998
10999 // If we scanned over all operands, then we have one unique value plus
11000 // phi values. Scan PHI nodes to see if they all merge in each other or
11001 // the value.
11002 if (InValNo == NumOperandVals) {
11003 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11004 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11005 return ReplaceInstUsesWith(PN, NonPhiInVal);
11006 }
11007 }
11008 }
Chris Lattner60921c92003-12-19 05:58:40 +000011009 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011010}
11011
Reid Spencer17212df2006-12-12 09:18:51 +000011012static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
11013 Instruction *InsertPoint,
11014 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000011015 unsigned PtrSize = DTy->getScalarSizeInBits();
11016 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000011017 // We must cast correctly to the pointer type. Ensure that we
11018 // sign extend the integer value if it is smaller as this is
11019 // used for address computation.
11020 Instruction::CastOps opcode =
11021 (VTySize < PtrSize ? Instruction::SExt :
11022 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11023 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000011024}
11025
Chris Lattnera1be5662002-05-02 17:06:02 +000011026
Chris Lattner7e708292002-06-25 16:13:24 +000011027Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000011028 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000011029 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000011030 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011031 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011032 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011033
Chris Lattnere87597f2004-10-16 18:11:37 +000011034 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000011035 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011036
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011037 bool HasZeroPointerIndex = false;
11038 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11039 HasZeroPointerIndex = C->isNullValue();
11040
11041 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011042 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011043
Chris Lattner28977af2004-04-05 01:30:19 +000011044 // Eliminate unneeded casts for indices.
11045 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011046
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011047 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011048 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11049 i != e; ++i, ++GTI) {
Sanjiv Gupta7787d4a2009-04-24 02:37:54 +000011050 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000011051 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011052 if (CI->getOpcode() == Instruction::ZExt ||
11053 CI->getOpcode() == Instruction::SExt) {
11054 const Type *SrcTy = CI->getOperand(0)->getType();
11055 // We can eliminate a cast from i32 to i64 iff the target
11056 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000011057 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011058 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000011059 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000011060 }
11061 }
11062 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011063 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000011064 // to what we need. If narrower, sign-extend it to what we need.
11065 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011066 // insert it. This explicit cast can make subsequent optimizations more
11067 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000011068 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011069 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000011070 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011071 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000011072 MadeChange = true;
11073 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011074 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11075 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011076 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011077 MadeChange = true;
11078 }
Dan Gohman4f833d42008-09-11 23:06:38 +000011079 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11080 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011081 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011082 MadeChange = true;
11083 } else {
11084 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11085 GEP);
11086 *i = Op;
11087 MadeChange = true;
11088 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011089 }
Chris Lattner28977af2004-04-05 01:30:19 +000011090 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011091 }
Chris Lattner28977af2004-04-05 01:30:19 +000011092 if (MadeChange) return &GEP;
11093
Chris Lattner90ac28c2002-08-02 19:29:35 +000011094 // Combine Indices - If the source pointer to this getelementptr instruction
11095 // is a getelementptr instruction, combine the indices of the two
11096 // getelementptr instructions into a single instruction.
11097 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011098 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000011099 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000011100 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000011101
11102 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011103 // Note that if our source is a gep chain itself that we wait for that
11104 // chain to be resolved before we perform this transformation. This
11105 // avoids us creating a TON of code in some cases.
11106 //
11107 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11108 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11109 return 0; // Wait until our source is folded to completion.
11110
Chris Lattner72588fc2007-02-15 22:48:32 +000011111 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011112
11113 // Find out whether the last index in the source GEP is a sequential idx.
11114 bool EndsWithSequential = false;
11115 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11116 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011117 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011118
Chris Lattner90ac28c2002-08-02 19:29:35 +000011119 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011120 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011121 // Replace: gep (gep %P, long B), long A, ...
11122 // With: T = long A+B; gep %P, T, ...
11123 //
Chris Lattner620ce142004-05-07 22:09:22 +000011124 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011125 if (SO1 == Context->getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011126 Sum = GO1;
Owen Andersond672ecb2009-07-03 00:17:18 +000011127 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011128 Sum = SO1;
11129 } else {
11130 // If they aren't the same type, convert both to an integer of the
11131 // target's pointer size.
11132 if (SO1->getType() != GO1->getType()) {
11133 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011134 SO1 =
11135 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011136 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011137 GO1 =
11138 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011139 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000011140 unsigned PS = TD->getPointerSizeInBits();
11141 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011142 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011143 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011144
Duncan Sands514ab342007-11-01 20:53:16 +000011145 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011146 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011147 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011148 } else {
11149 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011150 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11151 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011152 }
11153 }
11154 }
Chris Lattner620ce142004-05-07 22:09:22 +000011155 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersond672ecb2009-07-03 00:17:18 +000011156 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11157 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011158 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011159 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011160 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011161 }
Chris Lattner28977af2004-04-05 01:30:19 +000011162 }
Chris Lattner620ce142004-05-07 22:09:22 +000011163
11164 // Recycle the GEP we already have if possible.
11165 if (SrcGEPOperands.size() == 2) {
11166 GEP.setOperand(0, SrcGEPOperands[0]);
11167 GEP.setOperand(1, Sum);
11168 return &GEP;
11169 } else {
11170 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11171 SrcGEPOperands.end()-1);
11172 Indices.push_back(Sum);
11173 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11174 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011175 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011176 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011177 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011178 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011179 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11180 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011181 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11182 }
11183
11184 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011185 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11186 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011187
Chris Lattner620ce142004-05-07 22:09:22 +000011188 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011189 // GEP of global variable. If all of the indices for this GEP are
11190 // constants, we can promote this to a constexpr instead of an instruction.
11191
11192 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011193 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011194 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11195 for (; I != E && isa<Constant>(*I); ++I)
11196 Indices.push_back(cast<Constant>(*I));
11197
11198 if (I == E) { // If they are all constants...
Owen Andersond672ecb2009-07-03 00:17:18 +000011199 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011200 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011201
11202 // Replace all uses of the GEP with the new constexpr...
11203 return ReplaceInstUsesWith(GEP, CE);
11204 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011205 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011206 if (!isa<PointerType>(X->getType())) {
11207 // Not interesting. Source pointer must be a cast from pointer.
11208 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011209 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11210 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011211 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011212 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11213 // into : GEP i8* X, ...
11214 //
Chris Lattnereed48272005-09-13 00:40:14 +000011215 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011216 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11217 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011218 if (const ArrayType *CATy =
11219 dyn_cast<ArrayType>(CPTy->getElementType())) {
11220 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11221 if (CATy->getElementType() == XTy->getElementType()) {
11222 // -> GEP i8* X, ...
11223 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11224 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11225 GEP.getName());
11226 } else if (const ArrayType *XATy =
11227 dyn_cast<ArrayType>(XTy->getElementType())) {
11228 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011229 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011230 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011231 // At this point, we know that the cast source type is a pointer
11232 // to an array of the same type as the destination pointer
11233 // array. Because the array type is never stepped over (there
11234 // is a leading zero) we can fold the cast into this GEP.
11235 GEP.setOperand(0, X);
11236 return &GEP;
11237 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011238 }
11239 }
Chris Lattnereed48272005-09-13 00:40:14 +000011240 } else if (GEP.getNumOperands() == 2) {
11241 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011242 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11243 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011244 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11245 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11246 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011247 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11248 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011249 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011250 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011251 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011252 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011253 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011254 // V and GEP are both pointer types --> BitCast
11255 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011256 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011257
11258 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011259 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011260 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011261 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011262
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011263 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011264 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011265 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011266
11267 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11268 // allow either a mul, shift, or constant here.
11269 Value *NewIdx = 0;
11270 ConstantInt *Scale = 0;
11271 if (ArrayEltSize == 1) {
11272 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011273 Scale =
11274 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011275 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011276 NewIdx = Context->getConstantInt(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011277 Scale = CI;
11278 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11279 if (Inst->getOpcode() == Instruction::Shl &&
11280 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011281 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11282 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersond672ecb2009-07-03 00:17:18 +000011283 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011284 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011285 NewIdx = Inst->getOperand(0);
11286 } else if (Inst->getOpcode() == Instruction::Mul &&
11287 isa<ConstantInt>(Inst->getOperand(1))) {
11288 Scale = cast<ConstantInt>(Inst->getOperand(1));
11289 NewIdx = Inst->getOperand(0);
11290 }
11291 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011292
Chris Lattner7835cdd2005-09-13 18:36:04 +000011293 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011294 // out, perform the transformation. Note, we don't know whether Scale is
11295 // signed or not. We'll use unsigned version of division/modulo
11296 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011297 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011298 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011299 Scale = Context->getConstantInt(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011300 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011301 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011302 Constant *C =
11303 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011304 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011305 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011306 NewIdx = InsertNewInstBefore(Sc, GEP);
11307 }
11308
11309 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011310 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011311 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011312 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011313 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011314 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011315 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11316 // The NewGEP must be pointer typed, so must the old one -> BitCast
11317 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011318 }
11319 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011320 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011321 }
Chris Lattner58407792009-01-09 04:53:57 +000011322
Chris Lattner46cd5a12009-01-09 05:44:56 +000011323 /// See if we can simplify:
11324 /// X = bitcast A to B*
11325 /// Y = gep X, <...constant indices...>
11326 /// into a gep of the original struct. This is important for SROA and alias
11327 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011328 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011329 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11330 // Determine how much the GEP moves the pointer. We are guaranteed to get
11331 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011332 ConstantInt *OffsetV =
11333 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011334 int64_t Offset = OffsetV->getSExtValue();
11335
11336 // If this GEP instruction doesn't move the pointer, just replace the GEP
11337 // with a bitcast of the real input to the dest type.
11338 if (Offset == 0) {
11339 // If the bitcast is of an allocation, and the allocation will be
11340 // converted to match the type of the cast, don't touch this.
11341 if (isa<AllocationInst>(BCI->getOperand(0))) {
11342 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11343 if (Instruction *I = visitBitCast(*BCI)) {
11344 if (I != BCI) {
11345 I->takeName(BCI);
11346 BCI->getParent()->getInstList().insert(BCI, I);
11347 ReplaceInstUsesWith(*BCI, I);
11348 }
11349 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011350 }
Chris Lattner58407792009-01-09 04:53:57 +000011351 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011352 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011353 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011354
11355 // Otherwise, if the offset is non-zero, we need to find out if there is a
11356 // field at Offset in 'A's type. If so, we can pull the cast through the
11357 // GEP.
11358 SmallVector<Value*, 8> NewIndices;
11359 const Type *InTy =
11360 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011361 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011362 Instruction *NGEP =
11363 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11364 NewIndices.end());
11365 if (NGEP->getType() == GEP.getType()) return NGEP;
11366 InsertNewInstBefore(NGEP, GEP);
11367 NGEP->takeName(&GEP);
11368 return new BitCastInst(NGEP, GEP.getType());
11369 }
Chris Lattner58407792009-01-09 04:53:57 +000011370 }
11371 }
11372
Chris Lattner8a2a3112001-12-14 16:52:21 +000011373 return 0;
11374}
11375
Chris Lattner0864acf2002-11-04 16:18:53 +000011376Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11377 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011378 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011379 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11380 const Type *NewTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000011381 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011382 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011383
11384 // Create and insert the replacement instruction...
11385 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000011386 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011387 else {
11388 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000011389 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011390 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011391
11392 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011393
Chris Lattner0864acf2002-11-04 16:18:53 +000011394 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011395 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011396 //
11397 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011398 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011399
11400 // Now that I is pointing to the first non-allocation-inst in the block,
11401 // insert our getelementptr instruction...
11402 //
Owen Andersond672ecb2009-07-03 00:17:18 +000011403 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011404 Value *Idx[2];
11405 Idx[0] = NullIdx;
11406 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011407 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11408 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011409
11410 // Now make everything use the getelementptr instead of the original
11411 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011412 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011413 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011414 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011415 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011416 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011417
Dan Gohman6893cd72009-01-13 20:18:38 +000011418 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11419 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011420 // Note that we only do this for alloca's, because malloc should allocate
11421 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011422 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersond672ecb2009-07-03 00:17:18 +000011423 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011424
11425 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11426 if (AI.getAlignment() == 0)
11427 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11428 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011429
Chris Lattner0864acf2002-11-04 16:18:53 +000011430 return 0;
11431}
11432
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011433Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11434 Value *Op = FI.getOperand(0);
11435
Chris Lattner17be6352004-10-18 02:59:09 +000011436 // free undef -> unreachable.
11437 if (isa<UndefValue>(Op)) {
11438 // Insert a new store to null because we cannot modify the CFG here.
Owen Andersond672ecb2009-07-03 00:17:18 +000011439 new StoreInst(Context->getConstantIntTrue(),
11440 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011441 return EraseInstFromFunction(FI);
11442 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011443
Chris Lattner6160e852004-02-28 04:57:37 +000011444 // If we have 'free null' delete the instruction. This can happen in stl code
11445 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011446 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011447 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011448
11449 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11450 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11451 FI.setOperand(0, CI->getOperand(0));
11452 return &FI;
11453 }
11454
11455 // Change free (gep X, 0,0,0,0) into free(X)
11456 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11457 if (GEPI->hasAllZeroIndices()) {
11458 AddToWorkList(GEPI);
11459 FI.setOperand(0, GEPI->getOperand(0));
11460 return &FI;
11461 }
11462 }
11463
11464 // Change free(malloc) into nothing, if the malloc has a single use.
11465 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11466 if (MI->hasOneUse()) {
11467 EraseInstFromFunction(FI);
11468 return EraseInstFromFunction(*MI);
11469 }
Chris Lattner6160e852004-02-28 04:57:37 +000011470
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011471 return 0;
11472}
11473
11474
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011475/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011476static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011477 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011478 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011479 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011480 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011481
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011482 if (TD) {
11483 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11484 // Instead of loading constant c string, use corresponding integer value
11485 // directly if string length is small enough.
11486 std::string Str;
11487 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11488 unsigned len = Str.length();
11489 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11490 unsigned numBits = Ty->getPrimitiveSizeInBits();
11491 // Replace LI with immediate integer store.
11492 if ((numBits >> 3) == len + 1) {
11493 APInt StrVal(numBits, 0);
11494 APInt SingleChar(numBits, 0);
11495 if (TD->isLittleEndian()) {
11496 for (signed i = len-1; i >= 0; i--) {
11497 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11498 StrVal = (StrVal << 8) | SingleChar;
11499 }
11500 } else {
11501 for (unsigned i = 0; i < len; i++) {
11502 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11503 StrVal = (StrVal << 8) | SingleChar;
11504 }
11505 // Append NULL at the end.
11506 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011507 StrVal = (StrVal << 8) | SingleChar;
11508 }
Owen Andersond672ecb2009-07-03 00:17:18 +000011509 Value *NL = Context->getConstantInt(StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011510 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011511 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011512 }
11513 }
11514 }
11515
Mon P Wang6753f952009-02-07 22:19:29 +000011516 const PointerType *DestTy = cast<PointerType>(CI->getType());
11517 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011518 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011519
11520 // If the address spaces don't match, don't eliminate the cast.
11521 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11522 return 0;
11523
Chris Lattnerb89e0712004-07-13 01:49:43 +000011524 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011525
Reid Spencer42230162007-01-22 05:51:25 +000011526 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011527 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011528 // If the source is an array, the code below will not succeed. Check to
11529 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11530 // constants.
11531 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11532 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11533 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011534 Value *Idxs[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011535 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11536 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011537 SrcTy = cast<PointerType>(CastOp->getType());
11538 SrcPTy = SrcTy->getElementType();
11539 }
11540
Reid Spencer42230162007-01-22 05:51:25 +000011541 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011542 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011543 // Do not allow turning this into a load of an integer, which is then
11544 // casted to a pointer, this pessimizes pointer analysis a lot.
11545 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011546 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11547 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011548
Chris Lattnerf9527852005-01-31 04:50:46 +000011549 // Okay, we are casting from one integer or pointer type to another of
11550 // the same size. Instead of casting the pointer before the load, cast
11551 // the result of the loaded value.
11552 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11553 CI->getName(),
11554 LI.isVolatile()),LI);
11555 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011556 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011557 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011558 }
11559 }
11560 return 0;
11561}
11562
Chris Lattner833b8a42003-06-26 05:06:25 +000011563Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11564 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011565
Dan Gohman9941f742007-07-20 16:34:21 +000011566 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011567 unsigned KnownAlign =
11568 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011569 if (KnownAlign >
11570 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11571 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011572 LI.setAlignment(KnownAlign);
11573
Chris Lattner37366c12005-05-01 04:24:53 +000011574 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011575 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011576 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011577 return Res;
11578
11579 // None of the following transforms are legal for volatile loads.
11580 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011581
Dan Gohman2276a7b2008-10-15 23:19:35 +000011582 // Do really simple store-to-load forwarding and load CSE, to catch cases
11583 // where there are several consequtive memory accesses to the same location,
11584 // separated by a few arithmetic operations.
11585 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011586 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11587 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011588
Christopher Lambb15147e2007-12-29 07:56:53 +000011589 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11590 const Value *GEPI0 = GEPI->getOperand(0);
11591 // TODO: Consider a target hook for valid address spaces for this xform.
11592 if (isa<ConstantPointerNull>(GEPI0) &&
11593 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011594 // Insert a new store to null instruction before the load to indicate
11595 // that this code is not reachable. We do this instead of inserting
11596 // an unreachable instruction directly because we cannot modify the
11597 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011598 new StoreInst(Context->getUndef(LI.getType()),
11599 Context->getNullValue(Op->getType()), &LI);
11600 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011601 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011602 }
Chris Lattner37366c12005-05-01 04:24:53 +000011603
Chris Lattnere87597f2004-10-16 18:11:37 +000011604 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011605 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011606 // TODO: Consider a target hook for valid address spaces for this xform.
11607 if (isa<UndefValue>(C) || (C->isNullValue() &&
11608 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011609 // Insert a new store to null instruction before the load to indicate that
11610 // this code is not reachable. We do this instead of inserting an
11611 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011612 new StoreInst(Context->getUndef(LI.getType()),
11613 Context->getNullValue(Op->getType()), &LI);
11614 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011615 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011616
Chris Lattnere87597f2004-10-16 18:11:37 +000011617 // Instcombine load (constant global) into the value loaded.
11618 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011619 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011620 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011621
Chris Lattnere87597f2004-10-16 18:11:37 +000011622 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011623 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011624 if (CE->getOpcode() == Instruction::GetElementPtr) {
11625 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011626 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011627 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011628 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11629 Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011630 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011631 if (CE->getOperand(0)->isNullValue()) {
11632 // Insert a new store to null instruction before the load to indicate
11633 // that this code is not reachable. We do this instead of inserting
11634 // an unreachable instruction directly because we cannot modify the
11635 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011636 new StoreInst(Context->getUndef(LI.getType()),
11637 Context->getNullValue(Op->getType()), &LI);
11638 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011639 }
11640
Reid Spencer3da59db2006-11-27 01:05:10 +000011641 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011642 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011643 return Res;
11644 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011645 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011646 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011647
11648 // If this load comes from anywhere in a constant global, and if the global
11649 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011650 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011651 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011652 if (GV->getInitializer()->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +000011653 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011654 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersond672ecb2009-07-03 00:17:18 +000011655 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011656 }
11657 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011658
Chris Lattner37366c12005-05-01 04:24:53 +000011659 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011660 // Change select and PHI nodes to select values instead of addresses: this
11661 // helps alias analysis out a lot, allows many others simplifications, and
11662 // exposes redundancy in the code.
11663 //
11664 // Note that we cannot do the transformation unless we know that the
11665 // introduced loads cannot trap! Something like this is valid as long as
11666 // the condition is always false: load (select bool %C, int* null, int* %G),
11667 // but it would not be valid if we transformed it to load from null
11668 // unconditionally.
11669 //
11670 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11671 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011672 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11673 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011674 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011675 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011676 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011677 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011678 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011679 }
11680
Chris Lattner684fe212004-09-23 15:46:00 +000011681 // load (select (cond, null, P)) -> load P
11682 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11683 if (C->isNullValue()) {
11684 LI.setOperand(0, SI->getOperand(2));
11685 return &LI;
11686 }
11687
11688 // load (select (cond, P, null)) -> load P
11689 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11690 if (C->isNullValue()) {
11691 LI.setOperand(0, SI->getOperand(1));
11692 return &LI;
11693 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011694 }
11695 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011696 return 0;
11697}
11698
Reid Spencer55af2b52007-01-19 21:20:31 +000011699/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011700/// when possible. This makes it generally easy to do alias analysis and/or
11701/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011702static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11703 User *CI = cast<User>(SI.getOperand(1));
11704 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011705 LLVMContext *Context = IC.getContext();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011706
11707 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011708 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11709 if (SrcTy == 0) return 0;
11710
11711 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011712
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011713 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11714 return 0;
11715
Chris Lattner3914f722009-01-24 01:00:13 +000011716 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11717 /// to its first element. This allows us to handle things like:
11718 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11719 /// on 32-bit hosts.
11720 SmallVector<Value*, 4> NewGEPIndices;
11721
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011722 // If the source is an array, the code below will not succeed. Check to
11723 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11724 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011725 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11726 // Index through pointer.
Owen Andersond672ecb2009-07-03 00:17:18 +000011727 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011728 NewGEPIndices.push_back(Zero);
11729
11730 while (1) {
11731 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011732 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011733 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011734 NewGEPIndices.push_back(Zero);
11735 SrcPTy = STy->getElementType(0);
11736 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11737 NewGEPIndices.push_back(Zero);
11738 SrcPTy = ATy->getElementType();
11739 } else {
11740 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011741 }
Chris Lattner3914f722009-01-24 01:00:13 +000011742 }
11743
Owen Andersond672ecb2009-07-03 00:17:18 +000011744 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011745 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011746
11747 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11748 return 0;
11749
Chris Lattner71759c42009-01-16 20:12:52 +000011750 // If the pointers point into different address spaces or if they point to
11751 // values with different sizes, we can't do the transformation.
11752 if (SrcTy->getAddressSpace() !=
11753 cast<PointerType>(CI->getType())->getAddressSpace() ||
11754 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011755 IC.getTargetData().getTypeSizeInBits(DestPTy))
11756 return 0;
11757
11758 // Okay, we are casting from one integer or pointer type to another of
11759 // the same size. Instead of casting the pointer before
11760 // the store, cast the value to be stored.
11761 Value *NewCast;
11762 Value *SIOp0 = SI.getOperand(0);
11763 Instruction::CastOps opcode = Instruction::BitCast;
11764 const Type* CastSrcTy = SIOp0->getType();
11765 const Type* CastDstTy = SrcPTy;
11766 if (isa<PointerType>(CastDstTy)) {
11767 if (CastSrcTy->isInteger())
11768 opcode = Instruction::IntToPtr;
11769 } else if (isa<IntegerType>(CastDstTy)) {
11770 if (isa<PointerType>(SIOp0->getType()))
11771 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011772 }
Chris Lattner3914f722009-01-24 01:00:13 +000011773
11774 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11775 // emit a GEP to index into its first field.
11776 if (!NewGEPIndices.empty()) {
11777 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000011778 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011779 NewGEPIndices.size());
11780 else
11781 CastOp = IC.InsertNewInstBefore(
11782 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11783 NewGEPIndices.end()), SI);
11784 }
11785
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011786 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersond672ecb2009-07-03 00:17:18 +000011787 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011788 else
11789 NewCast = IC.InsertNewInstBefore(
11790 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11791 SI);
11792 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011793}
11794
Chris Lattner4aebaee2008-11-27 08:56:30 +000011795/// equivalentAddressValues - Test if A and B will obviously have the same
11796/// value. This includes recognizing that %t0 and %t1 will have the same
11797/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011798/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011799/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011800/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011801/// %t2 = load i32* %t1
11802///
11803static bool equivalentAddressValues(Value *A, Value *B) {
11804 // Test if the values are trivially equivalent.
11805 if (A == B) return true;
11806
11807 // Test if the values come form identical arithmetic instructions.
11808 if (isa<BinaryOperator>(A) ||
11809 isa<CastInst>(A) ||
11810 isa<PHINode>(A) ||
11811 isa<GetElementPtrInst>(A))
11812 if (Instruction *BI = dyn_cast<Instruction>(B))
11813 if (cast<Instruction>(A)->isIdenticalTo(BI))
11814 return true;
11815
11816 // Otherwise they may not be equivalent.
11817 return false;
11818}
11819
Dale Johannesen4945c652009-03-03 21:26:39 +000011820// If this instruction has two uses, one of which is a llvm.dbg.declare,
11821// return the llvm.dbg.declare.
11822DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11823 if (!V->hasNUses(2))
11824 return 0;
11825 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11826 UI != E; ++UI) {
11827 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11828 return DI;
11829 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11830 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11831 return DI;
11832 }
11833 }
11834 return 0;
11835}
11836
Chris Lattner2f503e62005-01-31 05:36:43 +000011837Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11838 Value *Val = SI.getOperand(0);
11839 Value *Ptr = SI.getOperand(1);
11840
11841 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011842 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011843 ++NumCombined;
11844 return 0;
11845 }
Chris Lattner836692d2007-01-15 06:51:56 +000011846
11847 // If the RHS is an alloca with a single use, zapify the store, making the
11848 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011849 // If the RHS is an alloca with a two uses, the other one being a
11850 // llvm.dbg.declare, zapify the store and the declare, making the
11851 // alloca dead. We must do this to prevent declare's from affecting
11852 // codegen.
11853 if (!SI.isVolatile()) {
11854 if (Ptr->hasOneUse()) {
11855 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011856 EraseInstFromFunction(SI);
11857 ++NumCombined;
11858 return 0;
11859 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011860 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11861 if (isa<AllocaInst>(GEP->getOperand(0))) {
11862 if (GEP->getOperand(0)->hasOneUse()) {
11863 EraseInstFromFunction(SI);
11864 ++NumCombined;
11865 return 0;
11866 }
11867 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11868 EraseInstFromFunction(*DI);
11869 EraseInstFromFunction(SI);
11870 ++NumCombined;
11871 return 0;
11872 }
11873 }
11874 }
11875 }
11876 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11877 EraseInstFromFunction(*DI);
11878 EraseInstFromFunction(SI);
11879 ++NumCombined;
11880 return 0;
11881 }
Chris Lattner836692d2007-01-15 06:51:56 +000011882 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011883
Dan Gohman9941f742007-07-20 16:34:21 +000011884 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011885 unsigned KnownAlign =
11886 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011887 if (KnownAlign >
11888 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11889 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011890 SI.setAlignment(KnownAlign);
11891
Dale Johannesenacb51a32009-03-03 01:43:03 +000011892 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011893 // stores to the same location, separated by a few arithmetic operations. This
11894 // situation often occurs with bitfield accesses.
11895 BasicBlock::iterator BBI = &SI;
11896 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11897 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011898 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011899 // Don't count debug info directives, lest they affect codegen,
11900 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11901 // It is necessary for correctness to skip those that feed into a
11902 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011903 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011904 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011905 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011906 continue;
11907 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011908
11909 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11910 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011911 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11912 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011913 ++NumDeadStore;
11914 ++BBI;
11915 EraseInstFromFunction(*PrevSI);
11916 continue;
11917 }
11918 break;
11919 }
11920
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011921 // If this is a load, we have to stop. However, if the loaded value is from
11922 // the pointer we're loading and is producing the pointer we're storing,
11923 // then *this* store is dead (X = load P; store X -> P).
11924 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011925 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11926 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011927 EraseInstFromFunction(SI);
11928 ++NumCombined;
11929 return 0;
11930 }
11931 // Otherwise, this is a load from some other location. Stores before it
11932 // may not be dead.
11933 break;
11934 }
11935
Chris Lattner9ca96412006-02-08 03:25:32 +000011936 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011937 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011938 break;
11939 }
11940
11941
11942 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011943
11944 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011945 if (isa<ConstantPointerNull>(Ptr) &&
11946 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011947 if (!isa<UndefValue>(Val)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011948 SI.setOperand(0, Context->getUndef(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011949 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011950 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011951 ++NumCombined;
11952 }
11953 return 0; // Do not modify these!
11954 }
11955
11956 // store undef, Ptr -> noop
11957 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011958 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011959 ++NumCombined;
11960 return 0;
11961 }
11962
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011963 // If the pointer destination is a cast, see if we can fold the cast into the
11964 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011965 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011966 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11967 return Res;
11968 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011969 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011970 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11971 return Res;
11972
Chris Lattner408902b2005-09-12 23:23:25 +000011973
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011974 // If this store is the last instruction in the basic block (possibly
11975 // excepting debug info instructions and the pointer bitcasts that feed
11976 // into them), and if the block ends with an unconditional branch, try
11977 // to move it to the successor block.
11978 BBI = &SI;
11979 do {
11980 ++BBI;
11981 } while (isa<DbgInfoIntrinsic>(BBI) ||
11982 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011983 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011984 if (BI->isUnconditional())
11985 if (SimplifyStoreAtEndOfBlock(SI))
11986 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011987
Chris Lattner2f503e62005-01-31 05:36:43 +000011988 return 0;
11989}
11990
Chris Lattner3284d1f2007-04-15 00:07:55 +000011991/// SimplifyStoreAtEndOfBlock - Turn things like:
11992/// if () { *P = v1; } else { *P = v2 }
11993/// into a phi node with a store in the successor.
11994///
Chris Lattner31755a02007-04-15 01:02:18 +000011995/// Simplify things like:
11996/// *P = v1; if () { *P = v2; }
11997/// into a phi node with a store in the successor.
11998///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011999bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12000 BasicBlock *StoreBB = SI.getParent();
12001
12002 // Check to see if the successor block has exactly two incoming edges. If
12003 // so, see if the other predecessor contains a store to the same location.
12004 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012005 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012006
12007 // Determine whether Dest has exactly two predecessors and, if so, compute
12008 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012009 pred_iterator PI = pred_begin(DestBB);
12010 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012011 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012012 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012013 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012014 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012015 return false;
12016
12017 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012018 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012019 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012020 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012021 }
Chris Lattner31755a02007-04-15 01:02:18 +000012022 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012023 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012024
12025 // Bail out if all the relevant blocks aren't distinct (this can happen,
12026 // for example, if SI is in an infinite loop)
12027 if (StoreBB == DestBB || OtherBB == DestBB)
12028 return false;
12029
Chris Lattner31755a02007-04-15 01:02:18 +000012030 // Verify that the other block ends in a branch and is not otherwise empty.
12031 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012032 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012033 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012034 return false;
12035
Chris Lattner31755a02007-04-15 01:02:18 +000012036 // If the other block ends in an unconditional branch, check for the 'if then
12037 // else' case. there is an instruction before the branch.
12038 StoreInst *OtherStore = 0;
12039 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012040 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012041 // Skip over debugging info.
12042 while (isa<DbgInfoIntrinsic>(BBI) ||
12043 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12044 if (BBI==OtherBB->begin())
12045 return false;
12046 --BBI;
12047 }
12048 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012049 OtherStore = dyn_cast<StoreInst>(BBI);
12050 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12051 return false;
12052 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012053 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012054 // destinations is StoreBB, then we have the if/then case.
12055 if (OtherBr->getSuccessor(0) != StoreBB &&
12056 OtherBr->getSuccessor(1) != StoreBB)
12057 return false;
12058
12059 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012060 // if/then triangle. See if there is a store to the same ptr as SI that
12061 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012062 for (;; --BBI) {
12063 // Check to see if we find the matching store.
12064 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12065 if (OtherStore->getOperand(1) != SI.getOperand(1))
12066 return false;
12067 break;
12068 }
Eli Friedman6903a242008-06-13 22:02:12 +000012069 // If we find something that may be using or overwriting the stored
12070 // value, or if we run out of instructions, we can't do the xform.
12071 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012072 BBI == OtherBB->begin())
12073 return false;
12074 }
12075
12076 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012077 // make sure nothing reads or overwrites the stored value in
12078 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012079 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12080 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012081 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012082 return false;
12083 }
12084 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012085
Chris Lattner31755a02007-04-15 01:02:18 +000012086 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012087 Value *MergedVal = OtherStore->getOperand(0);
12088 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012089 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012090 PN->reserveOperandSpace(2);
12091 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012092 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12093 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012094 }
12095
12096 // Advance to a place where it is safe to insert the new store and
12097 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012098 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012099 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12100 OtherStore->isVolatile()), *BBI);
12101
12102 // Nuke the old stores.
12103 EraseInstFromFunction(SI);
12104 EraseInstFromFunction(*OtherStore);
12105 ++NumCombined;
12106 return true;
12107}
12108
Chris Lattner2f503e62005-01-31 05:36:43 +000012109
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012110Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12111 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012112 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012113 BasicBlock *TrueDest;
12114 BasicBlock *FalseDest;
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012115 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012116 !isa<Constant>(X)) {
12117 // Swap Destinations and condition...
12118 BI.setCondition(X);
12119 BI.setSuccessor(0, FalseDest);
12120 BI.setSuccessor(1, TrueDest);
12121 return &BI;
12122 }
12123
Reid Spencere4d87aa2006-12-23 06:05:41 +000012124 // Cannonicalize fcmp_one -> fcmp_oeq
12125 FCmpInst::Predicate FPred; Value *Y;
12126 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012127 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012128 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12129 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12130 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012131 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012132 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012133 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012134 // Swap Destinations and condition...
12135 BI.setCondition(NewSCC);
12136 BI.setSuccessor(0, FalseDest);
12137 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012138 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012139 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012140 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012141 return &BI;
12142 }
12143
12144 // Cannonicalize icmp_ne -> icmp_eq
12145 ICmpInst::Predicate IPred;
12146 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012147 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012148 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12149 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12150 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12151 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012152 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012153 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012154 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012155 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012156 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012157 BI.setSuccessor(0, FalseDest);
12158 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012159 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012160 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012161 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012162 return &BI;
12163 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012164
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012165 return 0;
12166}
Chris Lattner0864acf2002-11-04 16:18:53 +000012167
Chris Lattner46238a62004-07-03 00:26:11 +000012168Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12169 Value *Cond = SI.getCondition();
12170 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12171 if (I->getOpcode() == Instruction::Add)
12172 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12173 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12174 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012175 SI.setOperand(i,
12176 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012177 AddRHS));
12178 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012179 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012180 return &SI;
12181 }
12182 }
12183 return 0;
12184}
12185
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012186Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012187 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012188
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012189 if (!EV.hasIndices())
12190 return ReplaceInstUsesWith(EV, Agg);
12191
12192 if (Constant *C = dyn_cast<Constant>(Agg)) {
12193 if (isa<UndefValue>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012194 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012195
12196 if (isa<ConstantAggregateZero>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012197 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012198
12199 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12200 // Extract the element indexed by the first index out of the constant
12201 Value *V = C->getOperand(*EV.idx_begin());
12202 if (EV.getNumIndices() > 1)
12203 // Extract the remaining indices out of the constant indexed by the
12204 // first index
12205 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12206 else
12207 return ReplaceInstUsesWith(EV, V);
12208 }
12209 return 0; // Can't handle other constants
12210 }
12211 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12212 // We're extracting from an insertvalue instruction, compare the indices
12213 const unsigned *exti, *exte, *insi, *inse;
12214 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12215 exte = EV.idx_end(), inse = IV->idx_end();
12216 exti != exte && insi != inse;
12217 ++exti, ++insi) {
12218 if (*insi != *exti)
12219 // The insert and extract both reference distinctly different elements.
12220 // This means the extract is not influenced by the insert, and we can
12221 // replace the aggregate operand of the extract with the aggregate
12222 // operand of the insert. i.e., replace
12223 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12224 // %E = extractvalue { i32, { i32 } } %I, 0
12225 // with
12226 // %E = extractvalue { i32, { i32 } } %A, 0
12227 return ExtractValueInst::Create(IV->getAggregateOperand(),
12228 EV.idx_begin(), EV.idx_end());
12229 }
12230 if (exti == exte && insi == inse)
12231 // Both iterators are at the end: Index lists are identical. Replace
12232 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12233 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12234 // with "i32 42"
12235 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12236 if (exti == exte) {
12237 // The extract list is a prefix of the insert list. i.e. replace
12238 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12239 // %E = extractvalue { i32, { i32 } } %I, 1
12240 // with
12241 // %X = extractvalue { i32, { i32 } } %A, 1
12242 // %E = insertvalue { i32 } %X, i32 42, 0
12243 // by switching the order of the insert and extract (though the
12244 // insertvalue should be left in, since it may have other uses).
12245 Value *NewEV = InsertNewInstBefore(
12246 ExtractValueInst::Create(IV->getAggregateOperand(),
12247 EV.idx_begin(), EV.idx_end()),
12248 EV);
12249 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12250 insi, inse);
12251 }
12252 if (insi == inse)
12253 // The insert list is a prefix of the extract list
12254 // We can simply remove the common indices from the extract and make it
12255 // operate on the inserted value instead of the insertvalue result.
12256 // i.e., replace
12257 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12258 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12259 // with
12260 // %E extractvalue { i32 } { i32 42 }, 0
12261 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12262 exti, exte);
12263 }
12264 // Can't simplify extracts from other values. Note that nested extracts are
12265 // already simplified implicitely by the above (extract ( extract (insert) )
12266 // will be translated into extract ( insert ( extract ) ) first and then just
12267 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012268 return 0;
12269}
12270
Chris Lattner220b0cf2006-03-05 00:22:33 +000012271/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12272/// is to leave as a vector operation.
12273static bool CheapToScalarize(Value *V, bool isConstant) {
12274 if (isa<ConstantAggregateZero>(V))
12275 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012276 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012277 if (isConstant) return true;
12278 // If all elts are the same, we can extract.
12279 Constant *Op0 = C->getOperand(0);
12280 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12281 if (C->getOperand(i) != Op0)
12282 return false;
12283 return true;
12284 }
12285 Instruction *I = dyn_cast<Instruction>(V);
12286 if (!I) return false;
12287
12288 // Insert element gets simplified to the inserted element or is deleted if
12289 // this is constant idx extract element and its a constant idx insertelt.
12290 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12291 isa<ConstantInt>(I->getOperand(2)))
12292 return true;
12293 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12294 return true;
12295 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12296 if (BO->hasOneUse() &&
12297 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12298 CheapToScalarize(BO->getOperand(1), isConstant)))
12299 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012300 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12301 if (CI->hasOneUse() &&
12302 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12303 CheapToScalarize(CI->getOperand(1), isConstant)))
12304 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012305
12306 return false;
12307}
12308
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012309/// Read and decode a shufflevector mask.
12310///
12311/// It turns undef elements into values that are larger than the number of
12312/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012313static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12314 unsigned NElts = SVI->getType()->getNumElements();
12315 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12316 return std::vector<unsigned>(NElts, 0);
12317 if (isa<UndefValue>(SVI->getOperand(2)))
12318 return std::vector<unsigned>(NElts, 2*NElts);
12319
12320 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012321 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012322 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12323 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012324 Result.push_back(NElts*2); // undef -> 8
12325 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012326 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012327 return Result;
12328}
12329
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012330/// FindScalarElement - Given a vector and an element number, see if the scalar
12331/// value is already around as a register, for example if it were inserted then
12332/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012333static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012334 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012335 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12336 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012337 unsigned Width = PTy->getNumElements();
12338 if (EltNo >= Width) // Out of range access.
Owen Andersond672ecb2009-07-03 00:17:18 +000012339 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012340
12341 if (isa<UndefValue>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012342 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012343 else if (isa<ConstantAggregateZero>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012344 return Context->getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012345 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012346 return CP->getOperand(EltNo);
12347 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12348 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012349 if (!isa<ConstantInt>(III->getOperand(2)))
12350 return 0;
12351 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012352
12353 // If this is an insert to the element we are looking for, return the
12354 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012355 if (EltNo == IIElt)
12356 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012357
12358 // Otherwise, the insertelement doesn't modify the value, recurse on its
12359 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012360 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012361 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012362 unsigned LHSWidth =
12363 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012364 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012365 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012366 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012367 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012368 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012369 else
Owen Andersond672ecb2009-07-03 00:17:18 +000012370 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012371 }
12372
12373 // Otherwise, we don't know.
12374 return 0;
12375}
12376
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012377Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012378 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012379 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012380 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012381
Dan Gohman07a96762007-07-16 14:29:03 +000012382 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012383 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012384 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012385
Reid Spencer9d6565a2007-02-15 02:26:10 +000012386 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012387 // If vector val is constant with all elements the same, replace EI with
12388 // that element. When the elements are not identical, we cannot replace yet
12389 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012390 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012391 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012392 if (C->getOperand(i) != op0) {
12393 op0 = 0;
12394 break;
12395 }
12396 if (op0)
12397 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012398 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000012399
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012400 // If extracting a specified index from the vector, see if we can recursively
12401 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012402 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012403 unsigned IndexVal = IdxC->getZExtValue();
12404 unsigned VectorWidth =
12405 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12406
12407 // If this is extracting an invalid index, turn this into undef, to avoid
12408 // crashing the code below.
12409 if (IndexVal >= VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012410 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012411
Chris Lattner867b99f2006-10-05 06:55:50 +000012412 // This instruction only demands the single element from the input vector.
12413 // If the input vector has a single use, simplify it based on this use
12414 // property.
Chris Lattner85464092007-04-09 01:37:55 +000012415 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012416 APInt UndefElts(VectorWidth, 0);
12417 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012418 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012419 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012420 EI.setOperand(0, V);
12421 return &EI;
12422 }
12423 }
12424
Owen Andersond672ecb2009-07-03 00:17:18 +000012425 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012426 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012427
12428 // If the this extractelement is directly using a bitcast from a vector of
12429 // the same number of elements, see if we can find the source element from
12430 // it. In this case, we will end up needing to bitcast the scalars.
12431 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12432 if (const VectorType *VT =
12433 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12434 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012435 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12436 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012437 return new BitCastInst(Elt, EI.getType());
12438 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012439 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012440
Chris Lattner73fa49d2006-05-25 22:53:38 +000012441 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012442 if (I->hasOneUse()) {
12443 // Push extractelement into predecessor operation if legal and
12444 // profitable to do so
12445 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012446 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12447 if (CheapToScalarize(BO, isConstantElt)) {
12448 ExtractElementInst *newEI0 =
12449 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12450 EI.getName()+".lhs");
12451 ExtractElementInst *newEI1 =
12452 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12453 EI.getName()+".rhs");
12454 InsertNewInstBefore(newEI0, EI);
12455 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012456 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012457 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012458 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012459 unsigned AS =
12460 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012461 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +000012462 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012463 GetElementPtrInst *GEP =
12464 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012465 InsertNewInstBefore(GEP, EI);
12466 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012467 }
12468 }
12469 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12470 // Extracting the inserted element?
12471 if (IE->getOperand(2) == EI.getOperand(1))
12472 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12473 // If the inserted and extracted elements are constants, they must not
12474 // be the same value, extract from the pre-inserted value instead.
12475 if (isa<Constant>(IE->getOperand(2)) &&
12476 isa<Constant>(EI.getOperand(1))) {
12477 AddUsesToWorkList(EI);
12478 EI.setOperand(0, IE->getOperand(0));
12479 return &EI;
12480 }
12481 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12482 // If this is extracting an element from a shufflevector, figure out where
12483 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012484 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12485 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012486 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012487 unsigned LHSWidth =
12488 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12489
12490 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012491 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012492 else if (SrcIdx < LHSWidth*2) {
12493 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012494 Src = SVI->getOperand(1);
12495 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012496 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012497 }
Chris Lattner867b99f2006-10-05 06:55:50 +000012498 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012499 }
12500 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012501 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012502 return 0;
12503}
12504
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012505/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12506/// elements from either LHS or RHS, return the shuffle mask and true.
12507/// Otherwise, return false.
12508static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012509 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012510 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012511 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12512 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012513 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012514
12515 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012516 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012517 return true;
12518 } else if (V == LHS) {
12519 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012520 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012521 return true;
12522 } else if (V == RHS) {
12523 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012524 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012525 return true;
12526 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12527 // If this is an insert of an extract from some other vector, include it.
12528 Value *VecOp = IEI->getOperand(0);
12529 Value *ScalarOp = IEI->getOperand(1);
12530 Value *IdxOp = IEI->getOperand(2);
12531
Chris Lattnerd929f062006-04-27 21:14:21 +000012532 if (!isa<ConstantInt>(IdxOp))
12533 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012534 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012535
12536 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12537 // Okay, we can handle this if the vector we are insertinting into is
12538 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012539 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012540 // If so, update the mask to reflect the inserted undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012541 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012542 return true;
12543 }
12544 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12545 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012546 EI->getOperand(0)->getType() == V->getType()) {
12547 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012548 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012549
12550 // This must be extracting from either LHS or RHS.
12551 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12552 // Okay, we can handle this if the vector we are insertinting into is
12553 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012554 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012555 // If so, update the mask to reflect the inserted value.
12556 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012557 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012558 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012559 } else {
12560 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012561 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012562 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012563
12564 }
12565 return true;
12566 }
12567 }
12568 }
12569 }
12570 }
12571 // TODO: Handle shufflevector here!
12572
12573 return false;
12574}
12575
12576/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12577/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12578/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012579static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012580 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012581 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012582 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012583 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012584 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012585
12586 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012587 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012588 return V;
12589 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012590 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012591 return V;
12592 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12593 // If this is an insert of an extract from some other vector, include it.
12594 Value *VecOp = IEI->getOperand(0);
12595 Value *ScalarOp = IEI->getOperand(1);
12596 Value *IdxOp = IEI->getOperand(2);
12597
12598 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12599 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12600 EI->getOperand(0)->getType() == V->getType()) {
12601 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012602 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12603 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012604
12605 // Either the extracted from or inserted into vector must be RHSVec,
12606 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012607 if (EI->getOperand(0) == RHS || RHS == 0) {
12608 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012609 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012610 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012611 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012612 return V;
12613 }
12614
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012615 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012616 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12617 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012618 // Everything but the extracted element is replaced with the RHS.
12619 for (unsigned i = 0; i != NumElts; ++i) {
12620 if (i != InsertedIdx)
Owen Andersond672ecb2009-07-03 00:17:18 +000012621 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012622 }
12623 return V;
12624 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012625
12626 // If this insertelement is a chain that comes from exactly these two
12627 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012628 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12629 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012630 return EI->getOperand(0);
12631
Chris Lattnerefb47352006-04-15 01:39:45 +000012632 }
12633 }
12634 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012635 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012636
12637 // Otherwise, can't do anything fancy. Return an identity vector.
12638 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012639 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012640 return V;
12641}
12642
12643Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12644 Value *VecOp = IE.getOperand(0);
12645 Value *ScalarOp = IE.getOperand(1);
12646 Value *IdxOp = IE.getOperand(2);
12647
Chris Lattner599ded12007-04-09 01:11:16 +000012648 // Inserting an undef or into an undefined place, remove this.
12649 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12650 ReplaceInstUsesWith(IE, VecOp);
12651
Chris Lattnerefb47352006-04-15 01:39:45 +000012652 // If the inserted element was extracted from some other vector, and if the
12653 // indexes are constant, try to turn this into a shufflevector operation.
12654 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12655 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12656 EI->getOperand(0)->getType() == IE.getType()) {
12657 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012658 unsigned ExtractedIdx =
12659 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012660 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012661
12662 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12663 return ReplaceInstUsesWith(IE, VecOp);
12664
12665 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersond672ecb2009-07-03 00:17:18 +000012666 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012667
12668 // If we are extracting a value from a vector, then inserting it right
12669 // back into the same place, just use the input vector.
12670 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12671 return ReplaceInstUsesWith(IE, VecOp);
12672
12673 // We could theoretically do this for ANY input. However, doing so could
12674 // turn chains of insertelement instructions into a chain of shufflevector
12675 // instructions, and right now we do not merge shufflevectors. As such,
12676 // only do this in a situation where it is clear that there is benefit.
12677 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12678 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12679 // the values of VecOp, except then one read from EIOp0.
12680 // Build a new shuffle mask.
12681 std::vector<Constant*> Mask;
12682 if (isa<UndefValue>(VecOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000012683 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012684 else {
12685 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersond672ecb2009-07-03 00:17:18 +000012686 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012687 NumVectorElts));
12688 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012689 Mask[InsertedIdx] =
12690 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012691 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersond672ecb2009-07-03 00:17:18 +000012692 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012693 }
12694
12695 // If this insertelement isn't used by some other insertelement, turn it
12696 // (and any insertelements it points to), into one big shuffle.
12697 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12698 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012699 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012700 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12701 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012702 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012703 return new ShuffleVectorInst(LHS, RHS,
12704 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012705 }
12706 }
12707 }
12708
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012709 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12710 APInt UndefElts(VWidth, 0);
12711 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12712 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12713 return &IE;
12714
Chris Lattnerefb47352006-04-15 01:39:45 +000012715 return 0;
12716}
12717
12718
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012719Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12720 Value *LHS = SVI.getOperand(0);
12721 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012722 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012723
12724 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012725
Chris Lattner867b99f2006-10-05 06:55:50 +000012726 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012727 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012728 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012729
Dan Gohman488fbfc2008-09-09 18:11:14 +000012730 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012731
12732 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12733 return 0;
12734
Evan Cheng388df622009-02-03 10:05:09 +000012735 APInt UndefElts(VWidth, 0);
12736 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12737 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012738 LHS = SVI.getOperand(0);
12739 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012740 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012741 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012742
Chris Lattner863bcff2006-05-25 23:48:38 +000012743 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12744 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12745 if (LHS == RHS || isa<UndefValue>(LHS)) {
12746 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012747 // shuffle(undef,undef,mask) -> undef.
12748 return ReplaceInstUsesWith(SVI, LHS);
12749 }
12750
Chris Lattner863bcff2006-05-25 23:48:38 +000012751 // Remap any references to RHS to use LHS.
12752 std::vector<Constant*> Elts;
12753 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012754 if (Mask[i] >= 2*e)
Owen Andersond672ecb2009-07-03 00:17:18 +000012755 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012756 else {
12757 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012758 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012759 Mask[i] = 2*e; // Turn into undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012760 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012761 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012762 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersond672ecb2009-07-03 00:17:18 +000012763 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012764 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012765 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012766 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012767 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +000012768 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12769 SVI.setOperand(2, Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012770 LHS = SVI.getOperand(0);
12771 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012772 MadeChange = true;
12773 }
12774
Chris Lattner7b2e27922006-05-26 00:29:06 +000012775 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012776 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012777
Chris Lattner863bcff2006-05-25 23:48:38 +000012778 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12779 if (Mask[i] >= e*2) continue; // Ignore undef values.
12780 // Is this an identity shuffle of the LHS value?
12781 isLHSID &= (Mask[i] == i);
12782
12783 // Is this an identity shuffle of the RHS value?
12784 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012785 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012786
Chris Lattner863bcff2006-05-25 23:48:38 +000012787 // Eliminate identity shuffles.
12788 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12789 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012790
Chris Lattner7b2e27922006-05-26 00:29:06 +000012791 // If the LHS is a shufflevector itself, see if we can combine it with this
12792 // one without producing an unusual shuffle. Here we are really conservative:
12793 // we are absolutely afraid of producing a shuffle mask not in the input
12794 // program, because the code gen may not be smart enough to turn a merged
12795 // shuffle into two specific shuffles: it may produce worse code. As such,
12796 // we only merge two shuffles if the result is one of the two input shuffle
12797 // masks. In this case, merging the shuffles just removes one instruction,
12798 // which we know is safe. This is good for things like turning:
12799 // (splat(splat)) -> splat.
12800 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12801 if (isa<UndefValue>(RHS)) {
12802 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12803
12804 std::vector<unsigned> NewMask;
12805 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12806 if (Mask[i] >= 2*e)
12807 NewMask.push_back(2*e);
12808 else
12809 NewMask.push_back(LHSMask[Mask[i]]);
12810
12811 // If the result mask is equal to the src shuffle or this shuffle mask, do
12812 // the replacement.
12813 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012814 unsigned LHSInNElts =
12815 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012816 std::vector<Constant*> Elts;
12817 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012818 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012819 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012820 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012821 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012822 }
12823 }
12824 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12825 LHSSVI->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +000012826 Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012827 }
12828 }
12829 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012830
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012831 return MadeChange ? &SVI : 0;
12832}
12833
12834
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012835
Chris Lattnerea1c4542004-12-08 23:43:58 +000012836
12837/// TryToSinkInstruction - Try to move the specified instruction from its
12838/// current block into the beginning of DestBlock, which can only happen if it's
12839/// safe to move the instruction past all of the instructions between it and the
12840/// end of its block.
12841static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12842 assert(I->hasOneUse() && "Invariants didn't hold!");
12843
Chris Lattner108e9022005-10-27 17:13:11 +000012844 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012845 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012846 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012847
Chris Lattnerea1c4542004-12-08 23:43:58 +000012848 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012849 if (isa<AllocaInst>(I) && I->getParent() ==
12850 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012851 return false;
12852
Chris Lattner96a52a62004-12-09 07:14:34 +000012853 // We can only sink load instructions if there is nothing between the load and
12854 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012855 if (I->mayReadFromMemory()) {
12856 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012857 Scan != E; ++Scan)
12858 if (Scan->mayWriteToMemory())
12859 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012860 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012861
Dan Gohman02dea8b2008-05-23 21:05:58 +000012862 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012863
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012864 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012865 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012866 ++NumSunkInst;
12867 return true;
12868}
12869
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012870
12871/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12872/// all reachable code to the worklist.
12873///
12874/// This has a couple of tricks to make the code faster and more powerful. In
12875/// particular, we constant fold and DCE instructions as we go, to avoid adding
12876/// them to the worklist (this significantly speeds up instcombine on code where
12877/// many instructions are dead or constant). Additionally, if we find a branch
12878/// whose condition is a known constant, we only visit the reachable successors.
12879///
12880static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012881 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012882 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012883 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012884 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012885 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012886
Chris Lattner2c7718a2007-03-23 19:17:18 +000012887 while (!Worklist.empty()) {
12888 BB = Worklist.back();
12889 Worklist.pop_back();
12890
12891 // We have now visited this block! If we've already been here, ignore it.
12892 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012893
12894 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012895 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12896 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012897
Chris Lattner2c7718a2007-03-23 19:17:18 +000012898 // DCE instruction if trivially dead.
12899 if (isInstructionTriviallyDead(Inst)) {
12900 ++NumDeadInst;
12901 DOUT << "IC: DCE: " << *Inst;
12902 Inst->eraseFromParent();
12903 continue;
12904 }
12905
12906 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012907 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012908 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12909 Inst->replaceAllUsesWith(C);
12910 ++NumConstProp;
12911 Inst->eraseFromParent();
12912 continue;
12913 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012914
Devang Patel7fe1dec2008-11-19 18:56:50 +000012915 // If there are two consecutive llvm.dbg.stoppoint calls then
12916 // it is likely that the optimizer deleted code in between these
12917 // two intrinsics.
12918 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12919 if (DBI_Next) {
12920 if (DBI_Prev
12921 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12922 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12923 IC.RemoveFromWorkList(DBI_Prev);
12924 DBI_Prev->eraseFromParent();
12925 }
12926 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012927 } else {
12928 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012929 }
12930
Chris Lattner2c7718a2007-03-23 19:17:18 +000012931 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012932 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012933
12934 // Recursively visit successors. If this is a branch or switch on a
12935 // constant, only visit the reachable successor.
12936 TerminatorInst *TI = BB->getTerminator();
12937 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12938 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12939 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012940 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012941 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012942 continue;
12943 }
12944 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12945 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12946 // See if this is an explicit destination.
12947 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12948 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012949 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012950 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012951 continue;
12952 }
12953
12954 // Otherwise it is the default destination.
12955 Worklist.push_back(SI->getSuccessor(0));
12956 continue;
12957 }
12958 }
12959
12960 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12961 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012962 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012963}
12964
Chris Lattnerec9c3582007-03-03 02:04:50 +000012965bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012966 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012967 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012968
12969 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12970 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012971
Chris Lattnerb3d59702005-07-07 20:40:38 +000012972 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012973 // Do a depth-first traversal of the function, populate the worklist with
12974 // the reachable instructions. Ignore blocks that are not reachable. Keep
12975 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012976 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012977 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012978
Chris Lattnerb3d59702005-07-07 20:40:38 +000012979 // Do a quick scan over the function. If we find any blocks that are
12980 // unreachable, remove any instructions inside of them. This prevents
12981 // the instcombine code from having to deal with some bad special cases.
12982 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12983 if (!Visited.count(BB)) {
12984 Instruction *Term = BB->getTerminator();
12985 while (Term != BB->begin()) { // Remove instrs bottom-up
12986 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012987
Bill Wendlingb7427032006-11-26 09:46:52 +000012988 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012989 // A debug intrinsic shouldn't force another iteration if we weren't
12990 // going to do one without it.
12991 if (!isa<DbgInfoIntrinsic>(I)) {
12992 ++NumDeadInst;
12993 Changed = true;
12994 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012995 if (!I->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000012996 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012997 I->eraseFromParent();
12998 }
12999 }
13000 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013001
Chris Lattnerdbab3862007-03-02 21:28:56 +000013002 while (!Worklist.empty()) {
13003 Instruction *I = RemoveOneFromWorkList();
13004 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013005
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013006 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013007 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013008 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000013009 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013010 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000013011 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013012
Bill Wendlingb7427032006-11-26 09:46:52 +000013013 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013014
13015 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013016 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013017 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013018 continue;
13019 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013020
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013021 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000013022 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013023 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013024
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013025 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013026 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000013027 ReplaceInstUsesWith(*I, C);
13028
Chris Lattner62b14df2002-09-02 04:59:56 +000013029 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013030 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013031 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013032 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013033 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000013034 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013035
Dan Gohman31e4c772009-05-07 19:43:39 +000013036 if (TD &&
13037 (I->getType()->getTypeID() == Type::VoidTyID ||
13038 I->isTrapping())) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013039 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000013040 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13041 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000013042 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13043 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000013044 if (NewC != CE) {
13045 i->set(NewC);
13046 Changed = true;
13047 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013048 }
13049
Chris Lattnerea1c4542004-12-08 23:43:58 +000013050 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013051 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013052 BasicBlock *BB = I->getParent();
13053 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13054 if (UserParent != BB) {
13055 bool UserIsSuccessor = false;
13056 // See if the user is one of our successors.
13057 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13058 if (*SI == UserParent) {
13059 UserIsSuccessor = true;
13060 break;
13061 }
13062
13063 // If the user is one of our immediate successors, and if that successor
13064 // only has us as a predecessors (we'd have to split the critical edge
13065 // otherwise), we can keep going.
13066 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13067 next(pred_begin(UserParent)) == pred_end(UserParent))
13068 // Okay, the CFG is simple enough, try to sink this instruction.
13069 Changed |= TryToSinkInstruction(I, UserParent);
13070 }
13071 }
13072
Chris Lattner8a2a3112001-12-14 16:52:21 +000013073 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013074#ifndef NDEBUG
13075 std::string OrigI;
13076#endif
13077 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013078 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013079 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013080 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013081 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013082 DOUT << "IC: Old = " << *I
13083 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013084
Chris Lattnerf523d062004-06-09 05:08:07 +000013085 // Everything uses the new instruction now.
13086 I->replaceAllUsesWith(Result);
13087
13088 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013089 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013090 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013091
Chris Lattner6934a042007-02-11 01:23:03 +000013092 // Move the name to the new instruction first.
13093 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013094
13095 // Insert the new instruction into the basic block...
13096 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013097 BasicBlock::iterator InsertPos = I;
13098
13099 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13100 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13101 ++InsertPos;
13102
13103 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013104
Chris Lattner00d51312004-05-01 23:27:23 +000013105 // Make sure that we reprocess all operands now that we reduced their
13106 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013107 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013108
Chris Lattnerf523d062004-06-09 05:08:07 +000013109 // Instructions can end up on the worklist more than once. Make sure
13110 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013111 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013112
13113 // Erase the old instruction.
13114 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013115 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013116#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013117 DOUT << "IC: Mod = " << OrigI
13118 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013119#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013120
Chris Lattner90ac28c2002-08-02 19:29:35 +000013121 // If the instruction was modified, it's possible that it is now dead.
13122 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013123 if (isInstructionTriviallyDead(I)) {
13124 // Make sure we process all operands now that we are reducing their
13125 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013126 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013127
Chris Lattner00d51312004-05-01 23:27:23 +000013128 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013129 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013130 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013131 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013132 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013133 AddToWorkList(I);
13134 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013135 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013136 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013137 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013138 }
13139 }
13140
Chris Lattnerec9c3582007-03-03 02:04:50 +000013141 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013142
13143 // Do an explicit clear, this shrinks the map if needed.
13144 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013145 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013146}
13147
Chris Lattnerec9c3582007-03-03 02:04:50 +000013148
13149bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013150 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13151
Chris Lattnerec9c3582007-03-03 02:04:50 +000013152 bool EverMadeChange = false;
13153
13154 // Iterate while there is work to do.
13155 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013156 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013157 EverMadeChange = true;
13158 return EverMadeChange;
13159}
13160
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013161FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013162 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013163}