blob: 8b9c5999477967e39669faf29cfc0742cedd9d96 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000049#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000051#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000052#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000053#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000054#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000055#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000056#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000059#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000060#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000061#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000062#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000063using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000064using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000065
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000073 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000077 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000078 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000079 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000080 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000081 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000082 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000083 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000084
Chris Lattnerdbab3862007-03-02 21:28:56 +000085 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000089 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000109
Chris Lattnerdbab3862007-03-02 21:28:56 +0000110
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000115 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000118 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000119 }
120
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000127 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000128 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greif177dd3f2008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000141 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000142 // Set the operand to undef to drop the use.
Gabor Greif177dd3f2008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000144 }
145
146 return R;
147 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000148
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000149 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000150 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000151
152 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000153
Chris Lattner97e52e42002-04-28 21:27:06 +0000154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000155 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000156 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000157 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000158 }
159
Chris Lattner28977af2004-04-05 01:30:19 +0000160 TargetData &getTargetData() const { return *TD; }
161
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000166 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000168 //
Chris Lattner7e708292002-06-25 16:13:24 +0000169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000175 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000183 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000184 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000185 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000186 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000187 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000188 Instruction *visitOr (BinaryOperator &I);
189 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000190 Instruction *visitShl(BinaryOperator &I);
191 Instruction *visitAShr(BinaryOperator &I);
192 Instruction *visitLShr(BinaryOperator &I);
193 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000194 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
195 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000196 Instruction *visitFCmpInst(FCmpInst &I);
197 Instruction *visitICmpInst(ICmpInst &I);
198 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000199 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
200 Instruction *LHS,
201 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000202 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000204
Reid Spencere4d87aa2006-12-23 06:05:41 +0000205 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000207 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000208 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000209 Instruction *commonCastTransforms(CastInst &CI);
210 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000211 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000212 Instruction *visitTrunc(TruncInst &CI);
213 Instruction *visitZExt(ZExtInst &CI);
214 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000215 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000216 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000217 Instruction *visitFPToUI(FPToUIInst &FI);
218 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000219 Instruction *visitUIToFP(CastInst &CI);
220 Instruction *visitSIToFP(CastInst &CI);
221 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000222 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000223 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000224 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225 Instruction *FI);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000226 Instruction *visitSelectInst(SelectInst &SI);
227 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000228 Instruction *visitCallInst(CallInst &CI);
229 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000230 Instruction *visitPHINode(PHINode &PN);
231 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000232 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000233 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000234 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000235 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000236 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000237 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000238 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000239 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000240 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000241 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000242
243 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000244 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000245
Chris Lattner9fe38862003-06-19 17:00:31 +0000246 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000247 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000248 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000249 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000250 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000252 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000253
Chris Lattner28977af2004-04-05 01:30:19 +0000254 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000255 // InsertNewInstBefore - insert an instruction New before instruction Old
256 // in the program. Add the new instruction to the worklist.
257 //
Chris Lattner955f3312004-09-28 21:48:02 +0000258 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000259 assert(New && New->getParent() == 0 &&
260 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000261 BasicBlock *BB = Old.getParent();
262 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000263 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000264 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000265 }
266
Chris Lattner0c967662004-09-24 15:21:34 +0000267 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
268 /// This also adds the cast to the worklist. Finally, this returns the
269 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000270 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
271 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000272 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000273
Chris Lattnere2ed0572006-04-06 19:19:17 +0000274 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000275 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000276
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000277 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000278 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000279 return C;
280 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000281
282 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
283 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
284 }
285
Chris Lattner0c967662004-09-24 15:21:34 +0000286
Chris Lattner8b170942002-08-09 23:47:40 +0000287 // ReplaceInstUsesWith - This method is to be used when an instruction is
288 // found to be dead, replacable with another preexisting expression. Here
289 // we add all uses of I to the worklist, replace all uses of I with the new
290 // value, then return I, so that the inst combiner will know that I was
291 // modified.
292 //
293 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000294 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000295 if (&I != V) {
296 I.replaceAllUsesWith(V);
297 return &I;
298 } else {
299 // If we are replacing the instruction with itself, this must be in a
300 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000301 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000302 return &I;
303 }
Chris Lattner8b170942002-08-09 23:47:40 +0000304 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000305
306 // EraseInstFromFunction - When dealing with an instruction that has side
307 // effects or produces a void value, we can't rely on DCE to delete the
308 // instruction. Instead, visit methods should return the value returned by
309 // this function.
310 Instruction *EraseInstFromFunction(Instruction &I) {
311 assert(I.use_empty() && "Cannot erase instruction that is used!");
312 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000313 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000314 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000315 return 0; // Don't do anything with FI
316 }
Chris Lattner173234a2008-06-02 01:18:21 +0000317
318 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
319 APInt &KnownOne, unsigned Depth = 0) const {
320 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
321 }
322
323 bool MaskedValueIsZero(Value *V, const APInt &Mask,
324 unsigned Depth = 0) const {
325 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
326 }
327 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
328 return llvm::ComputeNumSignBits(Op, TD, Depth);
329 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000330
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000331 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000332
Reid Spencere4d87aa2006-12-23 06:05:41 +0000333 /// SimplifyCommutative - This performs a few simplifications for
334 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000335 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000336
Reid Spencere4d87aa2006-12-23 06:05:41 +0000337 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338 /// most-complex to least-complex order.
339 bool SimplifyCompare(CmpInst &I);
340
Chris Lattner886ab6c2009-01-31 08:15:18 +0000341 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
342 /// based on the demanded bits.
343 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
344 APInt& KnownZero, APInt& KnownOne,
345 unsigned Depth);
346 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000347 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000348 unsigned Depth=0);
349
350 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
351 /// SimplifyDemandedBits knows about. See if the instruction has any
352 /// properties that allow us to simplify its operands.
353 bool SimplifyDemandedInstructionBits(Instruction &Inst);
354
Chris Lattner867b99f2006-10-05 06:55:50 +0000355 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
356 uint64_t &UndefElts, unsigned Depth = 0);
357
Chris Lattner4e998b22004-09-29 05:07:12 +0000358 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
359 // PHI node as operand #0, see if we can fold the instruction into the PHI
360 // (which is only possible if all operands to the PHI are constants).
361 Instruction *FoldOpIntoPhi(Instruction &I);
362
Chris Lattnerbac32862004-11-14 19:13:23 +0000363 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
364 // operator and they all are only used by the PHI, PHI together their
365 // inputs, and do the operation once, to the result of the PHI.
366 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000367 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000368 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
369
Chris Lattner7da52b22006-11-01 04:51:18 +0000370
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000371 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
372 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000373
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000374 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000375 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000376 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000377 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000378 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000379 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000380 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000381 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000382 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000383
Chris Lattnerafe91a52006-06-15 19:07:26 +0000384
Reid Spencerc55b2432006-12-13 18:21:21 +0000385 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000386
Dan Gohmaneee962e2008-04-10 18:43:06 +0000387 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000388 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000389 unsigned GetOrEnforceKnownAlignment(Value *V,
390 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000391
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000392 };
393}
394
Dan Gohman844731a2008-05-13 00:00:25 +0000395char InstCombiner::ID = 0;
396static RegisterPass<InstCombiner>
397X("instcombine", "Combine redundant instructions");
398
Chris Lattner4f98c562003-03-10 21:43:22 +0000399// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000400// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000401static unsigned getComplexity(Value *V) {
402 if (isa<Instruction>(V)) {
403 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000404 return 3;
405 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000406 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000407 if (isa<Argument>(V)) return 3;
408 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000409}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000410
Chris Lattnerc8802d22003-03-11 00:12:48 +0000411// isOnlyUse - Return true if this instruction will be deleted if we stop using
412// it.
413static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000414 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000415}
416
Chris Lattner4cb170c2004-02-23 06:38:22 +0000417// getPromotedType - Return the specified type promoted as it would be to pass
418// though a va_arg area...
419static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000420 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
421 if (ITy->getBitWidth() < 32)
422 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000423 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000424 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000425}
426
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000427/// getBitCastOperand - If the specified operand is a CastInst, a constant
428/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
429/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000430static Value *getBitCastOperand(Value *V) {
431 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000432 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000433 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000434 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
435 // GetElementPtrInst?
436 if (GEP->hasAllZeroIndices())
437 return GEP->getOperand(0);
438 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000439 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000440 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000441 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000442 else if (CE->getOpcode() == Instruction::GetElementPtr) {
443 // GetElementPtr ConstantExp?
444 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
445 I != E; ++I) {
446 ConstantInt *CI = dyn_cast<ConstantInt>(I);
447 if (!CI || !CI->isZero())
448 // Any non-zero indices? Not cast-like.
449 return 0;
450 }
451 // All-zero indices? This is just like casting.
452 return CE->getOperand(0);
453 }
454 }
Chris Lattnereed48272005-09-13 00:40:14 +0000455 return 0;
456}
457
Reid Spencer3da59db2006-11-27 01:05:10 +0000458/// This function is a wrapper around CastInst::isEliminableCastPair. It
459/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000460static Instruction::CastOps
461isEliminableCastPair(
462 const CastInst *CI, ///< The first cast instruction
463 unsigned opcode, ///< The opcode of the second cast instruction
464 const Type *DstTy, ///< The target type for the second cast instruction
465 TargetData *TD ///< The target data for pointer size
466) {
467
468 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
469 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000470
Reid Spencer3da59db2006-11-27 01:05:10 +0000471 // Get the opcodes of the two Cast instructions
472 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
473 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000474
Reid Spencer3da59db2006-11-27 01:05:10 +0000475 return Instruction::CastOps(
476 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
477 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000478}
479
480/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
481/// in any code being generated. It does not require codegen if V is simple
482/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000483static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
484 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000485 if (V->getType() == Ty || isa<Constant>(V)) return false;
486
Chris Lattner01575b72006-05-25 23:24:33 +0000487 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000488 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000489 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000490 return false;
491 return true;
492}
493
Chris Lattner4f98c562003-03-10 21:43:22 +0000494// SimplifyCommutative - This performs a few simplifications for commutative
495// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000496//
Chris Lattner4f98c562003-03-10 21:43:22 +0000497// 1. Order operands such that they are listed from right (least complex) to
498// left (most complex). This puts constants before unary operators before
499// binary operators.
500//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000501// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
502// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000503//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000504bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000505 bool Changed = false;
506 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
507 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000508
Chris Lattner4f98c562003-03-10 21:43:22 +0000509 if (!I.isAssociative()) return Changed;
510 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000511 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
512 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
513 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000514 Constant *Folded = ConstantExpr::get(I.getOpcode(),
515 cast<Constant>(I.getOperand(1)),
516 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000517 I.setOperand(0, Op->getOperand(0));
518 I.setOperand(1, Folded);
519 return true;
520 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
521 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
522 isOnlyUse(Op) && isOnlyUse(Op1)) {
523 Constant *C1 = cast<Constant>(Op->getOperand(1));
524 Constant *C2 = cast<Constant>(Op1->getOperand(1));
525
526 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000527 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000528 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000529 Op1->getOperand(0),
530 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000531 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000532 I.setOperand(0, New);
533 I.setOperand(1, Folded);
534 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000535 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000536 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000537 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000538}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000539
Reid Spencere4d87aa2006-12-23 06:05:41 +0000540/// SimplifyCompare - For a CmpInst this function just orders the operands
541/// so that theyare listed from right (least complex) to left (most complex).
542/// This puts constants before unary operators before binary operators.
543bool InstCombiner::SimplifyCompare(CmpInst &I) {
544 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
545 return false;
546 I.swapOperands();
547 // Compare instructions are not associative so there's nothing else we can do.
548 return true;
549}
550
Chris Lattner8d969642003-03-10 23:06:50 +0000551// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
552// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000553//
Chris Lattner8d969642003-03-10 23:06:50 +0000554static inline Value *dyn_castNegVal(Value *V) {
555 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000556 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000557
Chris Lattner0ce85802004-12-14 20:08:06 +0000558 // Constants can be considered to be negated values if they can be folded.
559 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
560 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000561
562 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
563 if (C->getType()->getElementType()->isInteger())
564 return ConstantExpr::getNeg(C);
565
Chris Lattner8d969642003-03-10 23:06:50 +0000566 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000567}
568
Chris Lattner8d969642003-03-10 23:06:50 +0000569static inline Value *dyn_castNotVal(Value *V) {
570 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000571 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000572
573 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000574 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000575 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000576 return 0;
577}
578
Chris Lattnerc8802d22003-03-11 00:12:48 +0000579// dyn_castFoldableMul - If this value is a multiply that can be folded into
580// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000581// non-constant operand of the multiply, and set CST to point to the multiplier.
582// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000583//
Chris Lattner50af16a2004-11-13 19:50:12 +0000584static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000585 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000586 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000587 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000588 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000589 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000590 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000591 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000592 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000593 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000594 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000595 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000596 return I->getOperand(0);
597 }
598 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000599 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000600}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000601
Chris Lattner574da9b2005-01-13 20:14:25 +0000602/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
603/// expression, return it.
604static User *dyn_castGetElementPtr(Value *V) {
605 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
606 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
607 if (CE->getOpcode() == Instruction::GetElementPtr)
608 return cast<User>(V);
609 return false;
610}
611
Dan Gohmaneee962e2008-04-10 18:43:06 +0000612/// getOpcode - If this is an Instruction or a ConstantExpr, return the
613/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000614static unsigned getOpcode(const Value *V) {
615 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000616 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000617 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000618 return CE->getOpcode();
619 // Use UserOp1 to mean there's no opcode.
620 return Instruction::UserOp1;
621}
622
Reid Spencer7177c3a2007-03-25 05:33:51 +0000623/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000624static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000625 APInt Val(C->getValue());
626 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000627}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000628/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000629static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000630 APInt Val(C->getValue());
631 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000632}
633/// Add - Add two ConstantInts together
634static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
635 return ConstantInt::get(C1->getValue() + C2->getValue());
636}
637/// And - Bitwise AND two ConstantInts together
638static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() & C2->getValue());
640}
641/// Subtract - Subtract one ConstantInt from another
642static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
643 return ConstantInt::get(C1->getValue() - C2->getValue());
644}
645/// Multiply - Multiply two ConstantInts together
646static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
647 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000648}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000649/// MultiplyOverflows - True if the multiply can not be expressed in an int
650/// this size.
651static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
652 uint32_t W = C1->getBitWidth();
653 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
654 if (sign) {
655 LHSExt.sext(W * 2);
656 RHSExt.sext(W * 2);
657 } else {
658 LHSExt.zext(W * 2);
659 RHSExt.zext(W * 2);
660 }
661
662 APInt MulExt = LHSExt * RHSExt;
663
664 if (sign) {
665 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
666 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
667 return MulExt.slt(Min) || MulExt.sgt(Max);
668 } else
669 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
670}
Chris Lattner955f3312004-09-28 21:48:02 +0000671
Reid Spencere7816b52007-03-08 01:52:58 +0000672
Chris Lattner255d8912006-02-11 09:31:47 +0000673/// ShrinkDemandedConstant - Check to see if the specified operand of the
674/// specified instruction is a constant integer. If so, check to see if there
675/// are any bits set in the constant that are not demanded. If so, shrink the
676/// constant and return true.
677static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000678 APInt Demanded) {
679 assert(I && "No instruction?");
680 assert(OpNo < I->getNumOperands() && "Operand index too large");
681
682 // If the operand is not a constant integer, nothing to do.
683 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
684 if (!OpC) return false;
685
686 // If there are no bits set that aren't demanded, nothing to do.
687 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
688 if ((~Demanded & OpC->getValue()) == 0)
689 return false;
690
691 // This instruction is producing bits that are not demanded. Shrink the RHS.
692 Demanded &= OpC->getValue();
693 I->setOperand(OpNo, ConstantInt::get(Demanded));
694 return true;
695}
696
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000697// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
698// set of known zero and one bits, compute the maximum and minimum values that
699// could have the specified known zero and known one bits, returning them in
700// min/max.
701static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000702 const APInt& KnownZero,
703 const APInt& KnownOne,
704 APInt& Min, APInt& Max) {
705 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
706 assert(KnownZero.getBitWidth() == BitWidth &&
707 KnownOne.getBitWidth() == BitWidth &&
708 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
709 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000710 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000711
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000712 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
713 // bit if it is unknown.
714 Min = KnownOne;
715 Max = KnownOne|UnknownBits;
716
Zhou Sheng4acf1552007-03-28 05:15:57 +0000717 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000718 Min.set(BitWidth-1);
719 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000720 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000721}
722
723// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
724// a set of known zero and one bits, compute the maximum and minimum values that
725// could have the specified known zero and known one bits, returning them in
726// min/max.
727static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000728 const APInt &KnownZero,
729 const APInt &KnownOne,
730 APInt &Min, APInt &Max) {
731 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000732 assert(KnownZero.getBitWidth() == BitWidth &&
733 KnownOne.getBitWidth() == BitWidth &&
734 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
735 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000736 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000737
738 // The minimum value is when the unknown bits are all zeros.
739 Min = KnownOne;
740 // The maximum value is when the unknown bits are all ones.
741 Max = KnownOne|UnknownBits;
742}
Chris Lattner255d8912006-02-11 09:31:47 +0000743
Chris Lattner886ab6c2009-01-31 08:15:18 +0000744/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
745/// SimplifyDemandedBits knows about. See if the instruction has any
746/// properties that allow us to simplify its operands.
747bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
748 unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
749 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
750 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
751
752 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
753 KnownZero, KnownOne, 0);
754 if (V == 0) return false;
755 if (V == &Inst) return true;
756 ReplaceInstUsesWith(Inst, V);
757 return true;
758}
759
760/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
761/// specified instruction operand if possible, updating it in place. It returns
762/// true if it made any change and false otherwise.
763bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
764 APInt &KnownZero, APInt &KnownOne,
765 unsigned Depth) {
766 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
767 KnownZero, KnownOne, Depth);
768 if (NewVal == 0) return false;
769 U.set(NewVal);
770 return true;
771}
772
773
774/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
775/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000776/// that only the bits set in DemandedMask of the result of V are ever used
777/// downstream. Consequently, depending on the mask and V, it may be possible
778/// to replace V with a constant or one of its operands. In such cases, this
779/// function does the replacement and returns true. In all other cases, it
780/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000781/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000782/// to be zero in the expression. These are provided to potentially allow the
783/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
784/// the expression. KnownOne and KnownZero always follow the invariant that
785/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
786/// the bits in KnownOne and KnownZero may only be accurate for those bits set
787/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
788/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000789///
790/// This returns null if it did not change anything and it permits no
791/// simplification. This returns V itself if it did some simplification of V's
792/// operands based on the information about what bits are demanded. This returns
793/// some other non-null value if it found out that V is equal to another value
794/// in the context where the specified bits are demanded, but not for all users.
795Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
796 APInt &KnownZero, APInt &KnownOne,
797 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000798 assert(V != 0 && "Null pointer of Value???");
799 assert(Depth <= 6 && "Limit Search Depth");
800 uint32_t BitWidth = DemandedMask.getBitWidth();
801 const IntegerType *VTy = cast<IntegerType>(V->getType());
802 assert(VTy->getBitWidth() == BitWidth &&
803 KnownZero.getBitWidth() == BitWidth &&
804 KnownOne.getBitWidth() == BitWidth &&
805 "Value *V, DemandedMask, KnownZero and KnownOne \
806 must have same BitWidth");
807 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
808 // We know all of the bits for a constant!
809 KnownOne = CI->getValue() & DemandedMask;
810 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000811 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000812 }
813
Chris Lattner08d2cc72009-01-31 07:26:06 +0000814 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000815 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000816 if (DemandedMask == 0) { // Not demanding any bits from V.
817 if (isa<UndefValue>(V))
818 return 0;
819 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000820 }
821
Chris Lattner4598c942009-01-31 08:24:16 +0000822 if (Depth == 6) // Limit search depth.
823 return 0;
824
Reid Spencer8cb68342007-03-12 17:25:59 +0000825 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000826 if (!I) return 0; // Only analyze instructions.
Chris Lattner4598c942009-01-31 08:24:16 +0000827
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000828 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
829 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
830
Chris Lattner4598c942009-01-31 08:24:16 +0000831 // If there are multiple uses of this value and we aren't at the root, then
832 // we can't do any simplifications of the operands, because DemandedMask
833 // only reflects the bits demanded by *one* of the users.
834 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000835 // Despite the fact that we can't simplify this instruction in all User's
836 // context, we can at least compute the knownzero/knownone bits, and we can
837 // do simplifications that apply to *just* the one user if we know that
838 // this instruction has a simpler value in that context.
839 if (I->getOpcode() == Instruction::And) {
840 // If either the LHS or the RHS are Zero, the result is zero.
841 ComputeMaskedBits(I->getOperand(1), DemandedMask,
842 RHSKnownZero, RHSKnownOne, Depth+1);
843 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
844 LHSKnownZero, LHSKnownOne, Depth+1);
845
846 // If all of the demanded bits are known 1 on one side, return the other.
847 // These bits cannot contribute to the result of the 'and' in this
848 // context.
849 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
850 (DemandedMask & ~LHSKnownZero))
851 return I->getOperand(0);
852 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
853 (DemandedMask & ~RHSKnownZero))
854 return I->getOperand(1);
855
856 // If all of the demanded bits in the inputs are known zeros, return zero.
857 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
858 return Constant::getNullValue(VTy);
859
860 } else if (I->getOpcode() == Instruction::Or) {
861 // We can simplify (X|Y) -> X or Y in the user's context if we know that
862 // only bits from X or Y are demanded.
863
864 // If either the LHS or the RHS are One, the result is One.
865 ComputeMaskedBits(I->getOperand(1), DemandedMask,
866 RHSKnownZero, RHSKnownOne, Depth+1);
867 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
868 LHSKnownZero, LHSKnownOne, Depth+1);
869
870 // If all of the demanded bits are known zero on one side, return the
871 // other. These bits cannot contribute to the result of the 'or' in this
872 // context.
873 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
874 (DemandedMask & ~LHSKnownOne))
875 return I->getOperand(0);
876 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
877 (DemandedMask & ~RHSKnownOne))
878 return I->getOperand(1);
879
880 // If all of the potentially set bits on one side are known to be set on
881 // the other side, just use the 'other' side.
882 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
883 (DemandedMask & (~RHSKnownZero)))
884 return I->getOperand(0);
885 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
886 (DemandedMask & (~LHSKnownZero)))
887 return I->getOperand(1);
888 }
889
Chris Lattner4598c942009-01-31 08:24:16 +0000890 // Compute the KnownZero/KnownOne bits to simplify things downstream.
891 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
892 return 0;
893 }
894
895 // If this is the root being simplified, allow it to have multiple uses,
896 // just set the DemandedMask to all bits so that we can try to simplify the
897 // operands. This allows visitTruncInst (for example) to simplify the
898 // operand of a trunc without duplicating all the logic below.
899 if (Depth == 0 && !V->hasOneUse())
900 DemandedMask = APInt::getAllOnesValue(BitWidth);
901
Reid Spencer8cb68342007-03-12 17:25:59 +0000902 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000903 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000904 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000905 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000906 case Instruction::And:
907 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000908 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
909 RHSKnownZero, RHSKnownOne, Depth+1) ||
910 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000911 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000912 return I;
913 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
914 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000915
916 // If all of the demanded bits are known 1 on one side, return the other.
917 // These bits cannot contribute to the result of the 'and'.
918 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
919 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000920 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000921 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
922 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000923 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000924
925 // If all of the demanded bits in the inputs are known zeros, return zero.
926 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000927 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000928
929 // If the RHS is a constant, see if we can simplify it.
930 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000931 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000932
933 // Output known-1 bits are only known if set in both the LHS & RHS.
934 RHSKnownOne &= LHSKnownOne;
935 // Output known-0 are known to be clear if zero in either the LHS | RHS.
936 RHSKnownZero |= LHSKnownZero;
937 break;
938 case Instruction::Or:
939 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000940 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
941 RHSKnownZero, RHSKnownOne, Depth+1) ||
942 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000943 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000944 return I;
945 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
946 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000947
948 // If all of the demanded bits are known zero on one side, return the other.
949 // These bits cannot contribute to the result of the 'or'.
950 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
951 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000952 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000953 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
954 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000955 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000956
957 // If all of the potentially set bits on one side are known to be set on
958 // the other side, just use the 'other' side.
959 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
960 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000961 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000962 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
963 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000964 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000965
966 // If the RHS is a constant, see if we can simplify it.
967 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000968 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000969
970 // Output known-0 bits are only known if clear in both the LHS & RHS.
971 RHSKnownZero &= LHSKnownZero;
972 // Output known-1 are known to be set if set in either the LHS | RHS.
973 RHSKnownOne |= LHSKnownOne;
974 break;
975 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
977 RHSKnownZero, RHSKnownOne, Depth+1) ||
978 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000979 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000980 return I;
981 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
982 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000983
984 // If all of the demanded bits are known zero on one side, return the other.
985 // These bits cannot contribute to the result of the 'xor'.
986 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000987 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000988 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000989 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000990
991 // Output known-0 bits are known if clear or set in both the LHS & RHS.
992 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
993 (RHSKnownOne & LHSKnownOne);
994 // Output known-1 are known to be set if set in only one of the LHS, RHS.
995 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
996 (RHSKnownOne & LHSKnownZero);
997
998 // If all of the demanded bits are known to be zero on one side or the
999 // other, turn this into an *inclusive* or.
1000 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1001 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1002 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001003 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001004 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001005 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001006 }
1007
1008 // If all of the demanded bits on one side are known, and all of the set
1009 // bits on that side are also known to be set on the other side, turn this
1010 // into an AND, as we know the bits will be cleared.
1011 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1012 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1013 // all known
1014 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1015 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1016 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001017 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001018 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001019 }
1020 }
1021
1022 // If the RHS is a constant, see if we can simplify it.
1023 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1024 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001025 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001026
1027 RHSKnownZero = KnownZeroOut;
1028 RHSKnownOne = KnownOneOut;
1029 break;
1030 }
1031 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001032 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1033 RHSKnownZero, RHSKnownOne, Depth+1) ||
1034 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001035 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001036 return I;
1037 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1038 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001039
1040 // If the operands are constants, see if we can simplify them.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001041 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1042 ShrinkDemandedConstant(I, 2, DemandedMask))
1043 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001044
1045 // Only known if known in both the LHS and RHS.
1046 RHSKnownOne &= LHSKnownOne;
1047 RHSKnownZero &= LHSKnownZero;
1048 break;
1049 case Instruction::Trunc: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001050 unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001051 DemandedMask.zext(truncBf);
1052 RHSKnownZero.zext(truncBf);
1053 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001054 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001055 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001057 DemandedMask.trunc(BitWidth);
1058 RHSKnownZero.trunc(BitWidth);
1059 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001061 break;
1062 }
1063 case Instruction::BitCast:
1064 if (!I->getOperand(0)->getType()->isInteger())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001065 return false; // vector->int or fp->int?
1066 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001067 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001068 return I;
1069 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001070 break;
1071 case Instruction::ZExt: {
1072 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001073 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001074
Zhou Shengd48653a2007-03-29 04:45:55 +00001075 DemandedMask.trunc(SrcBitWidth);
1076 RHSKnownZero.trunc(SrcBitWidth);
1077 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001079 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001080 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001081 DemandedMask.zext(BitWidth);
1082 RHSKnownZero.zext(BitWidth);
1083 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001084 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001085 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001086 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001087 break;
1088 }
1089 case Instruction::SExt: {
1090 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001091 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001092
Reid Spencer8cb68342007-03-12 17:25:59 +00001093 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001094 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001095
Zhou Sheng01542f32007-03-29 02:26:30 +00001096 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 // If any of the sign extended bits are demanded, we know that the sign
1098 // bit is demanded.
1099 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001100 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001101
Zhou Shengd48653a2007-03-29 04:45:55 +00001102 InputDemandedBits.trunc(SrcBitWidth);
1103 RHSKnownZero.trunc(SrcBitWidth);
1104 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001105 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001106 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001108 InputDemandedBits.zext(BitWidth);
1109 RHSKnownZero.zext(BitWidth);
1110 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001111 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001112
1113 // If the sign bit of the input is known set or clear, then we know the
1114 // top bits of the result.
1115
1116 // If the input sign bit is known zero, or if the NewBits are not demanded
1117 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001118 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001120 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1121 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001122 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001123 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001124 }
1125 break;
1126 }
1127 case Instruction::Add: {
1128 // Figure out what the input bits are. If the top bits of the and result
1129 // are not demanded, then the add doesn't demand them from its input
1130 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001131 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001132
1133 // If there is a constant on the RHS, there are a variety of xformations
1134 // we can do.
1135 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1136 // If null, this should be simplified elsewhere. Some of the xforms here
1137 // won't work if the RHS is zero.
1138 if (RHS->isZero())
1139 break;
1140
1141 // If the top bit of the output is demanded, demand everything from the
1142 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001143 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001144
1145 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001146 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001147 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001148 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001149
1150 // If the RHS of the add has bits set that can't affect the input, reduce
1151 // the constant.
1152 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001153 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001154
1155 // Avoid excess work.
1156 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1157 break;
1158
1159 // Turn it into OR if input bits are zero.
1160 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1161 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001162 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001163 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001164 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001165 }
1166
1167 // We can say something about the output known-zero and known-one bits,
1168 // depending on potential carries from the input constant and the
1169 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1170 // bits set and the RHS constant is 0x01001, then we know we have a known
1171 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1172
1173 // To compute this, we first compute the potential carry bits. These are
1174 // the bits which may be modified. I'm not aware of a better way to do
1175 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001176 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001177 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001178
1179 // Now that we know which bits have carries, compute the known-1/0 sets.
1180
1181 // Bits are known one if they are known zero in one operand and one in the
1182 // other, and there is no input carry.
1183 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1184 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1185
1186 // Bits are known zero if they are known zero in both operands and there
1187 // is no input carry.
1188 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1189 } else {
1190 // If the high-bits of this ADD are not demanded, then it does not demand
1191 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001192 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001193 // Right fill the mask of bits for this ADD to demand the most
1194 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001195 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001196 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1197 LHSKnownZero, LHSKnownOne, Depth+1) ||
1198 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001199 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001200 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001201 }
1202 }
1203 break;
1204 }
1205 case Instruction::Sub:
1206 // If the high-bits of this SUB are not demanded, then it does not demand
1207 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001208 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 // Right fill the mask of bits for this SUB to demand the most
1210 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001211 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001212 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001213 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1214 LHSKnownZero, LHSKnownOne, Depth+1) ||
1215 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001216 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001217 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001218 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001219 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1220 // the known zeros and ones.
1221 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001222 break;
1223 case Instruction::Shl:
1224 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001225 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001226 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001227 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001228 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001229 return I;
1230 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 RHSKnownZero <<= ShiftAmt;
1232 RHSKnownOne <<= ShiftAmt;
1233 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001234 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001235 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001236 }
1237 break;
1238 case Instruction::LShr:
1239 // For a logical shift right
1240 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001241 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001242
Reid Spencer8cb68342007-03-12 17:25:59 +00001243 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001244 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001245 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001246 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001247 return I;
1248 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001249 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1250 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001251 if (ShiftAmt) {
1252 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001253 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001254 RHSKnownZero |= HighBits; // high bits known zero.
1255 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001256 }
1257 break;
1258 case Instruction::AShr:
1259 // If this is an arithmetic shift right and only the low-bit is set, we can
1260 // always convert this into a logical shr, even if the shift amount is
1261 // variable. The low bit of the shift cannot be an input sign bit unless
1262 // the shift amount is >= the size of the datatype, which is undefined.
1263 if (DemandedMask == 1) {
1264 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001265 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001266 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001267 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001269
1270 // If the sign bit is the only bit demanded by this ashr, then there is no
1271 // need to do it, the shift doesn't change the high bit.
1272 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001273 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001274
1275 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001276 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001277
Reid Spencer8cb68342007-03-12 17:25:59 +00001278 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001279 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001280 // If any of the "high bits" are demanded, we should set the sign bit as
1281 // demanded.
1282 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1283 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001284 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001286 return I;
1287 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001289 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001290 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1291 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1292
1293 // Handle the sign bits.
1294 APInt SignBit(APInt::getSignBit(BitWidth));
1295 // Adjust to where it is now in the mask.
1296 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1297
1298 // If the input sign bit is known to be zero, or if none of the top bits
1299 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001300 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001301 (HighBits & ~DemandedMask) == HighBits) {
1302 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001303 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001304 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001305 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001306 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1307 RHSKnownOne |= HighBits;
1308 }
1309 }
1310 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001311 case Instruction::SRem:
1312 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001313 APInt RA = Rem->getValue().abs();
1314 if (RA.isPowerOf2()) {
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001315 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001316 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001317
Nick Lewycky8e394322008-11-02 02:41:50 +00001318 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001319 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001320 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001321 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001323
1324 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1325 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001326
1327 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001328
Chris Lattner886ab6c2009-01-31 08:15:18 +00001329 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001330 }
1331 }
1332 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001333 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001334 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1335 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001336 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1337 KnownZero2, KnownOne2, Depth+1) ||
1338 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001339 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001340 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001341
Chris Lattner455e9ab2009-01-21 18:09:24 +00001342 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001343 Leaders = std::max(Leaders,
1344 KnownZero2.countLeadingOnes());
1345 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001346 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001347 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001348 case Instruction::Call:
1349 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1350 switch (II->getIntrinsicID()) {
1351 default: break;
1352 case Intrinsic::bswap: {
1353 // If the only bits demanded come from one byte of the bswap result,
1354 // just shift the input byte into position to eliminate the bswap.
1355 unsigned NLZ = DemandedMask.countLeadingZeros();
1356 unsigned NTZ = DemandedMask.countTrailingZeros();
1357
1358 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1359 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1360 // have 14 leading zeros, round to 8.
1361 NLZ &= ~7;
1362 NTZ &= ~7;
1363 // If we need exactly one byte, we can do this transformation.
1364 if (BitWidth-NLZ-NTZ == 8) {
1365 unsigned ResultBit = NTZ;
1366 unsigned InputBit = BitWidth-NTZ-8;
1367
1368 // Replace this with either a left or right shift to get the byte into
1369 // the right place.
1370 Instruction *NewVal;
1371 if (InputBit > ResultBit)
1372 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1373 ConstantInt::get(I->getType(), InputBit-ResultBit));
1374 else
1375 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1376 ConstantInt::get(I->getType(), ResultBit-InputBit));
1377 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001378 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001379 }
1380
1381 // TODO: Could compute known zero/one bits based on the input.
1382 break;
1383 }
1384 }
1385 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001386 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001387 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001388 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001389
1390 // If the client is only demanding bits that we know, return the known
1391 // constant.
1392 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001393 return ConstantInt::get(RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001394 return false;
1395}
1396
Chris Lattner867b99f2006-10-05 06:55:50 +00001397
Mon P Wangaeb06d22008-11-10 04:46:22 +00001398/// SimplifyDemandedVectorElts - The specified value produces a vector with
Chris Lattner867b99f2006-10-05 06:55:50 +00001399/// 64 or fewer elements. DemandedElts contains the set of elements that are
1400/// actually used by the caller. This method analyzes which elements of the
1401/// operand are undef and returns that information in UndefElts.
1402///
1403/// If the information about demanded elements can be used to simplify the
1404/// operation, the operation is simplified, then the resultant value is
1405/// returned. This returns null if no change was made.
1406Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1407 uint64_t &UndefElts,
1408 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001409 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001410 assert(VWidth <= 64 && "Vector too wide to analyze!");
1411 uint64_t EltMask = ~0ULL >> (64-VWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001412 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001413
1414 if (isa<UndefValue>(V)) {
1415 // If the entire vector is undefined, just return this info.
1416 UndefElts = EltMask;
1417 return 0;
1418 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1419 UndefElts = EltMask;
1420 return UndefValue::get(V->getType());
1421 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001422
Chris Lattner867b99f2006-10-05 06:55:50 +00001423 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001424 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1425 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001426 Constant *Undef = UndefValue::get(EltTy);
1427
1428 std::vector<Constant*> Elts;
1429 for (unsigned i = 0; i != VWidth; ++i)
1430 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1431 Elts.push_back(Undef);
1432 UndefElts |= (1ULL << i);
1433 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1434 Elts.push_back(Undef);
1435 UndefElts |= (1ULL << i);
1436 } else { // Otherwise, defined.
1437 Elts.push_back(CP->getOperand(i));
1438 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001439
Chris Lattner867b99f2006-10-05 06:55:50 +00001440 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001441 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001442 return NewCP != CP ? NewCP : 0;
1443 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001444 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001445 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001446
1447 // Check if this is identity. If so, return 0 since we are not simplifying
1448 // anything.
1449 if (DemandedElts == ((1ULL << VWidth) -1))
1450 return 0;
1451
Reid Spencer9d6565a2007-02-15 02:26:10 +00001452 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001453 Constant *Zero = Constant::getNullValue(EltTy);
1454 Constant *Undef = UndefValue::get(EltTy);
1455 std::vector<Constant*> Elts;
1456 for (unsigned i = 0; i != VWidth; ++i)
1457 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1458 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001459 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001460 }
1461
Dan Gohman488fbfc2008-09-09 18:11:14 +00001462 // Limit search depth.
1463 if (Depth == 10)
1464 return false;
1465
1466 // If multiple users are using the root value, procede with
1467 // simplification conservatively assuming that all elements
1468 // are needed.
1469 if (!V->hasOneUse()) {
1470 // Quit if we find multiple users of a non-root value though.
1471 // They'll be handled when it's their turn to be visited by
1472 // the main instcombine process.
1473 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001474 // TODO: Just compute the UndefElts information recursively.
1475 return false;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001476
1477 // Conservatively assume that all elements are needed.
1478 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001479 }
1480
1481 Instruction *I = dyn_cast<Instruction>(V);
1482 if (!I) return false; // Only analyze instructions.
1483
1484 bool MadeChange = false;
1485 uint64_t UndefElts2;
1486 Value *TmpV;
1487 switch (I->getOpcode()) {
1488 default: break;
1489
1490 case Instruction::InsertElement: {
1491 // If this is a variable index, we don't know which element it overwrites.
1492 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001493 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001494 if (Idx == 0) {
1495 // Note that we can't propagate undef elt info, because we don't know
1496 // which elt is getting updated.
1497 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1498 UndefElts2, Depth+1);
1499 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1500 break;
1501 }
1502
1503 // If this is inserting an element that isn't demanded, remove this
1504 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001505 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001506 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1507 return AddSoonDeadInstToWorklist(*I, 0);
1508
1509 // Otherwise, the element inserted overwrites whatever was there, so the
1510 // input demanded set is simpler than the output set.
1511 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1512 DemandedElts & ~(1ULL << IdxNo),
1513 UndefElts, Depth+1);
1514 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1515
1516 // The inserted element is defined.
Dan Gohman488fbfc2008-09-09 18:11:14 +00001517 UndefElts &= ~(1ULL << IdxNo);
1518 break;
1519 }
1520 case Instruction::ShuffleVector: {
1521 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001522 uint64_t LHSVWidth =
1523 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Dan Gohman488fbfc2008-09-09 18:11:14 +00001524 uint64_t LeftDemanded = 0, RightDemanded = 0;
1525 for (unsigned i = 0; i < VWidth; i++) {
1526 if (DemandedElts & (1ULL << i)) {
1527 unsigned MaskVal = Shuffle->getMaskValue(i);
1528 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001529 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001530 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001531 if (MaskVal < LHSVWidth)
Dan Gohman488fbfc2008-09-09 18:11:14 +00001532 LeftDemanded |= 1ULL << MaskVal;
1533 else
Mon P Wangaeb06d22008-11-10 04:46:22 +00001534 RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001535 }
1536 }
1537 }
1538
1539 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1540 UndefElts2, Depth+1);
1541 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1542
1543 uint64_t UndefElts3;
1544 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1545 UndefElts3, Depth+1);
1546 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1547
1548 bool NewUndefElts = false;
1549 for (unsigned i = 0; i < VWidth; i++) {
1550 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001551 if (MaskVal == -1u) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001552 uint64_t NewBit = 1ULL << i;
1553 UndefElts |= NewBit;
Mon P Wangaeb06d22008-11-10 04:46:22 +00001554 } else if (MaskVal < LHSVWidth) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001555 uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1556 NewUndefElts |= NewBit;
1557 UndefElts |= NewBit;
1558 } else {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001559 uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001560 NewUndefElts |= NewBit;
1561 UndefElts |= NewBit;
1562 }
1563 }
1564
1565 if (NewUndefElts) {
1566 // Add additional discovered undefs.
1567 std::vector<Constant*> Elts;
1568 for (unsigned i = 0; i < VWidth; ++i) {
1569 if (UndefElts & (1ULL << i))
1570 Elts.push_back(UndefValue::get(Type::Int32Ty));
1571 else
1572 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1573 Shuffle->getMaskValue(i)));
1574 }
1575 I->setOperand(2, ConstantVector::get(Elts));
1576 MadeChange = true;
1577 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001578 break;
1579 }
Chris Lattner69878332007-04-14 22:29:23 +00001580 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001581 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001582 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1583 if (!VTy) break;
1584 unsigned InVWidth = VTy->getNumElements();
1585 uint64_t InputDemandedElts = 0;
1586 unsigned Ratio;
1587
1588 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001589 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001590 // elements as are demanded of us.
1591 Ratio = 1;
1592 InputDemandedElts = DemandedElts;
1593 } else if (VWidth > InVWidth) {
1594 // Untested so far.
1595 break;
1596
1597 // If there are more elements in the result than there are in the source,
1598 // then an input element is live if any of the corresponding output
1599 // elements are live.
1600 Ratio = VWidth/InVWidth;
1601 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1602 if (DemandedElts & (1ULL << OutIdx))
1603 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1604 }
1605 } else {
1606 // Untested so far.
1607 break;
1608
1609 // If there are more elements in the source than there are in the result,
1610 // then an input element is live if the corresponding output element is
1611 // live.
1612 Ratio = InVWidth/VWidth;
1613 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1614 if (DemandedElts & (1ULL << InIdx/Ratio))
1615 InputDemandedElts |= 1ULL << InIdx;
1616 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001617
Chris Lattner69878332007-04-14 22:29:23 +00001618 // div/rem demand all inputs, because they don't want divide by zero.
1619 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1620 UndefElts2, Depth+1);
1621 if (TmpV) {
1622 I->setOperand(0, TmpV);
1623 MadeChange = true;
1624 }
1625
1626 UndefElts = UndefElts2;
1627 if (VWidth > InVWidth) {
1628 assert(0 && "Unimp");
1629 // If there are more elements in the result than there are in the source,
1630 // then an output element is undef if the corresponding input element is
1631 // undef.
1632 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1633 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1634 UndefElts |= 1ULL << OutIdx;
1635 } else if (VWidth < InVWidth) {
1636 assert(0 && "Unimp");
1637 // If there are more elements in the source than there are in the result,
1638 // then a result element is undef if all of the corresponding input
1639 // elements are undef.
1640 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1641 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1642 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1643 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1644 }
1645 break;
1646 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001647 case Instruction::And:
1648 case Instruction::Or:
1649 case Instruction::Xor:
1650 case Instruction::Add:
1651 case Instruction::Sub:
1652 case Instruction::Mul:
1653 // div/rem demand all inputs, because they don't want divide by zero.
1654 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1655 UndefElts, Depth+1);
1656 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1657 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1658 UndefElts2, Depth+1);
1659 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1660
1661 // Output elements are undefined if both are undefined. Consider things
1662 // like undef&0. The result is known zero, not undef.
1663 UndefElts &= UndefElts2;
1664 break;
1665
1666 case Instruction::Call: {
1667 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1668 if (!II) break;
1669 switch (II->getIntrinsicID()) {
1670 default: break;
1671
1672 // Binary vector operations that work column-wise. A dest element is a
1673 // function of the corresponding input elements from the two inputs.
1674 case Intrinsic::x86_sse_sub_ss:
1675 case Intrinsic::x86_sse_mul_ss:
1676 case Intrinsic::x86_sse_min_ss:
1677 case Intrinsic::x86_sse_max_ss:
1678 case Intrinsic::x86_sse2_sub_sd:
1679 case Intrinsic::x86_sse2_mul_sd:
1680 case Intrinsic::x86_sse2_min_sd:
1681 case Intrinsic::x86_sse2_max_sd:
1682 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1683 UndefElts, Depth+1);
1684 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1685 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1686 UndefElts2, Depth+1);
1687 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1688
1689 // If only the low elt is demanded and this is a scalarizable intrinsic,
1690 // scalarize it now.
1691 if (DemandedElts == 1) {
1692 switch (II->getIntrinsicID()) {
1693 default: break;
1694 case Intrinsic::x86_sse_sub_ss:
1695 case Intrinsic::x86_sse_mul_ss:
1696 case Intrinsic::x86_sse2_sub_sd:
1697 case Intrinsic::x86_sse2_mul_sd:
1698 // TODO: Lower MIN/MAX/ABS/etc
1699 Value *LHS = II->getOperand(1);
1700 Value *RHS = II->getOperand(2);
1701 // Extract the element as scalars.
1702 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1703 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1704
1705 switch (II->getIntrinsicID()) {
1706 default: assert(0 && "Case stmts out of sync!");
1707 case Intrinsic::x86_sse_sub_ss:
1708 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001709 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001710 II->getName()), *II);
1711 break;
1712 case Intrinsic::x86_sse_mul_ss:
1713 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001714 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001715 II->getName()), *II);
1716 break;
1717 }
1718
1719 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001720 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1721 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001722 InsertNewInstBefore(New, *II);
1723 AddSoonDeadInstToWorklist(*II, 0);
1724 return New;
1725 }
1726 }
1727
1728 // Output elements are undefined if both are undefined. Consider things
1729 // like undef&0. The result is known zero, not undef.
1730 UndefElts &= UndefElts2;
1731 break;
1732 }
1733 break;
1734 }
1735 }
1736 return MadeChange ? I : 0;
1737}
1738
Dan Gohman45b4e482008-05-19 22:14:15 +00001739
Chris Lattner564a7272003-08-13 19:01:45 +00001740/// AssociativeOpt - Perform an optimization on an associative operator. This
1741/// function is designed to check a chain of associative operators for a
1742/// potential to apply a certain optimization. Since the optimization may be
1743/// applicable if the expression was reassociated, this checks the chain, then
1744/// reassociates the expression as necessary to expose the optimization
1745/// opportunity. This makes use of a special Functor, which must define
1746/// 'shouldApply' and 'apply' methods.
1747///
1748template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001749static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001750 unsigned Opcode = Root.getOpcode();
1751 Value *LHS = Root.getOperand(0);
1752
1753 // Quick check, see if the immediate LHS matches...
1754 if (F.shouldApply(LHS))
1755 return F.apply(Root);
1756
1757 // Otherwise, if the LHS is not of the same opcode as the root, return.
1758 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001759 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001760 // Should we apply this transform to the RHS?
1761 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1762
1763 // If not to the RHS, check to see if we should apply to the LHS...
1764 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1765 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1766 ShouldApply = true;
1767 }
1768
1769 // If the functor wants to apply the optimization to the RHS of LHSI,
1770 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1771 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001772 // Now all of the instructions are in the current basic block, go ahead
1773 // and perform the reassociation.
1774 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1775
1776 // First move the selected RHS to the LHS of the root...
1777 Root.setOperand(0, LHSI->getOperand(1));
1778
1779 // Make what used to be the LHS of the root be the user of the root...
1780 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001781 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001782 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1783 return 0;
1784 }
Chris Lattner65725312004-04-16 18:08:07 +00001785 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001786 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001787 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001788 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001789 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001790
1791 // Now propagate the ExtraOperand down the chain of instructions until we
1792 // get to LHSI.
1793 while (TmpLHSI != LHSI) {
1794 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001795 // Move the instruction to immediately before the chain we are
1796 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001797 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001798 ARI = NextLHSI;
1799
Chris Lattner564a7272003-08-13 19:01:45 +00001800 Value *NextOp = NextLHSI->getOperand(1);
1801 NextLHSI->setOperand(1, ExtraOperand);
1802 TmpLHSI = NextLHSI;
1803 ExtraOperand = NextOp;
1804 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001805
Chris Lattner564a7272003-08-13 19:01:45 +00001806 // Now that the instructions are reassociated, have the functor perform
1807 // the transformation...
1808 return F.apply(Root);
1809 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001810
Chris Lattner564a7272003-08-13 19:01:45 +00001811 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1812 }
1813 return 0;
1814}
1815
Dan Gohman844731a2008-05-13 00:00:25 +00001816namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001817
Nick Lewycky02d639f2008-05-23 04:34:58 +00001818// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001819struct AddRHS {
1820 Value *RHS;
1821 AddRHS(Value *rhs) : RHS(rhs) {}
1822 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1823 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001824 return BinaryOperator::CreateShl(Add.getOperand(0),
1825 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001826 }
1827};
1828
1829// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1830// iff C1&C2 == 0
1831struct AddMaskingAnd {
1832 Constant *C2;
1833 AddMaskingAnd(Constant *c) : C2(c) {}
1834 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001835 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001836 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001837 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001838 }
1839 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001840 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001841 }
1842};
1843
Dan Gohman844731a2008-05-13 00:00:25 +00001844}
1845
Chris Lattner6e7ba452005-01-01 16:22:27 +00001846static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001847 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001848 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001849 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001850 }
1851
Chris Lattner2eefe512004-04-09 19:05:30 +00001852 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001853 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1854 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001855
Chris Lattner2eefe512004-04-09 19:05:30 +00001856 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1857 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001858 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1859 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001860 }
1861
1862 Value *Op0 = SO, *Op1 = ConstOperand;
1863 if (!ConstIsRHS)
1864 std::swap(Op0, Op1);
1865 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001866 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001867 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001868 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001869 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001870 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001871 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001872 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001873 abort();
1874 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001875 return IC->InsertNewInstBefore(New, I);
1876}
1877
1878// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1879// constant as the other operand, try to fold the binary operator into the
1880// select arguments. This also works for Cast instructions, which obviously do
1881// not have a second operand.
1882static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1883 InstCombiner *IC) {
1884 // Don't modify shared select instructions
1885 if (!SI->hasOneUse()) return 0;
1886 Value *TV = SI->getOperand(1);
1887 Value *FV = SI->getOperand(2);
1888
1889 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001890 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001891 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001892
Chris Lattner6e7ba452005-01-01 16:22:27 +00001893 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1894 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1895
Gabor Greif051a9502008-04-06 20:25:17 +00001896 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1897 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001898 }
1899 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001900}
1901
Chris Lattner4e998b22004-09-29 05:07:12 +00001902
1903/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1904/// node as operand #0, see if we can fold the instruction into the PHI (which
1905/// is only possible if all operands to the PHI are constants).
1906Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1907 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001908 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001909 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001910
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001911 // Check to see if all of the operands of the PHI are constants. If there is
1912 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001913 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001914 BasicBlock *NonConstBB = 0;
1915 for (unsigned i = 0; i != NumPHIValues; ++i)
1916 if (!isa<Constant>(PN->getIncomingValue(i))) {
1917 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001918 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001919 NonConstBB = PN->getIncomingBlock(i);
1920
1921 // If the incoming non-constant value is in I's block, we have an infinite
1922 // loop.
1923 if (NonConstBB == I.getParent())
1924 return 0;
1925 }
1926
1927 // If there is exactly one non-constant value, we can insert a copy of the
1928 // operation in that block. However, if this is a critical edge, we would be
1929 // inserting the computation one some other paths (e.g. inside a loop). Only
1930 // do this if the pred block is unconditionally branching into the phi block.
1931 if (NonConstBB) {
1932 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1933 if (!BI || !BI->isUnconditional()) return 0;
1934 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001935
1936 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001937 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001938 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001939 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001940 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001941
1942 // Next, add all of the operands to the PHI.
1943 if (I.getNumOperands() == 2) {
1944 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001945 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001946 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001947 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001948 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1949 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1950 else
1951 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001952 } else {
1953 assert(PN->getIncomingBlock(i) == NonConstBB);
1954 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001955 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001956 PN->getIncomingValue(i), C, "phitmp",
1957 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001958 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001959 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001960 CI->getPredicate(),
1961 PN->getIncomingValue(i), C, "phitmp",
1962 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001963 else
1964 assert(0 && "Unknown binop!");
1965
Chris Lattnerdbab3862007-03-02 21:28:56 +00001966 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001967 }
1968 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001969 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001970 } else {
1971 CastInst *CI = cast<CastInst>(&I);
1972 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001973 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001974 Value *InV;
1975 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001976 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001977 } else {
1978 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001979 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001980 I.getType(), "phitmp",
1981 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001982 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001983 }
1984 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001985 }
1986 }
1987 return ReplaceInstUsesWith(I, NewPN);
1988}
1989
Chris Lattner2454a2e2008-01-29 06:52:45 +00001990
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001991/// WillNotOverflowSignedAdd - Return true if we can prove that:
1992/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1993/// This basically requires proving that the add in the original type would not
1994/// overflow to change the sign bit or have a carry out.
1995bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1996 // There are different heuristics we can use for this. Here are some simple
1997 // ones.
1998
1999 // Add has the property that adding any two 2's complement numbers can only
2000 // have one carry bit which can change a sign. As such, if LHS and RHS each
2001 // have at least two sign bits, we know that the addition of the two values will
2002 // sign extend fine.
2003 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2004 return true;
2005
2006
2007 // If one of the operands only has one non-zero bit, and if the other operand
2008 // has a known-zero bit in a more significant place than it (not including the
2009 // sign bit) the ripple may go up to and fill the zero, but won't change the
2010 // sign. For example, (X & ~4) + 1.
2011
2012 // TODO: Implement.
2013
2014 return false;
2015}
2016
Chris Lattner2454a2e2008-01-29 06:52:45 +00002017
Chris Lattner7e708292002-06-25 16:13:24 +00002018Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002019 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002020 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002021
Chris Lattner66331a42004-04-10 22:01:55 +00002022 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002023 // X + undef -> undef
2024 if (isa<UndefValue>(RHS))
2025 return ReplaceInstUsesWith(I, RHS);
2026
Chris Lattner66331a42004-04-10 22:01:55 +00002027 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002028 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002029 if (RHSC->isNullValue())
2030 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002031 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002032 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2033 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002034 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002035 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002036
Chris Lattner66331a42004-04-10 22:01:55 +00002037 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002038 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002039 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002040 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002041 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002042 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002043
2044 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2045 // (X & 254)+1 -> (X&254)|1
Chris Lattner886ab6c2009-01-31 08:15:18 +00002046 if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2047 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002048
2049 // zext(i1) - 1 -> select i1, 0, -1
2050 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2051 if (CI->isAllOnesValue() &&
2052 ZI->getOperand(0)->getType() == Type::Int1Ty)
2053 return SelectInst::Create(ZI->getOperand(0),
2054 Constant::getNullValue(I.getType()),
2055 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00002056 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002057
2058 if (isa<PHINode>(LHS))
2059 if (Instruction *NV = FoldOpIntoPhi(I))
2060 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002061
Chris Lattner4f637d42006-01-06 17:59:59 +00002062 ConstantInt *XorRHS = 0;
2063 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002064 if (isa<ConstantInt>(RHSC) &&
2065 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002066 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002067 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002068
Zhou Sheng4351c642007-04-02 08:20:41 +00002069 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002070 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2071 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002072 do {
2073 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002074 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2075 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002076 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2077 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002078 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002079 if (!MaskedValueIsZero(XorLHS,
2080 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002081 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002082 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002083 }
2084 }
2085 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002086 C0080Val = APIntOps::lshr(C0080Val, Size);
2087 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2088 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002089
Reid Spencer35c38852007-03-28 01:36:16 +00002090 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002091 // with funny bit widths then this switch statement should be removed. It
2092 // is just here to get the size of the "middle" type back up to something
2093 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002094 const Type *MiddleType = 0;
2095 switch (Size) {
2096 default: break;
2097 case 32: MiddleType = Type::Int32Ty; break;
2098 case 16: MiddleType = Type::Int16Ty; break;
2099 case 8: MiddleType = Type::Int8Ty; break;
2100 }
2101 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002102 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002103 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002104 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002105 }
2106 }
Chris Lattner66331a42004-04-10 22:01:55 +00002107 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002108
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002109 if (I.getType() == Type::Int1Ty)
2110 return BinaryOperator::CreateXor(LHS, RHS);
2111
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002112 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002113 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002114 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002115
2116 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2117 if (RHSI->getOpcode() == Instruction::Sub)
2118 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2119 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2120 }
2121 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2122 if (LHSI->getOpcode() == Instruction::Sub)
2123 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2124 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2125 }
Robert Bocchino71698282004-07-27 21:02:21 +00002126 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002127
Chris Lattner5c4afb92002-05-08 22:46:53 +00002128 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002129 // -A + -B --> -(A + B)
2130 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002131 if (LHS->getType()->isIntOrIntVector()) {
2132 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002133 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002134 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002135 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002136 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002137 }
2138
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002139 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002140 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002141
2142 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002143 if (!isa<Constant>(RHS))
2144 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002145 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002146
Misha Brukmanfd939082005-04-21 23:48:37 +00002147
Chris Lattner50af16a2004-11-13 19:50:12 +00002148 ConstantInt *C2;
2149 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2150 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002151 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002152
2153 // X*C1 + X*C2 --> X * (C1+C2)
2154 ConstantInt *C1;
2155 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002156 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002157 }
2158
2159 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002160 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002161 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002162
Chris Lattnere617c9e2007-01-05 02:17:46 +00002163 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002164 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2165 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002166
Chris Lattnerad3448c2003-02-18 19:57:07 +00002167
Chris Lattner564a7272003-08-13 19:01:45 +00002168 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002169 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002170 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2171 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002172
2173 // A+B --> A|B iff A and B have no bits set in common.
2174 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2175 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2176 APInt LHSKnownOne(IT->getBitWidth(), 0);
2177 APInt LHSKnownZero(IT->getBitWidth(), 0);
2178 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2179 if (LHSKnownZero != 0) {
2180 APInt RHSKnownOne(IT->getBitWidth(), 0);
2181 APInt RHSKnownZero(IT->getBitWidth(), 0);
2182 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2183
2184 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002185 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002186 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002187 }
2188 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002189
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002190 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002191 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002192 Value *W, *X, *Y, *Z;
2193 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2194 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2195 if (W != Y) {
2196 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002197 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002198 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002199 std::swap(W, X);
2200 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002201 std::swap(Y, Z);
2202 std::swap(W, X);
2203 }
2204 }
2205
2206 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002207 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002208 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002209 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002210 }
2211 }
2212 }
2213
Chris Lattner6b032052003-10-02 15:11:26 +00002214 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002215 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002216 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002217 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002218
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002219 // (X & FF00) + xx00 -> (X+xx00) & FF00
2220 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002221 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002222 if (Anded == CRHS) {
2223 // See if all bits from the first bit set in the Add RHS up are included
2224 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002225 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002226
2227 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002228 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002229
2230 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002231 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002232
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002233 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2234 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002235 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002236 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002237 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002238 }
2239 }
2240 }
2241
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002242 // Try to fold constant add into select arguments.
2243 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002244 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002245 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002246 }
2247
Reid Spencer1628cec2006-10-26 06:15:43 +00002248 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002249 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002250 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002251 CastInst *CI = dyn_cast<CastInst>(LHS);
2252 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002253 if (!CI) {
2254 CI = dyn_cast<CastInst>(RHS);
2255 Other = LHS;
2256 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002257 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002258 (CI->getType()->getPrimitiveSizeInBits() ==
2259 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002260 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002261 unsigned AS =
2262 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002263 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2264 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002265 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002266 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002267 }
2268 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002269
Chris Lattner42790482007-12-20 01:56:58 +00002270 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002271 {
2272 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002273 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002274 if (!SI) {
2275 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002276 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002277 }
Chris Lattner42790482007-12-20 01:56:58 +00002278 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002279 Value *TV = SI->getTrueValue();
2280 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002281 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002282
2283 // Can we fold the add into the argument of the select?
2284 // We check both true and false select arguments for a matching subtract.
Chris Lattner6046fb72008-11-16 04:46:19 +00002285 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2286 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002287 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner6046fb72008-11-16 04:46:19 +00002288 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2289 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002290 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002291 }
2292 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002293
2294 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2295 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2296 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2297 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002298
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002299 // Check for (add (sext x), y), see if we can merge this into an
2300 // integer add followed by a sext.
2301 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2302 // (add (sext x), cst) --> (sext (add x, cst'))
2303 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2304 Constant *CI =
2305 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2306 if (LHSConv->hasOneUse() &&
2307 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2308 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2309 // Insert the new, smaller add.
2310 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2311 CI, "addconv");
2312 InsertNewInstBefore(NewAdd, I);
2313 return new SExtInst(NewAdd, I.getType());
2314 }
2315 }
2316
2317 // (add (sext x), (sext y)) --> (sext (add int x, y))
2318 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2319 // Only do this if x/y have the same type, if at last one of them has a
2320 // single use (so we don't increase the number of sexts), and if the
2321 // integer add will not overflow.
2322 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2323 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2324 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2325 RHSConv->getOperand(0))) {
2326 // Insert the new integer add.
2327 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2328 RHSConv->getOperand(0),
2329 "addconv");
2330 InsertNewInstBefore(NewAdd, I);
2331 return new SExtInst(NewAdd, I.getType());
2332 }
2333 }
2334 }
2335
2336 // Check for (add double (sitofp x), y), see if we can merge this into an
2337 // integer add followed by a promotion.
2338 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2339 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2340 // ... if the constant fits in the integer value. This is useful for things
2341 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2342 // requires a constant pool load, and generally allows the add to be better
2343 // instcombined.
2344 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2345 Constant *CI =
2346 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2347 if (LHSConv->hasOneUse() &&
2348 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2349 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2350 // Insert the new integer add.
2351 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2352 CI, "addconv");
2353 InsertNewInstBefore(NewAdd, I);
2354 return new SIToFPInst(NewAdd, I.getType());
2355 }
2356 }
2357
2358 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2359 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2360 // Only do this if x/y have the same type, if at last one of them has a
2361 // single use (so we don't increase the number of int->fp conversions),
2362 // and if the integer add will not overflow.
2363 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2364 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2365 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2366 RHSConv->getOperand(0))) {
2367 // Insert the new integer add.
2368 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2369 RHSConv->getOperand(0),
2370 "addconv");
2371 InsertNewInstBefore(NewAdd, I);
2372 return new SIToFPInst(NewAdd, I.getType());
2373 }
2374 }
2375 }
2376
Chris Lattner7e708292002-06-25 16:13:24 +00002377 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002378}
2379
Chris Lattner7e708292002-06-25 16:13:24 +00002380Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002381 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002382
Chris Lattnerd137ab42008-07-17 06:07:20 +00002383 if (Op0 == Op1 && // sub X, X -> 0
2384 !I.getType()->isFPOrFPVector())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002385 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002386
Chris Lattner233f7dc2002-08-12 21:17:25 +00002387 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002388 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002389 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002390
Chris Lattnere87597f2004-10-16 18:11:37 +00002391 if (isa<UndefValue>(Op0))
2392 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2393 if (isa<UndefValue>(Op1))
2394 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2395
Chris Lattnerd65460f2003-11-05 01:06:05 +00002396 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2397 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002398 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002399 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002400
Chris Lattnerd65460f2003-11-05 01:06:05 +00002401 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002402 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002403 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002404 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002405
Chris Lattner76b7a062007-01-15 07:02:54 +00002406 // -(X >>u 31) -> (X >>s 31)
2407 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002408 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002409 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002410 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002411 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002412 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002413 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002414 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002415 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002416 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002417 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002418 }
2419 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002420 }
2421 else if (SI->getOpcode() == Instruction::AShr) {
2422 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2423 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002424 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002425 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002426 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002427 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002428 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002429 }
2430 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002431 }
2432 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002433 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002434
2435 // Try to fold constant sub into select arguments.
2436 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002437 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002438 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002439 }
2440
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002441 if (I.getType() == Type::Int1Ty)
2442 return BinaryOperator::CreateXor(Op0, Op1);
2443
Chris Lattner43d84d62005-04-07 16:15:25 +00002444 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2445 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002446 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002447 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002448 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002449 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002450 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002451 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2452 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2453 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002454 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002455 Op1I->getOperand(0));
2456 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002457 }
2458
Chris Lattnerfd059242003-10-15 16:48:29 +00002459 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002460 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2461 // is not used by anyone else...
2462 //
Chris Lattner0517e722004-02-02 20:09:56 +00002463 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002464 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002465 // Swap the two operands of the subexpr...
2466 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2467 Op1I->setOperand(0, IIOp1);
2468 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002469
Chris Lattnera2881962003-02-18 19:28:33 +00002470 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002471 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002472 }
2473
2474 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2475 //
2476 if (Op1I->getOpcode() == Instruction::And &&
2477 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2478 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2479
Chris Lattnerf523d062004-06-09 05:08:07 +00002480 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002481 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2482 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002483 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002484
Reid Spencerac5209e2006-10-16 23:08:08 +00002485 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002486 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002487 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002488 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002489 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002490 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002491 ConstantExpr::getNeg(DivRHS));
2492
Chris Lattnerad3448c2003-02-18 19:57:07 +00002493 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002494 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002495 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002496 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002497 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002498 }
Chris Lattner40371712002-05-09 01:29:19 +00002499 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002500 }
Chris Lattnera2881962003-02-18 19:28:33 +00002501
Chris Lattner9919e3d2006-12-02 00:13:08 +00002502 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002503 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002504 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002505 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2506 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2507 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2508 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002509 } else if (Op0I->getOpcode() == Instruction::Sub) {
2510 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002511 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002512 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002513 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002514
Chris Lattner50af16a2004-11-13 19:50:12 +00002515 ConstantInt *C1;
2516 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002517 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002518 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002519
Chris Lattner50af16a2004-11-13 19:50:12 +00002520 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2521 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002522 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002523 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002524 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002525}
2526
Chris Lattnera0141b92007-07-15 20:42:37 +00002527/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2528/// comparison only checks the sign bit. If it only checks the sign bit, set
2529/// TrueIfSigned if the result of the comparison is true when the input value is
2530/// signed.
2531static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2532 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002533 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002534 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2535 TrueIfSigned = true;
2536 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002537 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2538 TrueIfSigned = true;
2539 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002540 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2541 TrueIfSigned = false;
2542 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002543 case ICmpInst::ICMP_UGT:
2544 // True if LHS u> RHS and RHS == high-bit-mask - 1
2545 TrueIfSigned = true;
2546 return RHS->getValue() ==
2547 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2548 case ICmpInst::ICMP_UGE:
2549 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2550 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002551 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002552 default:
2553 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002554 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002555}
2556
Chris Lattner7e708292002-06-25 16:13:24 +00002557Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002558 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002559 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002560
Chris Lattnere87597f2004-10-16 18:11:37 +00002561 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2562 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2563
Chris Lattner233f7dc2002-08-12 21:17:25 +00002564 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002565 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2566 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002567
2568 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002569 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002570 if (SI->getOpcode() == Instruction::Shl)
2571 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002572 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002573 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002574
Zhou Sheng843f07672007-04-19 05:39:12 +00002575 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002576 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2577 if (CI->equalsInt(1)) // X * 1 == X
2578 return ReplaceInstUsesWith(I, Op0);
2579 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002580 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002581
Zhou Sheng97b52c22007-03-29 01:57:21 +00002582 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002583 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002584 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002585 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002586 }
Robert Bocchino71698282004-07-27 21:02:21 +00002587 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002588 if (Op1F->isNullValue())
2589 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002590
Chris Lattnera2881962003-02-18 19:28:33 +00002591 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2592 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002593 if (Op1F->isExactlyValue(1.0))
2594 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2595 } else if (isa<VectorType>(Op1->getType())) {
2596 if (isa<ConstantAggregateZero>(Op1))
2597 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002598
2599 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2600 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2601 return BinaryOperator::CreateNeg(Op0, I.getName());
2602
2603 // As above, vector X*splat(1.0) -> X in all defined cases.
2604 if (Constant *Splat = Op1V->getSplatValue()) {
2605 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2606 if (F->isExactlyValue(1.0))
2607 return ReplaceInstUsesWith(I, Op0);
2608 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2609 if (CI->equalsInt(1))
2610 return ReplaceInstUsesWith(I, Op0);
2611 }
2612 }
Chris Lattnera2881962003-02-18 19:28:33 +00002613 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002614
2615 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2616 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002617 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002618 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002619 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002620 Op1, "tmp");
2621 InsertNewInstBefore(Add, I);
2622 Value *C1C2 = ConstantExpr::getMul(Op1,
2623 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002624 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002625
2626 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002627
2628 // Try to fold constant mul into select arguments.
2629 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002630 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002631 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002632
2633 if (isa<PHINode>(Op0))
2634 if (Instruction *NV = FoldOpIntoPhi(I))
2635 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002636 }
2637
Chris Lattnera4f445b2003-03-10 23:23:04 +00002638 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2639 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002640 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002641
Nick Lewycky0c730792008-11-21 07:33:58 +00002642 // (X / Y) * Y = X - (X % Y)
2643 // (X / Y) * -Y = (X % Y) - X
2644 {
2645 Value *Op1 = I.getOperand(1);
2646 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2647 if (!BO ||
2648 (BO->getOpcode() != Instruction::UDiv &&
2649 BO->getOpcode() != Instruction::SDiv)) {
2650 Op1 = Op0;
2651 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2652 }
2653 Value *Neg = dyn_castNegVal(Op1);
2654 if (BO && BO->hasOneUse() &&
2655 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2656 (BO->getOpcode() == Instruction::UDiv ||
2657 BO->getOpcode() == Instruction::SDiv)) {
2658 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2659
2660 Instruction *Rem;
2661 if (BO->getOpcode() == Instruction::UDiv)
2662 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2663 else
2664 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2665
2666 InsertNewInstBefore(Rem, I);
2667 Rem->takeName(BO);
2668
2669 if (Op1BO == Op1)
2670 return BinaryOperator::CreateSub(Op0BO, Rem);
2671 else
2672 return BinaryOperator::CreateSub(Rem, Op0BO);
2673 }
2674 }
2675
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002676 if (I.getType() == Type::Int1Ty)
2677 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2678
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002679 // If one of the operands of the multiply is a cast from a boolean value, then
2680 // we know the bool is either zero or one, so this is a 'masking' multiply.
2681 // See if we can simplify things based on how the boolean was originally
2682 // formed.
2683 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002684 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002685 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002686 BoolCast = CI;
2687 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002688 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002689 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002690 BoolCast = CI;
2691 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002692 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002693 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2694 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002695 bool TIS = false;
2696
Reid Spencere4d87aa2006-12-23 06:05:41 +00002697 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002698 // multiply into a shift/and combination.
2699 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002700 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2701 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002702 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002703 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002704 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002705 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002706 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002707 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002708 BoolCast->getOperand(0)->getName()+
2709 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002710
2711 // If the multiply type is not the same as the source type, sign extend
2712 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002713 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002714 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2715 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002716 Instruction::CastOps opcode =
2717 (SrcBits == DstBits ? Instruction::BitCast :
2718 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2719 V = InsertCastBefore(opcode, V, I.getType(), I);
2720 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002721
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002722 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002723 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002724 }
2725 }
2726 }
2727
Chris Lattner7e708292002-06-25 16:13:24 +00002728 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002729}
2730
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002731/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2732/// instruction.
2733bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2734 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2735
2736 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2737 int NonNullOperand = -1;
2738 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2739 if (ST->isNullValue())
2740 NonNullOperand = 2;
2741 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2742 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2743 if (ST->isNullValue())
2744 NonNullOperand = 1;
2745
2746 if (NonNullOperand == -1)
2747 return false;
2748
2749 Value *SelectCond = SI->getOperand(0);
2750
2751 // Change the div/rem to use 'Y' instead of the select.
2752 I.setOperand(1, SI->getOperand(NonNullOperand));
2753
2754 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2755 // problem. However, the select, or the condition of the select may have
2756 // multiple uses. Based on our knowledge that the operand must be non-zero,
2757 // propagate the known value for the select into other uses of it, and
2758 // propagate a known value of the condition into its other users.
2759
2760 // If the select and condition only have a single use, don't bother with this,
2761 // early exit.
2762 if (SI->use_empty() && SelectCond->hasOneUse())
2763 return true;
2764
2765 // Scan the current block backward, looking for other uses of SI.
2766 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2767
2768 while (BBI != BBFront) {
2769 --BBI;
2770 // If we found a call to a function, we can't assume it will return, so
2771 // information from below it cannot be propagated above it.
2772 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2773 break;
2774
2775 // Replace uses of the select or its condition with the known values.
2776 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2777 I != E; ++I) {
2778 if (*I == SI) {
2779 *I = SI->getOperand(NonNullOperand);
2780 AddToWorkList(BBI);
2781 } else if (*I == SelectCond) {
2782 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2783 ConstantInt::getFalse();
2784 AddToWorkList(BBI);
2785 }
2786 }
2787
2788 // If we past the instruction, quit looking for it.
2789 if (&*BBI == SI)
2790 SI = 0;
2791 if (&*BBI == SelectCond)
2792 SelectCond = 0;
2793
2794 // If we ran out of things to eliminate, break out of the loop.
2795 if (SelectCond == 0 && SI == 0)
2796 break;
2797
2798 }
2799 return true;
2800}
2801
2802
Reid Spencer1628cec2006-10-26 06:15:43 +00002803/// This function implements the transforms on div instructions that work
2804/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2805/// used by the visitors to those instructions.
2806/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002807Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002808 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002809
Chris Lattner50b2ca42008-02-19 06:12:18 +00002810 // undef / X -> 0 for integer.
2811 // undef / X -> undef for FP (the undef could be a snan).
2812 if (isa<UndefValue>(Op0)) {
2813 if (Op0->getType()->isFPOrFPVector())
2814 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002815 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002816 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002817
2818 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002819 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002820 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002821
Reid Spencer1628cec2006-10-26 06:15:43 +00002822 return 0;
2823}
Misha Brukmanfd939082005-04-21 23:48:37 +00002824
Reid Spencer1628cec2006-10-26 06:15:43 +00002825/// This function implements the transforms common to both integer division
2826/// instructions (udiv and sdiv). It is called by the visitors to those integer
2827/// division instructions.
2828/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002829Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002830 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2831
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002832 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002833 if (Op0 == Op1) {
2834 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2835 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2836 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2837 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2838 }
2839
2840 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2841 return ReplaceInstUsesWith(I, CI);
2842 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002843
Reid Spencer1628cec2006-10-26 06:15:43 +00002844 if (Instruction *Common = commonDivTransforms(I))
2845 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002846
2847 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2848 // This does not apply for fdiv.
2849 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2850 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002851
2852 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2853 // div X, 1 == X
2854 if (RHS->equalsInt(1))
2855 return ReplaceInstUsesWith(I, Op0);
2856
2857 // (X / C1) / C2 -> X / (C1*C2)
2858 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2859 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2860 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002861 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2862 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2863 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002864 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002865 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002866 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002867
Reid Spencerbca0e382007-03-23 20:05:17 +00002868 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002869 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2870 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2871 return R;
2872 if (isa<PHINode>(Op0))
2873 if (Instruction *NV = FoldOpIntoPhi(I))
2874 return NV;
2875 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002876 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002877
Chris Lattnera2881962003-02-18 19:28:33 +00002878 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002879 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002880 if (LHS->equalsInt(0))
2881 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2882
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002883 // It can't be division by zero, hence it must be division by one.
2884 if (I.getType() == Type::Int1Ty)
2885 return ReplaceInstUsesWith(I, Op0);
2886
Nick Lewycky895f0852008-11-27 20:21:08 +00002887 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2888 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2889 // div X, 1 == X
2890 if (X->isOne())
2891 return ReplaceInstUsesWith(I, Op0);
2892 }
2893
Reid Spencer1628cec2006-10-26 06:15:43 +00002894 return 0;
2895}
2896
2897Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2898 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2899
2900 // Handle the integer div common cases
2901 if (Instruction *Common = commonIDivTransforms(I))
2902 return Common;
2903
Reid Spencer1628cec2006-10-26 06:15:43 +00002904 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002905 // X udiv C^2 -> X >> C
2906 // Check to see if this is an unsigned division with an exact power of 2,
2907 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002908 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002909 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002910 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002911
2912 // X udiv C, where C >= signbit
2913 if (C->getValue().isNegative()) {
2914 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2915 I);
2916 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2917 ConstantInt::get(I.getType(), 1));
2918 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002919 }
2920
2921 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002922 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002923 if (RHSI->getOpcode() == Instruction::Shl &&
2924 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002925 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002926 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002927 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002928 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002929 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002930 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002931 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002932 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002933 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002934 }
2935 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002936 }
2937
Reid Spencer1628cec2006-10-26 06:15:43 +00002938 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2939 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002940 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002941 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002942 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002943 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002944 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002945 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002946 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002947 // Construct the "on true" case of the select
2948 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002949 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002950 Op0, TC, SI->getName()+".t");
2951 TSI = InsertNewInstBefore(TSI, I);
2952
2953 // Construct the "on false" case of the select
2954 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002955 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002956 Op0, FC, SI->getName()+".f");
2957 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002958
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002959 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002960 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002961 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002962 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002963 return 0;
2964}
2965
Reid Spencer1628cec2006-10-26 06:15:43 +00002966Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2967 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2968
2969 // Handle the integer div common cases
2970 if (Instruction *Common = commonIDivTransforms(I))
2971 return Common;
2972
2973 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2974 // sdiv X, -1 == -X
2975 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002976 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002977 }
2978
2979 // If the sign bits of both operands are zero (i.e. we can prove they are
2980 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002981 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002982 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002983 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002984 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002985 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002986 }
2987 }
2988
2989 return 0;
2990}
2991
2992Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2993 return commonDivTransforms(I);
2994}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002995
Reid Spencer0a783f72006-11-02 01:53:59 +00002996/// This function implements the transforms on rem instructions that work
2997/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2998/// is used by the visitors to those instructions.
2999/// @brief Transforms common to all three rem instructions
3000Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003001 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003002
Chris Lattner50b2ca42008-02-19 06:12:18 +00003003 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3004 if (I.getType()->isFPOrFPVector())
3005 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003006 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003007 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003008 if (isa<UndefValue>(Op1))
3009 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003010
3011 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003012 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3013 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003014
Reid Spencer0a783f72006-11-02 01:53:59 +00003015 return 0;
3016}
3017
3018/// This function implements the transforms common to both integer remainder
3019/// instructions (urem and srem). It is called by the visitors to those integer
3020/// remainder instructions.
3021/// @brief Common integer remainder transforms
3022Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3023 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3024
3025 if (Instruction *common = commonRemTransforms(I))
3026 return common;
3027
Dale Johannesened6af242009-01-21 00:35:19 +00003028 // 0 % X == 0 for integer, we don't need to preserve faults!
3029 if (Constant *LHS = dyn_cast<Constant>(Op0))
3030 if (LHS->isNullValue())
3031 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3032
Chris Lattner857e8cd2004-12-12 21:48:58 +00003033 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003034 // X % 0 == undef, we don't need to preserve faults!
3035 if (RHS->equalsInt(0))
3036 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3037
Chris Lattnera2881962003-02-18 19:28:33 +00003038 if (RHS->equalsInt(1)) // X % 1 == 0
3039 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3040
Chris Lattner97943922006-02-28 05:49:21 +00003041 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3042 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3043 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3044 return R;
3045 } else if (isa<PHINode>(Op0I)) {
3046 if (Instruction *NV = FoldOpIntoPhi(I))
3047 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003048 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003049
3050 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003051 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003052 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003053 }
Chris Lattnera2881962003-02-18 19:28:33 +00003054 }
3055
Reid Spencer0a783f72006-11-02 01:53:59 +00003056 return 0;
3057}
3058
3059Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3060 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3061
3062 if (Instruction *common = commonIRemTransforms(I))
3063 return common;
3064
3065 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3066 // X urem C^2 -> X and C
3067 // Check to see if this is an unsigned remainder with an exact power of 2,
3068 // if so, convert to a bitwise and.
3069 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003070 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003071 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003072 }
3073
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003074 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003075 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3076 if (RHSI->getOpcode() == Instruction::Shl &&
3077 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003078 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003079 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003080 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003081 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003082 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003083 }
3084 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003085 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003086
Reid Spencer0a783f72006-11-02 01:53:59 +00003087 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3088 // where C1&C2 are powers of two.
3089 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3090 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3091 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3092 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003093 if ((STO->getValue().isPowerOf2()) &&
3094 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003095 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003096 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003097 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003098 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003099 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003100 }
3101 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003102 }
3103
Chris Lattner3f5b8772002-05-06 16:14:14 +00003104 return 0;
3105}
3106
Reid Spencer0a783f72006-11-02 01:53:59 +00003107Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3108 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3109
Dan Gohmancff55092007-11-05 23:16:33 +00003110 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003111 if (Instruction *common = commonIRemTransforms(I))
3112 return common;
3113
3114 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003115 if (!isa<Constant>(RHSNeg) ||
3116 (isa<ConstantInt>(RHSNeg) &&
3117 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003118 // X % -Y -> X % Y
3119 AddUsesToWorkList(I);
3120 I.setOperand(1, RHSNeg);
3121 return &I;
3122 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003123
Dan Gohmancff55092007-11-05 23:16:33 +00003124 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003125 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003126 if (I.getType()->isInteger()) {
3127 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3128 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3129 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003130 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003131 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003132 }
3133
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003134 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003135 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3136 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003137
Nick Lewycky9dce8732008-12-20 16:48:00 +00003138 bool hasNegative = false;
3139 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3140 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3141 if (RHS->getValue().isNegative())
3142 hasNegative = true;
3143
3144 if (hasNegative) {
3145 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003146 for (unsigned i = 0; i != VWidth; ++i) {
3147 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3148 if (RHS->getValue().isNegative())
3149 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3150 else
3151 Elts[i] = RHS;
3152 }
3153 }
3154
3155 Constant *NewRHSV = ConstantVector::get(Elts);
3156 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003157 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003158 I.setOperand(1, NewRHSV);
3159 return &I;
3160 }
3161 }
3162 }
3163
Reid Spencer0a783f72006-11-02 01:53:59 +00003164 return 0;
3165}
3166
3167Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003168 return commonRemTransforms(I);
3169}
3170
Chris Lattner457dd822004-06-09 07:59:58 +00003171// isOneBitSet - Return true if there is exactly one bit set in the specified
3172// constant.
3173static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003174 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003175}
3176
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003177// isHighOnes - Return true if the constant is of the form 1+0+.
3178// This is the same as lowones(~X).
3179static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003180 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003181}
3182
Reid Spencere4d87aa2006-12-23 06:05:41 +00003183/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003184/// are carefully arranged to allow folding of expressions such as:
3185///
3186/// (A < B) | (A > B) --> (A != B)
3187///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003188/// Note that this is only valid if the first and second predicates have the
3189/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003190///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003191/// Three bits are used to represent the condition, as follows:
3192/// 0 A > B
3193/// 1 A == B
3194/// 2 A < B
3195///
3196/// <=> Value Definition
3197/// 000 0 Always false
3198/// 001 1 A > B
3199/// 010 2 A == B
3200/// 011 3 A >= B
3201/// 100 4 A < B
3202/// 101 5 A != B
3203/// 110 6 A <= B
3204/// 111 7 Always true
3205///
3206static unsigned getICmpCode(const ICmpInst *ICI) {
3207 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003208 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003209 case ICmpInst::ICMP_UGT: return 1; // 001
3210 case ICmpInst::ICMP_SGT: return 1; // 001
3211 case ICmpInst::ICMP_EQ: return 2; // 010
3212 case ICmpInst::ICMP_UGE: return 3; // 011
3213 case ICmpInst::ICMP_SGE: return 3; // 011
3214 case ICmpInst::ICMP_ULT: return 4; // 100
3215 case ICmpInst::ICMP_SLT: return 4; // 100
3216 case ICmpInst::ICMP_NE: return 5; // 101
3217 case ICmpInst::ICMP_ULE: return 6; // 110
3218 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003219 // True -> 7
3220 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003221 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003222 return 0;
3223 }
3224}
3225
Evan Cheng8db90722008-10-14 17:15:11 +00003226/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3227/// predicate into a three bit mask. It also returns whether it is an ordered
3228/// predicate by reference.
3229static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3230 isOrdered = false;
3231 switch (CC) {
3232 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3233 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003234 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3235 case FCmpInst::FCMP_UGT: return 1; // 001
3236 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3237 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003238 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3239 case FCmpInst::FCMP_UGE: return 3; // 011
3240 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3241 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003242 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3243 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003244 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3245 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003246 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003247 default:
3248 // Not expecting FCMP_FALSE and FCMP_TRUE;
3249 assert(0 && "Unexpected FCmp predicate!");
3250 return 0;
3251 }
3252}
3253
Reid Spencere4d87aa2006-12-23 06:05:41 +00003254/// getICmpValue - This is the complement of getICmpCode, which turns an
3255/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003256/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003257/// of predicate to use in the new icmp instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003258static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3259 switch (code) {
3260 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003261 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003262 case 1:
3263 if (sign)
3264 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3265 else
3266 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3267 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3268 case 3:
3269 if (sign)
3270 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3271 else
3272 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3273 case 4:
3274 if (sign)
3275 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3276 else
3277 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3278 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3279 case 6:
3280 if (sign)
3281 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3282 else
3283 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003284 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003285 }
3286}
3287
Evan Cheng8db90722008-10-14 17:15:11 +00003288/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3289/// opcode and two operands into either a FCmp instruction. isordered is passed
3290/// in to determine which kind of predicate to use in the new fcmp instruction.
3291static Value *getFCmpValue(bool isordered, unsigned code,
3292 Value *LHS, Value *RHS) {
3293 switch (code) {
Evan Cheng4990b252008-10-14 18:13:38 +00003294 default: assert(0 && "Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003295 case 0:
3296 if (isordered)
3297 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3298 else
3299 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3300 case 1:
3301 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003302 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3303 else
3304 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003305 case 2:
3306 if (isordered)
3307 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3308 else
3309 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003310 case 3:
3311 if (isordered)
3312 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3313 else
3314 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3315 case 4:
3316 if (isordered)
3317 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3318 else
3319 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3320 case 5:
3321 if (isordered)
Evan Cheng4990b252008-10-14 18:13:38 +00003322 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3323 else
3324 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3325 case 6:
3326 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003327 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3328 else
3329 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng40300622008-10-14 18:44:08 +00003330 case 7: return ConstantInt::getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003331 }
3332}
3333
Chris Lattnerb9553d62008-11-16 04:55:20 +00003334/// PredicatesFoldable - Return true if both predicates match sign or if at
3335/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003336static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3337 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003338 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3339 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003340}
3341
3342namespace {
3343// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3344struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003345 InstCombiner &IC;
3346 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003347 ICmpInst::Predicate pred;
3348 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3349 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3350 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003351 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003352 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3353 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003354 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3355 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003356 return false;
3357 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003358 Instruction *apply(Instruction &Log) const {
3359 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3360 if (ICI->getOperand(0) != LHS) {
3361 assert(ICI->getOperand(1) == LHS);
3362 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003363 }
3364
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003365 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003366 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003367 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003368 unsigned Code;
3369 switch (Log.getOpcode()) {
3370 case Instruction::And: Code = LHSCode & RHSCode; break;
3371 case Instruction::Or: Code = LHSCode | RHSCode; break;
3372 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003373 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003374 }
3375
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003376 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3377 ICmpInst::isSignedPredicate(ICI->getPredicate());
3378
3379 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003380 if (Instruction *I = dyn_cast<Instruction>(RV))
3381 return I;
3382 // Otherwise, it's a constant boolean value...
3383 return IC.ReplaceInstUsesWith(Log, RV);
3384 }
3385};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003386} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003387
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003388// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3389// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003390// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003391Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003392 ConstantInt *OpRHS,
3393 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003394 BinaryOperator &TheAnd) {
3395 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003396 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003397 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003398 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003399
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003400 switch (Op->getOpcode()) {
3401 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003402 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003403 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003404 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003405 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003406 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003407 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003408 }
3409 break;
3410 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003411 if (Together == AndRHS) // (X | C) & C --> C
3412 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003413
Chris Lattner6e7ba452005-01-01 16:22:27 +00003414 if (Op->hasOneUse() && Together != OpRHS) {
3415 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003416 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003417 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003418 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003419 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003420 }
3421 break;
3422 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003423 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003424 // Adding a one to a single bit bit-field should be turned into an XOR
3425 // of the bit. First thing to check is to see if this AND is with a
3426 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003427 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003428
3429 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003430 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003431 // Ok, at this point, we know that we are masking the result of the
3432 // ADD down to exactly one bit. If the constant we are adding has
3433 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003434 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003435
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003436 // Check to see if any bits below the one bit set in AndRHSV are set.
3437 if ((AddRHS & (AndRHSV-1)) == 0) {
3438 // If not, the only thing that can effect the output of the AND is
3439 // the bit specified by AndRHSV. If that bit is set, the effect of
3440 // the XOR is to toggle the bit. If it is clear, then the ADD has
3441 // no effect.
3442 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3443 TheAnd.setOperand(0, X);
3444 return &TheAnd;
3445 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003446 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003447 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003448 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003449 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003450 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003451 }
3452 }
3453 }
3454 }
3455 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003456
3457 case Instruction::Shl: {
3458 // We know that the AND will not produce any of the bits shifted in, so if
3459 // the anded constant includes them, clear them now!
3460 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003461 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003462 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003463 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3464 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003465
Zhou Sheng290bec52007-03-29 08:15:12 +00003466 if (CI->getValue() == ShlMask) {
3467 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003468 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3469 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003470 TheAnd.setOperand(1, CI);
3471 return &TheAnd;
3472 }
3473 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003474 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003475 case Instruction::LShr:
3476 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003477 // We know that the AND will not produce any of the bits shifted in, so if
3478 // the anded constant includes them, clear them now! This only applies to
3479 // unsigned shifts, because a signed shr may bring in set bits!
3480 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003481 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003482 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003483 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3484 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003485
Zhou Sheng290bec52007-03-29 08:15:12 +00003486 if (CI->getValue() == ShrMask) {
3487 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003488 return ReplaceInstUsesWith(TheAnd, Op);
3489 } else if (CI != AndRHS) {
3490 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3491 return &TheAnd;
3492 }
3493 break;
3494 }
3495 case Instruction::AShr:
3496 // Signed shr.
3497 // See if this is shifting in some sign extension, then masking it out
3498 // with an and.
3499 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003500 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003501 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003502 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3503 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003504 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003505 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003506 // Make the argument unsigned.
3507 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003508 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003509 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003510 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003511 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003512 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003513 }
3514 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003515 }
3516 return 0;
3517}
3518
Chris Lattner8b170942002-08-09 23:47:40 +00003519
Chris Lattnera96879a2004-09-29 17:40:11 +00003520/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3521/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003522/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3523/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003524/// insert new instructions.
3525Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003526 bool isSigned, bool Inside,
3527 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003528 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003529 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003530 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003531
Chris Lattnera96879a2004-09-29 17:40:11 +00003532 if (Inside) {
3533 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003534 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003535
Reid Spencere4d87aa2006-12-23 06:05:41 +00003536 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003537 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003538 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003539 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3540 return new ICmpInst(pred, V, Hi);
3541 }
3542
3543 // Emit V-Lo <u Hi-Lo
3544 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003545 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003546 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003547 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3548 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003549 }
3550
3551 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003552 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003553
Reid Spencere4e40032007-03-21 23:19:50 +00003554 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003555 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003556 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003557 ICmpInst::Predicate pred = (isSigned ?
3558 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3559 return new ICmpInst(pred, V, Hi);
3560 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003561
Reid Spencere4e40032007-03-21 23:19:50 +00003562 // Emit V-Lo >u Hi-1-Lo
3563 // Note that Hi has already had one subtracted from it, above.
3564 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003565 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003566 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003567 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3568 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003569}
3570
Chris Lattner7203e152005-09-18 07:22:02 +00003571// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3572// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3573// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3574// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003575static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003576 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003577 uint32_t BitWidth = Val->getType()->getBitWidth();
3578 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003579
3580 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003581 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003582 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003583 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003584 return true;
3585}
3586
Chris Lattner7203e152005-09-18 07:22:02 +00003587/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3588/// where isSub determines whether the operator is a sub. If we can fold one of
3589/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003590///
3591/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3592/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3593/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3594///
3595/// return (A +/- B).
3596///
3597Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003598 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003599 Instruction &I) {
3600 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3601 if (!LHSI || LHSI->getNumOperands() != 2 ||
3602 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3603
3604 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3605
3606 switch (LHSI->getOpcode()) {
3607 default: return 0;
3608 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003609 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003610 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003611 if ((Mask->getValue().countLeadingZeros() +
3612 Mask->getValue().countPopulation()) ==
3613 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003614 break;
3615
3616 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3617 // part, we don't need any explicit masks to take them out of A. If that
3618 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003619 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003620 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003621 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003622 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003623 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003624 break;
3625 }
3626 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003627 return 0;
3628 case Instruction::Or:
3629 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003630 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003631 if ((Mask->getValue().countLeadingZeros() +
3632 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003633 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003634 break;
3635 return 0;
3636 }
3637
3638 Instruction *New;
3639 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003640 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003641 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003642 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003643 return InsertNewInstBefore(New, I);
3644}
3645
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003646/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3647Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3648 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003649 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003650 ConstantInt *LHSCst, *RHSCst;
3651 ICmpInst::Predicate LHSCC, RHSCC;
3652
Chris Lattnerea065fb2008-11-16 05:10:52 +00003653 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003654 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerea065fb2008-11-16 05:10:52 +00003655 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003656 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003657
3658 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3659 // where C is a power of 2
3660 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3661 LHSCst->getValue().isPowerOf2()) {
3662 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3663 InsertNewInstBefore(NewOr, I);
3664 return new ICmpInst(LHSCC, NewOr, LHSCst);
3665 }
3666
3667 // From here on, we only handle:
3668 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3669 if (Val != Val2) return 0;
3670
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003671 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3672 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3673 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3674 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3675 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3676 return 0;
3677
3678 // We can't fold (ugt x, C) & (sgt x, C2).
3679 if (!PredicatesFoldable(LHSCC, RHSCC))
3680 return 0;
3681
3682 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003683 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003684 if (ICmpInst::isSignedPredicate(LHSCC) ||
3685 (ICmpInst::isEquality(LHSCC) &&
3686 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003687 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003688 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003689 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3690
3691 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003692 std::swap(LHS, RHS);
3693 std::swap(LHSCst, RHSCst);
3694 std::swap(LHSCC, RHSCC);
3695 }
3696
3697 // At this point, we know we have have two icmp instructions
3698 // comparing a value against two constants and and'ing the result
3699 // together. Because of the above check, we know that we only have
3700 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3701 // (from the FoldICmpLogical check above), that the two constants
3702 // are not equal and that the larger constant is on the RHS
3703 assert(LHSCst != RHSCst && "Compares not folded above?");
3704
3705 switch (LHSCC) {
3706 default: assert(0 && "Unknown integer condition code!");
3707 case ICmpInst::ICMP_EQ:
3708 switch (RHSCC) {
3709 default: assert(0 && "Unknown integer condition code!");
3710 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3711 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3712 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3713 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3714 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3715 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3716 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3717 return ReplaceInstUsesWith(I, LHS);
3718 }
3719 case ICmpInst::ICMP_NE:
3720 switch (RHSCC) {
3721 default: assert(0 && "Unknown integer condition code!");
3722 case ICmpInst::ICMP_ULT:
3723 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3724 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3725 break; // (X != 13 & X u< 15) -> no change
3726 case ICmpInst::ICMP_SLT:
3727 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3728 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3729 break; // (X != 13 & X s< 15) -> no change
3730 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3731 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3732 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3733 return ReplaceInstUsesWith(I, RHS);
3734 case ICmpInst::ICMP_NE:
3735 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3736 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3737 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3738 Val->getName()+".off");
3739 InsertNewInstBefore(Add, I);
3740 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3741 ConstantInt::get(Add->getType(), 1));
3742 }
3743 break; // (X != 13 & X != 15) -> no change
3744 }
3745 break;
3746 case ICmpInst::ICMP_ULT:
3747 switch (RHSCC) {
3748 default: assert(0 && "Unknown integer condition code!");
3749 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3750 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3751 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3752 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3753 break;
3754 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3755 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3756 return ReplaceInstUsesWith(I, LHS);
3757 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3758 break;
3759 }
3760 break;
3761 case ICmpInst::ICMP_SLT:
3762 switch (RHSCC) {
3763 default: assert(0 && "Unknown integer condition code!");
3764 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3765 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3766 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3767 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3768 break;
3769 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3770 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3771 return ReplaceInstUsesWith(I, LHS);
3772 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3773 break;
3774 }
3775 break;
3776 case ICmpInst::ICMP_UGT:
3777 switch (RHSCC) {
3778 default: assert(0 && "Unknown integer condition code!");
3779 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3780 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3781 return ReplaceInstUsesWith(I, RHS);
3782 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3783 break;
3784 case ICmpInst::ICMP_NE:
3785 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3786 return new ICmpInst(LHSCC, Val, RHSCst);
3787 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003788 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003789 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3790 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3791 break;
3792 }
3793 break;
3794 case ICmpInst::ICMP_SGT:
3795 switch (RHSCC) {
3796 default: assert(0 && "Unknown integer condition code!");
3797 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3798 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3799 return ReplaceInstUsesWith(I, RHS);
3800 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3801 break;
3802 case ICmpInst::ICMP_NE:
3803 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3804 return new ICmpInst(LHSCC, Val, RHSCst);
3805 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003806 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003807 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3808 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3809 break;
3810 }
3811 break;
3812 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003813
3814 return 0;
3815}
3816
3817
Chris Lattner7e708292002-06-25 16:13:24 +00003818Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003819 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003820 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003821
Chris Lattnere87597f2004-10-16 18:11:37 +00003822 if (isa<UndefValue>(Op1)) // X & undef -> 0
3823 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3824
Chris Lattner6e7ba452005-01-01 16:22:27 +00003825 // and X, X = X
3826 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003827 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003828
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003829 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003830 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003831 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00003832 if (SimplifyDemandedInstructionBits(I))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003833 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003834 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003835 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003836 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003837 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003838 } else if (isa<ConstantAggregateZero>(Op1)) {
3839 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003840 }
3841 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003842
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003843 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003844 const APInt& AndRHSMask = AndRHS->getValue();
3845 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003846
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003847 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003848 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003849 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003850 Value *Op0LHS = Op0I->getOperand(0);
3851 Value *Op0RHS = Op0I->getOperand(1);
3852 switch (Op0I->getOpcode()) {
3853 case Instruction::Xor:
3854 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003855 // If the mask is only needed on one incoming arm, push it up.
3856 if (Op0I->hasOneUse()) {
3857 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3858 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003859 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003860 Op0RHS->getName()+".masked");
3861 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003862 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003863 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003864 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003865 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003866 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3867 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003868 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003869 Op0LHS->getName()+".masked");
3870 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003871 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003872 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3873 }
3874 }
3875
Chris Lattner6e7ba452005-01-01 16:22:27 +00003876 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003877 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003878 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3879 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3880 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3881 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003882 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003883 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003884 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003885 break;
3886
3887 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003888 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3889 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3890 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3891 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003892 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003893
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003894 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3895 // has 1's for all bits that the subtraction with A might affect.
3896 if (Op0I->hasOneUse()) {
3897 uint32_t BitWidth = AndRHSMask.getBitWidth();
3898 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3899 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3900
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003901 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003902 if (!(A && A->isZero()) && // avoid infinite recursion.
3903 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003904 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3905 InsertNewInstBefore(NewNeg, I);
3906 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3907 }
3908 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003909 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003910
3911 case Instruction::Shl:
3912 case Instruction::LShr:
3913 // (1 << x) & 1 --> zext(x == 0)
3914 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00003915 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003916 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3917 Constant::getNullValue(I.getType()));
3918 InsertNewInstBefore(NewICmp, I);
3919 return new ZExtInst(NewICmp, I.getType());
3920 }
3921 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003922 }
3923
Chris Lattner58403262003-07-23 19:25:52 +00003924 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003925 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003926 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003927 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003928 // If this is an integer truncation or change from signed-to-unsigned, and
3929 // if the source is an and/or with immediate, transform it. This
3930 // frequently occurs for bitfield accesses.
3931 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003932 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003933 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003934 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003935 if (CastOp->getOpcode() == Instruction::And) {
3936 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003937 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3938 // This will fold the two constants together, which may allow
3939 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003940 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003941 CastOp->getOperand(0), I.getType(),
3942 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003943 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003944 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003945 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003946 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003947 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003948 } else if (CastOp->getOpcode() == Instruction::Or) {
3949 // Change: and (cast (or X, C1) to T), C2
3950 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003951 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003952 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3953 return ReplaceInstUsesWith(I, AndRHS);
3954 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003955 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003956 }
Chris Lattner06782f82003-07-23 19:36:21 +00003957 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003958
3959 // Try to fold constant and into select arguments.
3960 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003961 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003962 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003963 if (isa<PHINode>(Op0))
3964 if (Instruction *NV = FoldOpIntoPhi(I))
3965 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003966 }
3967
Chris Lattner8d969642003-03-10 23:06:50 +00003968 Value *Op0NotVal = dyn_castNotVal(Op0);
3969 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003970
Chris Lattner5b62aa72004-06-18 06:07:51 +00003971 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3972 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3973
Misha Brukmancb6267b2004-07-30 12:50:08 +00003974 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003975 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003976 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003977 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003978 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003979 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003980 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003981
3982 {
Chris Lattner003b6202007-06-15 05:58:24 +00003983 Value *A = 0, *B = 0, *C = 0, *D = 0;
3984 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003985 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3986 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003987
3988 // (A|B) & ~(A&B) -> A^B
3989 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3990 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003991 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003992 }
3993 }
3994
3995 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003996 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3997 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003998
3999 // ~(A&B) & (A|B) -> A^B
4000 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4001 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004002 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004003 }
4004 }
Chris Lattner64daab52006-04-01 08:03:55 +00004005
4006 if (Op0->hasOneUse() &&
4007 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4008 if (A == Op1) { // (A^B)&A -> A&(A^B)
4009 I.swapOperands(); // Simplify below
4010 std::swap(Op0, Op1);
4011 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4012 cast<BinaryOperator>(Op0)->swapOperands();
4013 I.swapOperands(); // Simplify below
4014 std::swap(Op0, Op1);
4015 }
4016 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004017
Chris Lattner64daab52006-04-01 08:03:55 +00004018 if (Op1->hasOneUse() &&
4019 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4020 if (B == Op0) { // B&(A^B) -> B&(B^A)
4021 cast<BinaryOperator>(Op1)->swapOperands();
4022 std::swap(A, B);
4023 }
4024 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004025 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004026 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004027 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004028 }
4029 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004030
4031 // (A&((~A)|B)) -> A&B
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004032 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4033 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4034 return BinaryOperator::CreateAnd(A, Op1);
4035 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4036 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4037 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004038 }
4039
Reid Spencere4d87aa2006-12-23 06:05:41 +00004040 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4041 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4042 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004043 return R;
4044
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004045 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4046 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4047 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004048 }
4049
Chris Lattner6fc205f2006-05-05 06:39:07 +00004050 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004051 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4052 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4053 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4054 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004055 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004056 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004057 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4058 I.getType(), TD) &&
4059 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4060 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004061 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004062 Op1C->getOperand(0),
4063 I.getName());
4064 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004065 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004066 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004067 }
Chris Lattnere511b742006-11-14 07:46:50 +00004068
4069 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004070 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4071 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4072 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004073 SI0->getOperand(1) == SI1->getOperand(1) &&
4074 (SI0->hasOneUse() || SI1->hasOneUse())) {
4075 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004076 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004077 SI1->getOperand(0),
4078 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004079 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004080 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004081 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004082 }
4083
Evan Cheng8db90722008-10-14 17:15:11 +00004084 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004085 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4086 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4087 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004088 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4089 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004090 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4091 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4092 // If either of the constants are nans, then the whole thing returns
4093 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004094 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004095 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4096 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4097 RHS->getOperand(0));
4098 }
Evan Cheng8db90722008-10-14 17:15:11 +00004099 } else {
4100 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4101 FCmpInst::Predicate Op0CC, Op1CC;
4102 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4103 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Cheng4990b252008-10-14 18:13:38 +00004104 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4105 // Swap RHS operands to match LHS.
4106 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4107 std::swap(Op1LHS, Op1RHS);
4108 }
Evan Cheng8db90722008-10-14 17:15:11 +00004109 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4110 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4111 if (Op0CC == Op1CC)
4112 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4113 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4114 Op1CC == FCmpInst::FCMP_FALSE)
4115 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4116 else if (Op0CC == FCmpInst::FCMP_TRUE)
4117 return ReplaceInstUsesWith(I, Op1);
4118 else if (Op1CC == FCmpInst::FCMP_TRUE)
4119 return ReplaceInstUsesWith(I, Op0);
4120 bool Op0Ordered;
4121 bool Op1Ordered;
4122 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4123 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4124 if (Op1Pred == 0) {
4125 std::swap(Op0, Op1);
4126 std::swap(Op0Pred, Op1Pred);
4127 std::swap(Op0Ordered, Op1Ordered);
4128 }
4129 if (Op0Pred == 0) {
4130 // uno && ueq -> uno && (uno || eq) -> ueq
4131 // ord && olt -> ord && (ord && lt) -> olt
4132 if (Op0Ordered == Op1Ordered)
4133 return ReplaceInstUsesWith(I, Op1);
4134 // uno && oeq -> uno && (ord && eq) -> false
4135 // uno && ord -> false
4136 if (!Op0Ordered)
4137 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4138 // ord && ueq -> ord && (uno || eq) -> oeq
4139 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4140 Op0LHS, Op0RHS));
4141 }
4142 }
4143 }
4144 }
Chris Lattner99c65742007-10-24 05:38:08 +00004145 }
4146 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004147
Chris Lattner7e708292002-06-25 16:13:24 +00004148 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004149}
4150
Chris Lattner8c34cd22008-10-05 02:13:19 +00004151/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4152/// capable of providing pieces of a bswap. The subexpression provides pieces
4153/// of a bswap if it is proven that each of the non-zero bytes in the output of
4154/// the expression came from the corresponding "byte swapped" byte in some other
4155/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4156/// we know that the expression deposits the low byte of %X into the high byte
4157/// of the bswap result and that all other bytes are zero. This expression is
4158/// accepted, the high byte of ByteValues is set to X to indicate a correct
4159/// match.
4160///
4161/// This function returns true if the match was unsuccessful and false if so.
4162/// On entry to the function the "OverallLeftShift" is a signed integer value
4163/// indicating the number of bytes that the subexpression is later shifted. For
4164/// example, if the expression is later right shifted by 16 bits, the
4165/// OverallLeftShift value would be -2 on entry. This is used to specify which
4166/// byte of ByteValues is actually being set.
4167///
4168/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4169/// byte is masked to zero by a user. For example, in (X & 255), X will be
4170/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4171/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4172/// always in the local (OverallLeftShift) coordinate space.
4173///
4174static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4175 SmallVector<Value*, 8> &ByteValues) {
4176 if (Instruction *I = dyn_cast<Instruction>(V)) {
4177 // If this is an or instruction, it may be an inner node of the bswap.
4178 if (I->getOpcode() == Instruction::Or) {
4179 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4180 ByteValues) ||
4181 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4182 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004183 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004184
4185 // If this is a logical shift by a constant multiple of 8, recurse with
4186 // OverallLeftShift and ByteMask adjusted.
4187 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4188 unsigned ShAmt =
4189 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4190 // Ensure the shift amount is defined and of a byte value.
4191 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4192 return true;
4193
4194 unsigned ByteShift = ShAmt >> 3;
4195 if (I->getOpcode() == Instruction::Shl) {
4196 // X << 2 -> collect(X, +2)
4197 OverallLeftShift += ByteShift;
4198 ByteMask >>= ByteShift;
4199 } else {
4200 // X >>u 2 -> collect(X, -2)
4201 OverallLeftShift -= ByteShift;
4202 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004203 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004204 }
4205
4206 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4207 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4208
4209 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4210 ByteValues);
4211 }
4212
4213 // If this is a logical 'and' with a mask that clears bytes, clear the
4214 // corresponding bytes in ByteMask.
4215 if (I->getOpcode() == Instruction::And &&
4216 isa<ConstantInt>(I->getOperand(1))) {
4217 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4218 unsigned NumBytes = ByteValues.size();
4219 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4220 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4221
4222 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4223 // If this byte is masked out by a later operation, we don't care what
4224 // the and mask is.
4225 if ((ByteMask & (1 << i)) == 0)
4226 continue;
4227
4228 // If the AndMask is all zeros for this byte, clear the bit.
4229 APInt MaskB = AndMask & Byte;
4230 if (MaskB == 0) {
4231 ByteMask &= ~(1U << i);
4232 continue;
4233 }
4234
4235 // If the AndMask is not all ones for this byte, it's not a bytezap.
4236 if (MaskB != Byte)
4237 return true;
4238
4239 // Otherwise, this byte is kept.
4240 }
4241
4242 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4243 ByteValues);
4244 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004245 }
4246
Chris Lattner8c34cd22008-10-05 02:13:19 +00004247 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4248 // the input value to the bswap. Some observations: 1) if more than one byte
4249 // is demanded from this input, then it could not be successfully assembled
4250 // into a byteswap. At least one of the two bytes would not be aligned with
4251 // their ultimate destination.
4252 if (!isPowerOf2_32(ByteMask)) return true;
4253 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004254
Chris Lattner8c34cd22008-10-05 02:13:19 +00004255 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4256 // is demanded, it needs to go into byte 0 of the result. This means that the
4257 // byte needs to be shifted until it lands in the right byte bucket. The
4258 // shift amount depends on the position: if the byte is coming from the high
4259 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4260 // low part, it must be shifted left.
4261 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4262 if (InputByteNo < ByteValues.size()/2) {
4263 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4264 return true;
4265 } else {
4266 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4267 return true;
4268 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004269
4270 // If the destination byte value is already defined, the values are or'd
4271 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004272 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004273 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004274 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004275 return false;
4276}
4277
4278/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4279/// If so, insert the new bswap intrinsic and return it.
4280Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004281 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004282 if (!ITy || ITy->getBitWidth() % 16 ||
4283 // ByteMask only allows up to 32-byte values.
4284 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004285 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004286
4287 /// ByteValues - For each byte of the result, we keep track of which value
4288 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004289 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004290 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004291
4292 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004293 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4294 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004295 return 0;
4296
4297 // Check to see if all of the bytes come from the same value.
4298 Value *V = ByteValues[0];
4299 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4300
4301 // Check to make sure that all of the bytes come from the same value.
4302 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4303 if (ByteValues[i] != V)
4304 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004305 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004306 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004307 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004308 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004309}
4310
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004311/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4312/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4313/// we can simplify this expression to "cond ? C : D or B".
4314static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4315 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004316 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004317 Value *Cond = 0;
Chris Lattner159c35b2009-01-05 23:53:12 +00004318 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004319 return 0;
4320
Chris Lattnera6a474d2008-11-16 04:26:55 +00004321 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner159c35b2009-01-05 23:53:12 +00004322 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004323 return SelectInst::Create(Cond, C, B);
Chris Lattner159c35b2009-01-05 23:53:12 +00004324 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004325 return SelectInst::Create(Cond, C, B);
4326 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner159c35b2009-01-05 23:53:12 +00004327 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004328 return SelectInst::Create(Cond, C, D);
Chris Lattner159c35b2009-01-05 23:53:12 +00004329 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004330 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004331 return 0;
4332}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004333
Chris Lattner69d4ced2008-11-16 05:20:07 +00004334/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4335Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4336 ICmpInst *LHS, ICmpInst *RHS) {
4337 Value *Val, *Val2;
4338 ConstantInt *LHSCst, *RHSCst;
4339 ICmpInst::Predicate LHSCC, RHSCC;
4340
4341 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4342 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4343 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4344 return 0;
4345
4346 // From here on, we only handle:
4347 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4348 if (Val != Val2) return 0;
4349
4350 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4351 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4352 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4353 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4354 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4355 return 0;
4356
4357 // We can't fold (ugt x, C) | (sgt x, C2).
4358 if (!PredicatesFoldable(LHSCC, RHSCC))
4359 return 0;
4360
4361 // Ensure that the larger constant is on the RHS.
4362 bool ShouldSwap;
4363 if (ICmpInst::isSignedPredicate(LHSCC) ||
4364 (ICmpInst::isEquality(LHSCC) &&
4365 ICmpInst::isSignedPredicate(RHSCC)))
4366 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4367 else
4368 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4369
4370 if (ShouldSwap) {
4371 std::swap(LHS, RHS);
4372 std::swap(LHSCst, RHSCst);
4373 std::swap(LHSCC, RHSCC);
4374 }
4375
4376 // At this point, we know we have have two icmp instructions
4377 // comparing a value against two constants and or'ing the result
4378 // together. Because of the above check, we know that we only have
4379 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4380 // FoldICmpLogical check above), that the two constants are not
4381 // equal.
4382 assert(LHSCst != RHSCst && "Compares not folded above?");
4383
4384 switch (LHSCC) {
4385 default: assert(0 && "Unknown integer condition code!");
4386 case ICmpInst::ICMP_EQ:
4387 switch (RHSCC) {
4388 default: assert(0 && "Unknown integer condition code!");
4389 case ICmpInst::ICMP_EQ:
4390 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4391 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4392 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4393 Val->getName()+".off");
4394 InsertNewInstBefore(Add, I);
4395 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4396 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4397 }
4398 break; // (X == 13 | X == 15) -> no change
4399 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4400 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4401 break;
4402 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4403 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4404 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4405 return ReplaceInstUsesWith(I, RHS);
4406 }
4407 break;
4408 case ICmpInst::ICMP_NE:
4409 switch (RHSCC) {
4410 default: assert(0 && "Unknown integer condition code!");
4411 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4412 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4413 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4414 return ReplaceInstUsesWith(I, LHS);
4415 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4416 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4417 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4418 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4419 }
4420 break;
4421 case ICmpInst::ICMP_ULT:
4422 switch (RHSCC) {
4423 default: assert(0 && "Unknown integer condition code!");
4424 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4425 break;
4426 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4427 // If RHSCst is [us]MAXINT, it is always false. Not handling
4428 // this can cause overflow.
4429 if (RHSCst->isMaxValue(false))
4430 return ReplaceInstUsesWith(I, LHS);
4431 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4432 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4433 break;
4434 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4435 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4436 return ReplaceInstUsesWith(I, RHS);
4437 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4438 break;
4439 }
4440 break;
4441 case ICmpInst::ICMP_SLT:
4442 switch (RHSCC) {
4443 default: assert(0 && "Unknown integer condition code!");
4444 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4445 break;
4446 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4447 // If RHSCst is [us]MAXINT, it is always false. Not handling
4448 // this can cause overflow.
4449 if (RHSCst->isMaxValue(true))
4450 return ReplaceInstUsesWith(I, LHS);
4451 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4452 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4453 break;
4454 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4455 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4456 return ReplaceInstUsesWith(I, RHS);
4457 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4458 break;
4459 }
4460 break;
4461 case ICmpInst::ICMP_UGT:
4462 switch (RHSCC) {
4463 default: assert(0 && "Unknown integer condition code!");
4464 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4465 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4466 return ReplaceInstUsesWith(I, LHS);
4467 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4468 break;
4469 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4470 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4471 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4472 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4473 break;
4474 }
4475 break;
4476 case ICmpInst::ICMP_SGT:
4477 switch (RHSCC) {
4478 default: assert(0 && "Unknown integer condition code!");
4479 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4480 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4481 return ReplaceInstUsesWith(I, LHS);
4482 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4483 break;
4484 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4485 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4486 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4487 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4488 break;
4489 }
4490 break;
4491 }
4492 return 0;
4493}
4494
Bill Wendlinga698a472008-12-01 08:23:25 +00004495/// FoldOrWithConstants - This helper function folds:
4496///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004497/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004498///
4499/// into:
4500///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004501/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004502///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004503/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004504Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004505 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004506 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4507 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004508
Bill Wendling286a0542008-12-02 06:24:20 +00004509 Value *V1 = 0;
4510 ConstantInt *CI2 = 0;
4511 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004512
Bill Wendling29976b92008-12-02 06:18:11 +00004513 APInt Xor = CI1->getValue() ^ CI2->getValue();
4514 if (!Xor.isAllOnesValue()) return 0;
4515
Bill Wendling286a0542008-12-02 06:24:20 +00004516 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004517 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004518 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4519 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004520 }
4521
4522 return 0;
4523}
4524
Chris Lattner7e708292002-06-25 16:13:24 +00004525Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004526 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004527 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004528
Chris Lattner42593e62007-03-24 23:56:43 +00004529 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004530 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004531
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004532 // or X, X = X
4533 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004534 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004535
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004536 // See if we can simplify any instructions used by the instruction whose sole
4537 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004538 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004539 if (SimplifyDemandedInstructionBits(I))
Chris Lattner42593e62007-03-24 23:56:43 +00004540 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004541 } else if (isa<ConstantAggregateZero>(Op1)) {
4542 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4543 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4544 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4545 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004546 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004547
4548
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004549
Chris Lattner3f5b8772002-05-06 16:14:14 +00004550 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004551 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004552 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004553 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4554 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004555 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004556 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004557 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004558 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004559 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004560 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004561
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004562 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4563 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004564 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004565 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004566 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004567 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004568 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004569 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004570
4571 // Try to fold constant and into select arguments.
4572 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004573 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004574 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004575 if (isa<PHINode>(Op0))
4576 if (Instruction *NV = FoldOpIntoPhi(I))
4577 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004578 }
4579
Chris Lattner4f637d42006-01-06 17:59:59 +00004580 Value *A = 0, *B = 0;
4581 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004582
4583 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4584 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4585 return ReplaceInstUsesWith(I, Op1);
4586 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4587 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4588 return ReplaceInstUsesWith(I, Op0);
4589
Chris Lattner6423d4c2006-07-10 20:25:24 +00004590 // (A | B) | C and A | (B | C) -> bswap if possible.
4591 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004592 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004593 match(Op1, m_Or(m_Value(), m_Value())) ||
4594 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4595 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004596 if (Instruction *BSwap = MatchBSwap(I))
4597 return BSwap;
4598 }
4599
Chris Lattner6e4c6492005-05-09 04:58:36 +00004600 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4601 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004602 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004603 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004604 InsertNewInstBefore(NOr, I);
4605 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004606 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004607 }
4608
4609 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4610 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004611 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004612 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004613 InsertNewInstBefore(NOr, I);
4614 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004615 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004616 }
4617
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004618 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004619 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004620 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4621 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004622 Value *V1 = 0, *V2 = 0, *V3 = 0;
4623 C1 = dyn_cast<ConstantInt>(C);
4624 C2 = dyn_cast<ConstantInt>(D);
4625 if (C1 && C2) { // (A & C1)|(B & C2)
4626 // If we have: ((V + N) & C1) | (V & C2)
4627 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4628 // replace with V+N.
4629 if (C1->getValue() == ~C2->getValue()) {
4630 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4631 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4632 // Add commutes, try both ways.
4633 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4634 return ReplaceInstUsesWith(I, A);
4635 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4636 return ReplaceInstUsesWith(I, A);
4637 }
4638 // Or commutes, try both ways.
4639 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4640 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4641 // Add commutes, try both ways.
4642 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4643 return ReplaceInstUsesWith(I, B);
4644 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4645 return ReplaceInstUsesWith(I, B);
4646 }
4647 }
Chris Lattner044e5332007-04-08 08:01:49 +00004648 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004649 }
4650
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004651 // Check to see if we have any common things being and'ed. If so, find the
4652 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004653 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4654 if (A == B) // (A & C)|(A & D) == A & (C|D)
4655 V1 = A, V2 = C, V3 = D;
4656 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4657 V1 = A, V2 = B, V3 = C;
4658 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4659 V1 = C, V2 = A, V3 = D;
4660 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4661 V1 = C, V2 = A, V3 = B;
4662
4663 if (V1) {
4664 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004665 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4666 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004667 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004668 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004669
Dan Gohman1975d032008-10-30 20:40:10 +00004670 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004671 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4672 return Match;
4673 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4674 return Match;
4675 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4676 return Match;
4677 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4678 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004679
Bill Wendlingb01865c2008-11-30 13:52:49 +00004680 // ((A&~B)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004681 if ((match(C, m_Not(m_Specific(D))) &&
4682 match(B, m_Not(m_Specific(A)))))
4683 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004684 // ((~B&A)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004685 if ((match(A, m_Not(m_Specific(D))) &&
4686 match(B, m_Not(m_Specific(C)))))
4687 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004688 // ((A&~B)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004689 if ((match(C, m_Not(m_Specific(B))) &&
4690 match(D, m_Not(m_Specific(A)))))
4691 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004692 // ((~B&A)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004693 if ((match(A, m_Not(m_Specific(B))) &&
4694 match(D, m_Not(m_Specific(C)))))
4695 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004696 }
Chris Lattnere511b742006-11-14 07:46:50 +00004697
4698 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004699 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4700 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4701 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004702 SI0->getOperand(1) == SI1->getOperand(1) &&
4703 (SI0->hasOneUse() || SI1->hasOneUse())) {
4704 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004705 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004706 SI1->getOperand(0),
4707 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004708 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004709 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004710 }
4711 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004712
Bill Wendlingb3833d12008-12-01 01:07:11 +00004713 // ((A|B)&1)|(B&-2) -> (A&1) | B
4714 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4715 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004716 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004717 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004718 }
4719 // (B&-2)|((A|B)&1) -> (A&1) | B
4720 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4721 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004722 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004723 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004724 }
4725
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004726 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4727 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004728 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004729 } else {
4730 A = 0;
4731 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004732 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004733 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4734 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004735 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004736
Misha Brukmancb6267b2004-07-30 12:50:08 +00004737 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004738 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004739 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004740 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004741 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004742 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004743 }
Chris Lattnera2881962003-02-18 19:28:33 +00004744
Reid Spencere4d87aa2006-12-23 06:05:41 +00004745 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4746 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4747 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004748 return R;
4749
Chris Lattner69d4ced2008-11-16 05:20:07 +00004750 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4751 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4752 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004753 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004754
4755 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004756 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004757 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004758 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004759 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4760 !isa<ICmpInst>(Op1C->getOperand(0))) {
4761 const Type *SrcTy = Op0C->getOperand(0)->getType();
4762 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4763 // Only do this if the casts both really cause code to be
4764 // generated.
4765 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4766 I.getType(), TD) &&
4767 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4768 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004769 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004770 Op1C->getOperand(0),
4771 I.getName());
4772 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004773 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004774 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004775 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004776 }
Chris Lattner99c65742007-10-24 05:38:08 +00004777 }
4778
4779
4780 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4781 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4782 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4783 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004784 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004785 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004786 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4787 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4788 // If either of the constants are nans, then the whole thing returns
4789 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004790 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004791 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4792
4793 // Otherwise, no need to compare the two constants, compare the
4794 // rest.
4795 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4796 RHS->getOperand(0));
4797 }
Evan Cheng40300622008-10-14 18:44:08 +00004798 } else {
4799 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4800 FCmpInst::Predicate Op0CC, Op1CC;
4801 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4802 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4803 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4804 // Swap RHS operands to match LHS.
4805 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4806 std::swap(Op1LHS, Op1RHS);
4807 }
4808 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4809 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4810 if (Op0CC == Op1CC)
4811 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4812 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4813 Op1CC == FCmpInst::FCMP_TRUE)
4814 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4815 else if (Op0CC == FCmpInst::FCMP_FALSE)
4816 return ReplaceInstUsesWith(I, Op1);
4817 else if (Op1CC == FCmpInst::FCMP_FALSE)
4818 return ReplaceInstUsesWith(I, Op0);
4819 bool Op0Ordered;
4820 bool Op1Ordered;
4821 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4822 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4823 if (Op0Ordered == Op1Ordered) {
4824 // If both are ordered or unordered, return a new fcmp with
4825 // or'ed predicates.
4826 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4827 Op0LHS, Op0RHS);
4828 if (Instruction *I = dyn_cast<Instruction>(RV))
4829 return I;
4830 // Otherwise, it's a constant boolean value...
4831 return ReplaceInstUsesWith(I, RV);
4832 }
4833 }
4834 }
4835 }
Chris Lattner99c65742007-10-24 05:38:08 +00004836 }
4837 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004838
Chris Lattner7e708292002-06-25 16:13:24 +00004839 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004840}
4841
Dan Gohman844731a2008-05-13 00:00:25 +00004842namespace {
4843
Chris Lattnerc317d392004-02-16 01:20:27 +00004844// XorSelf - Implements: X ^ X --> 0
4845struct XorSelf {
4846 Value *RHS;
4847 XorSelf(Value *rhs) : RHS(rhs) {}
4848 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4849 Instruction *apply(BinaryOperator &Xor) const {
4850 return &Xor;
4851 }
4852};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004853
Dan Gohman844731a2008-05-13 00:00:25 +00004854}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004855
Chris Lattner7e708292002-06-25 16:13:24 +00004856Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004857 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004858 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004859
Evan Chengd34af782008-03-25 20:07:13 +00004860 if (isa<UndefValue>(Op1)) {
4861 if (isa<UndefValue>(Op0))
4862 // Handle undef ^ undef -> 0 special case. This is a common
4863 // idiom (misuse).
4864 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004865 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004866 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004867
Chris Lattnerc317d392004-02-16 01:20:27 +00004868 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4869 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004870 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004871 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004872 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004873
4874 // See if we can simplify any instructions used by the instruction whose sole
4875 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004876 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004877 if (SimplifyDemandedInstructionBits(I))
Reid Spencera03d45f2007-03-22 22:19:58 +00004878 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004879 } else if (isa<ConstantAggregateZero>(Op1)) {
4880 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004881 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004882
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004883 // Is this a ~ operation?
4884 if (Value *NotOp = dyn_castNotVal(&I)) {
4885 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4886 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4887 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4888 if (Op0I->getOpcode() == Instruction::And ||
4889 Op0I->getOpcode() == Instruction::Or) {
4890 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4891 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4892 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004893 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004894 Op0I->getOperand(1)->getName()+".not");
4895 InsertNewInstBefore(NotY, I);
4896 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004897 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004898 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004899 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004900 }
4901 }
4902 }
4903 }
4904
4905
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004906 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004907 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00004908 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004909 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004910 return new ICmpInst(ICI->getInversePredicate(),
4911 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004912
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004913 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4914 return new FCmpInst(FCI->getInversePredicate(),
4915 FCI->getOperand(0), FCI->getOperand(1));
4916 }
4917
Nick Lewycky517e1f52008-05-31 19:01:33 +00004918 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4919 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4920 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4921 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4922 Instruction::CastOps Opcode = Op0C->getOpcode();
4923 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4924 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4925 Op0C->getDestTy())) {
4926 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4927 CI->getOpcode(), CI->getInversePredicate(),
4928 CI->getOperand(0), CI->getOperand(1)), I);
4929 NewCI->takeName(CI);
4930 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4931 }
4932 }
4933 }
4934 }
4935 }
4936
Reid Spencere4d87aa2006-12-23 06:05:41 +00004937 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004938 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004939 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4940 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004941 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4942 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004943 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004944 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004945 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004946
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004947 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004948 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004949 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004950 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004951 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004952 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004953 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004954 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004955 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004956 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004957 // (X + C) ^ signbit -> (X + C + signbit)
4958 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004959 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004960
Chris Lattner7c4049c2004-01-12 19:35:11 +00004961 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004962 } else if (Op0I->getOpcode() == Instruction::Or) {
4963 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004964 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004965 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4966 // Anything in both C1 and C2 is known to be zero, remove it from
4967 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004968 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004969 NewRHS = ConstantExpr::getAnd(NewRHS,
4970 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004971 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004972 I.setOperand(0, Op0I->getOperand(0));
4973 I.setOperand(1, NewRHS);
4974 return &I;
4975 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004976 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004977 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004978 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004979
4980 // Try to fold constant and into select arguments.
4981 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004982 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004983 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004984 if (isa<PHINode>(Op0))
4985 if (Instruction *NV = FoldOpIntoPhi(I))
4986 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004987 }
4988
Chris Lattner8d969642003-03-10 23:06:50 +00004989 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004990 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004991 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004992
Chris Lattner8d969642003-03-10 23:06:50 +00004993 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004994 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004995 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004996
Chris Lattner318bf792007-03-18 22:51:34 +00004997
4998 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4999 if (Op1I) {
5000 Value *A, *B;
5001 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5002 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005003 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005004 I.swapOperands();
5005 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005006 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005007 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005008 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005009 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005010 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5011 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5012 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5013 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Chris Lattner318bf792007-03-18 22:51:34 +00005014 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005015 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005016 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005017 std::swap(A, B);
5018 }
Chris Lattner318bf792007-03-18 22:51:34 +00005019 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005020 I.swapOperands(); // Simplified below.
5021 std::swap(Op0, Op1);
5022 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005023 }
Chris Lattner318bf792007-03-18 22:51:34 +00005024 }
5025
5026 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5027 if (Op0I) {
5028 Value *A, *B;
5029 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5030 if (A == Op1) // (B|A)^B == (A|B)^B
5031 std::swap(A, B);
5032 if (B == Op1) { // (A|B)^B == A & ~B
5033 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005034 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5035 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005036 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005037 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5038 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5039 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5040 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Chris Lattner318bf792007-03-18 22:51:34 +00005041 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5042 if (A == Op1) // (A&B)^A -> (B&A)^A
5043 std::swap(A, B);
5044 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005045 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005046 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005047 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5048 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005049 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005050 }
Chris Lattner318bf792007-03-18 22:51:34 +00005051 }
5052
5053 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5054 if (Op0I && Op1I && Op0I->isShift() &&
5055 Op0I->getOpcode() == Op1I->getOpcode() &&
5056 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5057 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5058 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005059 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005060 Op1I->getOperand(0),
5061 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005062 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005063 Op1I->getOperand(1));
5064 }
5065
5066 if (Op0I && Op1I) {
5067 Value *A, *B, *C, *D;
5068 // (A & B)^(A | B) -> A ^ B
5069 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5070 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5071 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005072 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005073 }
5074 // (A | B)^(A & B) -> A ^ B
5075 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5076 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5077 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005078 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005079 }
5080
5081 // (A & B)^(C & D)
5082 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5083 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5084 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5085 // (X & Y)^(X & Y) -> (Y^Z) & X
5086 Value *X = 0, *Y = 0, *Z = 0;
5087 if (A == C)
5088 X = A, Y = B, Z = D;
5089 else if (A == D)
5090 X = A, Y = B, Z = C;
5091 else if (B == C)
5092 X = B, Y = A, Z = D;
5093 else if (B == D)
5094 X = B, Y = A, Z = C;
5095
5096 if (X) {
5097 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005098 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5099 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005100 }
5101 }
5102 }
5103
Reid Spencere4d87aa2006-12-23 06:05:41 +00005104 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5105 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5106 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005107 return R;
5108
Chris Lattner6fc205f2006-05-05 06:39:07 +00005109 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005110 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005111 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005112 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5113 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005114 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005115 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005116 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5117 I.getType(), TD) &&
5118 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5119 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005120 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005121 Op1C->getOperand(0),
5122 I.getName());
5123 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005124 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005125 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005126 }
Chris Lattner99c65742007-10-24 05:38:08 +00005127 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005128
Chris Lattner7e708292002-06-25 16:13:24 +00005129 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005130}
5131
Chris Lattnera96879a2004-09-29 17:40:11 +00005132/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5133/// overflowed for this type.
5134static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005135 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005136 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005137
Reid Spencere4e40032007-03-21 23:19:50 +00005138 if (IsSigned)
5139 if (In2->getValue().isNegative())
5140 return Result->getValue().sgt(In1->getValue());
5141 else
5142 return Result->getValue().slt(In1->getValue());
5143 else
5144 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005145}
5146
Dan Gohman1df3fd62008-09-10 23:30:57 +00005147/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5148/// overflowed for this type.
5149static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5150 ConstantInt *In2, bool IsSigned = false) {
Dan Gohmanbcb37fd2008-09-11 18:53:02 +00005151 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohman1df3fd62008-09-10 23:30:57 +00005152
5153 if (IsSigned)
5154 if (In2->getValue().isNegative())
5155 return Result->getValue().slt(In1->getValue());
5156 else
5157 return Result->getValue().sgt(In1->getValue());
5158 else
5159 return Result->getValue().ugt(In1->getValue());
5160}
5161
Chris Lattner574da9b2005-01-13 20:14:25 +00005162/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5163/// code necessary to compute the offset from the base pointer (without adding
5164/// in the base pointer). Return the result as a signed integer of intptr size.
5165static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5166 TargetData &TD = IC.getTargetData();
5167 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005168 const Type *IntPtrTy = TD.getIntPtrType();
5169 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005170
5171 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005172 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005173 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005174
Gabor Greif177dd3f2008-06-12 21:37:33 +00005175 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5176 ++i, ++GTI) {
5177 Value *Op = *i;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005178 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005179 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5180 if (OpC->isZero()) continue;
5181
5182 // Handle a struct index, which adds its field offset to the pointer.
5183 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5184 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5185
5186 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5187 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005188 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005189 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005190 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005191 ConstantInt::get(IntPtrTy, Size),
5192 GEP->getName()+".offs"), I);
5193 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005194 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005195
5196 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5197 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5198 Scale = ConstantExpr::getMul(OC, Scale);
5199 if (Constant *RC = dyn_cast<Constant>(Result))
5200 Result = ConstantExpr::getAdd(RC, Scale);
5201 else {
5202 // Emit an add instruction.
5203 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005204 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005205 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005206 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005207 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005208 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005209 // Convert to correct type.
5210 if (Op->getType() != IntPtrTy) {
5211 if (Constant *OpC = dyn_cast<Constant>(Op))
5212 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5213 else
5214 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5215 Op->getName()+".c"), I);
5216 }
5217 if (Size != 1) {
5218 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5219 if (Constant *OpC = dyn_cast<Constant>(Op))
5220 Op = ConstantExpr::getMul(OpC, Scale);
5221 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005222 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005223 GEP->getName()+".idx"), I);
5224 }
5225
5226 // Emit an add instruction.
5227 if (isa<Constant>(Op) && isa<Constant>(Result))
5228 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5229 cast<Constant>(Result));
5230 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005231 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005232 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005233 }
5234 return Result;
5235}
5236
Chris Lattner10c0d912008-04-22 02:53:33 +00005237
5238/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5239/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5240/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5241/// complex, and scales are involved. The above expression would also be legal
5242/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5243/// later form is less amenable to optimization though, and we are allowed to
5244/// generate the first by knowing that pointer arithmetic doesn't overflow.
5245///
5246/// If we can't emit an optimized form for this expression, this returns null.
5247///
5248static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5249 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005250 TargetData &TD = IC.getTargetData();
5251 gep_type_iterator GTI = gep_type_begin(GEP);
5252
5253 // Check to see if this gep only has a single variable index. If so, and if
5254 // any constant indices are a multiple of its scale, then we can compute this
5255 // in terms of the scale of the variable index. For example, if the GEP
5256 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5257 // because the expression will cross zero at the same point.
5258 unsigned i, e = GEP->getNumOperands();
5259 int64_t Offset = 0;
5260 for (i = 1; i != e; ++i, ++GTI) {
5261 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5262 // Compute the aggregate offset of constant indices.
5263 if (CI->isZero()) continue;
5264
5265 // Handle a struct index, which adds its field offset to the pointer.
5266 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5267 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5268 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005269 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005270 Offset += Size*CI->getSExtValue();
5271 }
5272 } else {
5273 // Found our variable index.
5274 break;
5275 }
5276 }
5277
5278 // If there are no variable indices, we must have a constant offset, just
5279 // evaluate it the general way.
5280 if (i == e) return 0;
5281
5282 Value *VariableIdx = GEP->getOperand(i);
5283 // Determine the scale factor of the variable element. For example, this is
5284 // 4 if the variable index is into an array of i32.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005285 uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005286
5287 // Verify that there are no other variable indices. If so, emit the hard way.
5288 for (++i, ++GTI; i != e; ++i, ++GTI) {
5289 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5290 if (!CI) return 0;
5291
5292 // Compute the aggregate offset of constant indices.
5293 if (CI->isZero()) continue;
5294
5295 // Handle a struct index, which adds its field offset to the pointer.
5296 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5297 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5298 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005299 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005300 Offset += Size*CI->getSExtValue();
5301 }
5302 }
5303
5304 // Okay, we know we have a single variable index, which must be a
5305 // pointer/array/vector index. If there is no offset, life is simple, return
5306 // the index.
5307 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5308 if (Offset == 0) {
5309 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5310 // we don't need to bother extending: the extension won't affect where the
5311 // computation crosses zero.
5312 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5313 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5314 VariableIdx->getNameStart(), &I);
5315 return VariableIdx;
5316 }
5317
5318 // Otherwise, there is an index. The computation we will do will be modulo
5319 // the pointer size, so get it.
5320 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5321
5322 Offset &= PtrSizeMask;
5323 VariableScale &= PtrSizeMask;
5324
5325 // To do this transformation, any constant index must be a multiple of the
5326 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5327 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5328 // multiple of the variable scale.
5329 int64_t NewOffs = Offset / (int64_t)VariableScale;
5330 if (Offset != NewOffs*(int64_t)VariableScale)
5331 return 0;
5332
5333 // Okay, we can do this evaluation. Start by converting the index to intptr.
5334 const Type *IntPtrTy = TD.getIntPtrType();
5335 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005336 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005337 true /*SExt*/,
5338 VariableIdx->getNameStart(), &I);
5339 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005340 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005341}
5342
5343
Reid Spencere4d87aa2006-12-23 06:05:41 +00005344/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005345/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005346Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5347 ICmpInst::Predicate Cond,
5348 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005349 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005350
Chris Lattner10c0d912008-04-22 02:53:33 +00005351 // Look through bitcasts.
5352 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5353 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005354
Chris Lattner574da9b2005-01-13 20:14:25 +00005355 Value *PtrBase = GEPLHS->getOperand(0);
5356 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005357 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005358 // This transformation (ignoring the base and scales) is valid because we
5359 // know pointers can't overflow. See if we can output an optimized form.
5360 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5361
5362 // If not, synthesize the offset the hard way.
5363 if (Offset == 0)
5364 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005365 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5366 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005367 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005368 // If the base pointers are different, but the indices are the same, just
5369 // compare the base pointer.
5370 if (PtrBase != GEPRHS->getOperand(0)) {
5371 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005372 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005373 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005374 if (IndicesTheSame)
5375 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5376 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5377 IndicesTheSame = false;
5378 break;
5379 }
5380
5381 // If all indices are the same, just compare the base pointers.
5382 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005383 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5384 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005385
5386 // Otherwise, the base pointers are different and the indices are
5387 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005388 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005389 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005390
Chris Lattnere9d782b2005-01-13 22:25:21 +00005391 // If one of the GEPs has all zero indices, recurse.
5392 bool AllZeros = true;
5393 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5394 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5395 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5396 AllZeros = false;
5397 break;
5398 }
5399 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005400 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5401 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005402
5403 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005404 AllZeros = true;
5405 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5406 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5407 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5408 AllZeros = false;
5409 break;
5410 }
5411 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005412 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005413
Chris Lattner4401c9c2005-01-14 00:20:05 +00005414 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5415 // If the GEPs only differ by one index, compare it.
5416 unsigned NumDifferences = 0; // Keep track of # differences.
5417 unsigned DiffOperand = 0; // The operand that differs.
5418 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5419 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005420 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5421 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005422 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005423 NumDifferences = 2;
5424 break;
5425 } else {
5426 if (NumDifferences++) break;
5427 DiffOperand = i;
5428 }
5429 }
5430
5431 if (NumDifferences == 0) // SAME GEP?
5432 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005433 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005434 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005435
Chris Lattner4401c9c2005-01-14 00:20:05 +00005436 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005437 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5438 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005439 // Make sure we do a signed comparison here.
5440 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005441 }
5442 }
5443
Reid Spencere4d87aa2006-12-23 06:05:41 +00005444 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005445 // the result to fold to a constant!
5446 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5447 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5448 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5449 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5450 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005451 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005452 }
5453 }
5454 return 0;
5455}
5456
Chris Lattnera5406232008-05-19 20:18:56 +00005457/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5458///
5459Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5460 Instruction *LHSI,
5461 Constant *RHSC) {
5462 if (!isa<ConstantFP>(RHSC)) return 0;
5463 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5464
5465 // Get the width of the mantissa. We don't want to hack on conversions that
5466 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005467 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005468 if (MantissaWidth == -1) return 0; // Unknown.
5469
5470 // Check to see that the input is converted from an integer type that is small
5471 // enough that preserves all bits. TODO: check here for "known" sign bits.
5472 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5473 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5474
5475 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005476 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5477 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005478 ++InputSize;
5479
5480 // If the conversion would lose info, don't hack on this.
5481 if ((int)InputSize > MantissaWidth)
5482 return 0;
5483
5484 // Otherwise, we can potentially simplify the comparison. We know that it
5485 // will always come through as an integer value and we know the constant is
5486 // not a NAN (it would have been previously simplified).
5487 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5488
5489 ICmpInst::Predicate Pred;
5490 switch (I.getPredicate()) {
5491 default: assert(0 && "Unexpected predicate!");
5492 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005493 case FCmpInst::FCMP_OEQ:
5494 Pred = ICmpInst::ICMP_EQ;
5495 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005496 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005497 case FCmpInst::FCMP_OGT:
5498 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5499 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005500 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005501 case FCmpInst::FCMP_OGE:
5502 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5503 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005504 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005505 case FCmpInst::FCMP_OLT:
5506 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5507 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005508 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005509 case FCmpInst::FCMP_OLE:
5510 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5511 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005512 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005513 case FCmpInst::FCMP_ONE:
5514 Pred = ICmpInst::ICMP_NE;
5515 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005516 case FCmpInst::FCMP_ORD:
Eli Friedman8b019c82008-11-30 22:48:49 +00005517 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005518 case FCmpInst::FCMP_UNO:
Eli Friedman8b019c82008-11-30 22:48:49 +00005519 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005520 }
5521
5522 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5523
5524 // Now we know that the APFloat is a normal number, zero or inf.
5525
Chris Lattner85162782008-05-20 03:50:52 +00005526 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005527 // comparing an i8 to 300.0.
5528 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5529
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005530 if (!LHSUnsigned) {
5531 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5532 // and large values.
5533 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5534 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5535 APFloat::rmNearestTiesToEven);
5536 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5537 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5538 Pred == ICmpInst::ICMP_SLE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005539 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5540 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005541 }
5542 } else {
5543 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5544 // +INF and large values.
5545 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5546 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5547 APFloat::rmNearestTiesToEven);
5548 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5549 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5550 Pred == ICmpInst::ICMP_ULE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005551 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5552 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005553 }
Chris Lattnera5406232008-05-19 20:18:56 +00005554 }
5555
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005556 if (!LHSUnsigned) {
5557 // See if the RHS value is < SignedMin.
5558 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5559 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5560 APFloat::rmNearestTiesToEven);
5561 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5562 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5563 Pred == ICmpInst::ICMP_SGE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005564 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5565 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005566 }
Chris Lattnera5406232008-05-19 20:18:56 +00005567 }
5568
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005569 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5570 // [0, UMAX], but it may still be fractional. See if it is fractional by
5571 // casting the FP value to the integer value and back, checking for equality.
5572 // Don't do this for zero, because -0.0 is not fractional.
Chris Lattnera5406232008-05-19 20:18:56 +00005573 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5574 if (!RHS.isZero() &&
5575 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005576 // If we had a comparison against a fractional value, we have to adjust the
5577 // compare predicate and sometimes the value. RHSC is rounded towards zero
5578 // at this point.
Chris Lattnera5406232008-05-19 20:18:56 +00005579 switch (Pred) {
5580 default: assert(0 && "Unexpected integer comparison!");
5581 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedman8b019c82008-11-30 22:48:49 +00005582 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005583 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Eli Friedman8b019c82008-11-30 22:48:49 +00005584 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005585 case ICmpInst::ICMP_ULE:
5586 // (float)int <= 4.4 --> int <= 4
5587 // (float)int <= -4.4 --> false
5588 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005589 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005590 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005591 case ICmpInst::ICMP_SLE:
5592 // (float)int <= 4.4 --> int <= 4
5593 // (float)int <= -4.4 --> int < -4
5594 if (RHS.isNegative())
5595 Pred = ICmpInst::ICMP_SLT;
5596 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005597 case ICmpInst::ICMP_ULT:
5598 // (float)int < -4.4 --> false
5599 // (float)int < 4.4 --> int <= 4
5600 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005601 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005602 Pred = ICmpInst::ICMP_ULE;
5603 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005604 case ICmpInst::ICMP_SLT:
5605 // (float)int < -4.4 --> int < -4
5606 // (float)int < 4.4 --> int <= 4
5607 if (!RHS.isNegative())
5608 Pred = ICmpInst::ICMP_SLE;
5609 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005610 case ICmpInst::ICMP_UGT:
5611 // (float)int > 4.4 --> int > 4
5612 // (float)int > -4.4 --> true
5613 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005614 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005615 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005616 case ICmpInst::ICMP_SGT:
5617 // (float)int > 4.4 --> int > 4
5618 // (float)int > -4.4 --> int >= -4
5619 if (RHS.isNegative())
5620 Pred = ICmpInst::ICMP_SGE;
5621 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005622 case ICmpInst::ICMP_UGE:
5623 // (float)int >= -4.4 --> true
5624 // (float)int >= 4.4 --> int > 4
5625 if (!RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005626 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005627 Pred = ICmpInst::ICMP_UGT;
5628 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005629 case ICmpInst::ICMP_SGE:
5630 // (float)int >= -4.4 --> int >= -4
5631 // (float)int >= 4.4 --> int > 4
5632 if (!RHS.isNegative())
5633 Pred = ICmpInst::ICMP_SGT;
5634 break;
5635 }
5636 }
5637
5638 // Lower this FP comparison into an appropriate integer version of the
5639 // comparison.
5640 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5641}
5642
Reid Spencere4d87aa2006-12-23 06:05:41 +00005643Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5644 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005645 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005646
Chris Lattner58e97462007-01-14 19:42:17 +00005647 // Fold trivial predicates.
5648 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005649 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005650 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005651 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005652
5653 // Simplify 'fcmp pred X, X'
5654 if (Op0 == Op1) {
5655 switch (I.getPredicate()) {
5656 default: assert(0 && "Unknown predicate!");
5657 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5658 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5659 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedman8b019c82008-11-30 22:48:49 +00005660 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005661 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5662 case FCmpInst::FCMP_OLT: // True if ordered and less than
5663 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedman8b019c82008-11-30 22:48:49 +00005664 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005665
5666 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5667 case FCmpInst::FCMP_ULT: // True if unordered or less than
5668 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5669 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5670 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5671 I.setPredicate(FCmpInst::FCMP_UNO);
5672 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5673 return &I;
5674
5675 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5676 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5677 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5678 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5679 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5680 I.setPredicate(FCmpInst::FCMP_ORD);
5681 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5682 return &I;
5683 }
5684 }
5685
Reid Spencere4d87aa2006-12-23 06:05:41 +00005686 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005687 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005688
Reid Spencere4d87aa2006-12-23 06:05:41 +00005689 // Handle fcmp with constant RHS
5690 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005691 // If the constant is a nan, see if we can fold the comparison based on it.
5692 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5693 if (CFP->getValueAPF().isNaN()) {
5694 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedman8b019c82008-11-30 22:48:49 +00005695 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005696 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5697 "Comparison must be either ordered or unordered!");
5698 // True if unordered.
Eli Friedman8b019c82008-11-30 22:48:49 +00005699 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005700 }
5701 }
5702
Reid Spencere4d87aa2006-12-23 06:05:41 +00005703 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5704 switch (LHSI->getOpcode()) {
5705 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005706 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5707 // block. If in the same block, we're encouraging jump threading. If
5708 // not, we are just pessimizing the code by making an i1 phi.
5709 if (LHSI->getParent() == I.getParent())
5710 if (Instruction *NV = FoldOpIntoPhi(I))
5711 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005712 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005713 case Instruction::SIToFP:
5714 case Instruction::UIToFP:
5715 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5716 return NV;
5717 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005718 case Instruction::Select:
5719 // If either operand of the select is a constant, we can fold the
5720 // comparison into the select arms, which will cause one to be
5721 // constant folded and the select turned into a bitwise or.
5722 Value *Op1 = 0, *Op2 = 0;
5723 if (LHSI->hasOneUse()) {
5724 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5725 // Fold the known value into the constant operand.
5726 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5727 // Insert a new FCmp of the other select operand.
5728 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5729 LHSI->getOperand(2), RHSC,
5730 I.getName()), I);
5731 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5732 // Fold the known value into the constant operand.
5733 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5734 // Insert a new FCmp of the other select operand.
5735 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5736 LHSI->getOperand(1), RHSC,
5737 I.getName()), I);
5738 }
5739 }
5740
5741 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005742 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005743 break;
5744 }
5745 }
5746
5747 return Changed ? &I : 0;
5748}
5749
5750Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5751 bool Changed = SimplifyCompare(I);
5752 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5753 const Type *Ty = Op0->getType();
5754
5755 // icmp X, X
5756 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005757 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005758 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005759
5760 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005761 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005762
Reid Spencere4d87aa2006-12-23 06:05:41 +00005763 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005764 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005765 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5766 isa<ConstantPointerNull>(Op0)) &&
5767 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005768 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005769 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005770 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005771
Reid Spencere4d87aa2006-12-23 06:05:41 +00005772 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005773 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005774 switch (I.getPredicate()) {
5775 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005776 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005777 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005778 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005779 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005780 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005781 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005782 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005783
Reid Spencere4d87aa2006-12-23 06:05:41 +00005784 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005785 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005786 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005787 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005788 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005789 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005790 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005791 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005792 case ICmpInst::ICMP_SGT:
5793 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005794 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005795 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5796 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5797 InsertNewInstBefore(Not, I);
5798 return BinaryOperator::CreateAnd(Not, Op0);
5799 }
5800 case ICmpInst::ICMP_UGE:
5801 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5802 // FALL THROUGH
5803 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005804 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005805 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005806 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005807 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005808 case ICmpInst::ICMP_SGE:
5809 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5810 // FALL THROUGH
5811 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5812 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5813 InsertNewInstBefore(Not, I);
5814 return BinaryOperator::CreateOr(Not, Op0);
5815 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005816 }
Chris Lattner8b170942002-08-09 23:47:40 +00005817 }
5818
Dan Gohman81b28ce2008-09-16 18:46:06 +00005819 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005820 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerf2991842008-07-11 04:09:09 +00005821 Value *A, *B;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005822
Chris Lattnerb6566012008-01-05 01:18:20 +00005823 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5824 if (I.isEquality() && CI->isNullValue() &&
5825 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5826 // (icmp cond A B) if cond is equality
5827 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005828 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005829
Dan Gohman81b28ce2008-09-16 18:46:06 +00005830 // If we have an icmp le or icmp ge instruction, turn it into the
5831 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5832 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005833 switch (I.getPredicate()) {
5834 default: break;
5835 case ICmpInst::ICMP_ULE:
5836 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5837 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5838 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5839 case ICmpInst::ICMP_SLE:
5840 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5841 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5842 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5843 case ICmpInst::ICMP_UGE:
5844 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5845 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5846 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5847 case ICmpInst::ICMP_SGE:
5848 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5849 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5850 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5851 }
5852
Chris Lattner183661e2008-07-11 05:40:05 +00005853 // See if we can fold the comparison based on range information we can get
5854 // by checking whether bits are known to be zero or one in the input.
5855 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5856 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5857
5858 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005859 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005860 bool UnusedBit;
5861 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5862
Chris Lattner886ab6c2009-01-31 08:15:18 +00005863 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00005864 isSignBit ? APInt::getSignBit(BitWidth)
5865 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005866 KnownZero, KnownOne, 0))
5867 return &I;
5868
5869 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00005870 // in. Compute the Min, Max and RHS values based on the known bits. For the
5871 // EQ and NE we use unsigned values.
5872 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner84dff672008-07-11 05:08:55 +00005873 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5874 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5875 else
5876 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5877
Chris Lattner183661e2008-07-11 05:40:05 +00005878 // If Min and Max are known to be the same, then SimplifyDemandedBits
5879 // figured out that the LHS is a constant. Just constant fold this now so
5880 // that code below can assume that Min != Max.
5881 if (Min == Max)
5882 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5883 ConstantInt::get(Min),
5884 CI));
5885
5886 // Based on the range information we know about the LHS, see if we can
5887 // simplify this comparison. For example, (x&4) < 8 is always true.
5888 const APInt &RHSVal = CI->getValue();
Chris Lattner84dff672008-07-11 05:08:55 +00005889 switch (I.getPredicate()) { // LE/GE have been folded already.
5890 default: assert(0 && "Unknown icmp opcode!");
5891 case ICmpInst::ICMP_EQ:
5892 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5893 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5894 break;
5895 case ICmpInst::ICMP_NE:
5896 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5897 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5898 break;
5899 case ICmpInst::ICMP_ULT:
Chris Lattner183661e2008-07-11 05:40:05 +00005900 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005901 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005902 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005903 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005904 if (RHSVal == Max) // A <u MAX -> A != MAX
5905 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5906 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5907 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5908
5909 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5910 if (CI->isMinValue(true))
5911 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5912 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005913 break;
5914 case ICmpInst::ICMP_UGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005915 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005916 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005917 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005918 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005919
5920 if (RHSVal == Min) // A >u MIN -> A != MIN
5921 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5922 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5923 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5924
5925 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5926 if (CI->isMaxValue(true))
5927 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5928 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005929 break;
5930 case ICmpInst::ICMP_SLT:
Chris Lattner183661e2008-07-11 05:40:05 +00005931 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005932 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerd01bee72008-07-11 06:40:29 +00005933 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005934 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005935 if (RHSVal == Max) // A <s MAX -> A != MAX
5936 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattnera8ff4a82008-07-11 06:36:01 +00005937 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattnerf9685ac2008-07-11 06:38:16 +00005938 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005939 break;
5940 case ICmpInst::ICMP_SGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005941 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005942 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005943 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005944 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005945
5946 if (RHSVal == Min) // A >s MIN -> A != MIN
5947 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5948 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5949 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005950 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005951 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00005952 }
5953
5954 // Test if the ICmpInst instruction is used exclusively by a select as
5955 // part of a minimum or maximum operation. If so, refrain from doing
5956 // any other folding. This helps out other analyses which understand
5957 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5958 // and CodeGen. And in this case, at least one of the comparison
5959 // operands has at least one user besides the compare (the select),
5960 // which would often largely negate the benefit of folding anyway.
5961 if (I.hasOneUse())
5962 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5963 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5964 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5965 return 0;
5966
5967 // See if we are doing a comparison between a constant and an instruction that
5968 // can be folded into the comparison.
5969 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005970 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005971 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005972 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005973 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005974 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5975 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005976 }
5977
Chris Lattner01deb9d2007-04-03 17:43:25 +00005978 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005979 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5980 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5981 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005982 case Instruction::GetElementPtr:
5983 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005984 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005985 bool isAllZeros = true;
5986 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5987 if (!isa<Constant>(LHSI->getOperand(i)) ||
5988 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5989 isAllZeros = false;
5990 break;
5991 }
5992 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005993 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005994 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5995 }
5996 break;
5997
Chris Lattner6970b662005-04-23 15:31:55 +00005998 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005999 // Only fold icmp into the PHI if the phi and fcmp are in the same
6000 // block. If in the same block, we're encouraging jump threading. If
6001 // not, we are just pessimizing the code by making an i1 phi.
6002 if (LHSI->getParent() == I.getParent())
6003 if (Instruction *NV = FoldOpIntoPhi(I))
6004 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006005 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006006 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006007 // If either operand of the select is a constant, we can fold the
6008 // comparison into the select arms, which will cause one to be
6009 // constant folded and the select turned into a bitwise or.
6010 Value *Op1 = 0, *Op2 = 0;
6011 if (LHSI->hasOneUse()) {
6012 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6013 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006014 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6015 // Insert a new ICmp of the other select operand.
6016 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6017 LHSI->getOperand(2), RHSC,
6018 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006019 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6020 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006021 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6022 // Insert a new ICmp of the other select operand.
6023 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6024 LHSI->getOperand(1), RHSC,
6025 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006026 }
6027 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006028
Chris Lattner6970b662005-04-23 15:31:55 +00006029 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006030 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006031 break;
6032 }
Chris Lattner4802d902007-04-06 18:57:34 +00006033 case Instruction::Malloc:
6034 // If we have (malloc != null), and if the malloc has a single use, we
6035 // can assume it is successful and remove the malloc.
6036 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6037 AddToWorkList(LHSI);
6038 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006039 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006040 }
6041 break;
6042 }
Chris Lattner6970b662005-04-23 15:31:55 +00006043 }
6044
Reid Spencere4d87aa2006-12-23 06:05:41 +00006045 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006046 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006047 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006048 return NI;
6049 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006050 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6051 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006052 return NI;
6053
Reid Spencere4d87aa2006-12-23 06:05:41 +00006054 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006055 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6056 // now.
6057 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6058 if (isa<PointerType>(Op0->getType()) &&
6059 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006060 // We keep moving the cast from the left operand over to the right
6061 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006062 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006063
Chris Lattner57d86372007-01-06 01:45:59 +00006064 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6065 // so eliminate it as well.
6066 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6067 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006068
Chris Lattnerde90b762003-11-03 04:25:02 +00006069 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006070 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006071 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006072 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006073 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006074 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006075 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006076 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006077 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006078 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006079 }
Chris Lattner57d86372007-01-06 01:45:59 +00006080 }
6081
6082 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006083 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006084 // This comes up when you have code like
6085 // int X = A < B;
6086 // if (X) ...
6087 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006088 // with a constant or another cast from the same type.
6089 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006090 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006091 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006092 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006093
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006094 // See if it's the same type of instruction on the left and right.
6095 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6096 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006097 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6098 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6099 I.isEquality()) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006100 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006101 default: break;
6102 case Instruction::Add:
6103 case Instruction::Sub:
6104 case Instruction::Xor:
Nick Lewycky5d52c452008-08-21 05:56:10 +00006105 // a+x icmp eq/ne b+x --> a icmp b
6106 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6107 Op1I->getOperand(0));
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006108 break;
6109 case Instruction::Mul:
Nick Lewycky5d52c452008-08-21 05:56:10 +00006110 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6111 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6112 // Mask = -1 >> count-trailing-zeros(Cst).
6113 if (!CI->isZero() && !CI->isOne()) {
6114 const APInt &AP = CI->getValue();
6115 ConstantInt *Mask = ConstantInt::get(
6116 APInt::getLowBitsSet(AP.getBitWidth(),
6117 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006118 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006119 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6120 Mask);
6121 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6122 Mask);
6123 InsertNewInstBefore(And1, I);
6124 InsertNewInstBefore(And2, I);
6125 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006126 }
6127 }
6128 break;
6129 }
6130 }
6131 }
6132 }
6133
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006134 // ~x < ~y --> y < x
6135 { Value *A, *B;
6136 if (match(Op0, m_Not(m_Value(A))) &&
6137 match(Op1, m_Not(m_Value(B))))
6138 return new ICmpInst(I.getPredicate(), B, A);
6139 }
6140
Chris Lattner65b72ba2006-09-18 04:22:48 +00006141 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006142 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006143
6144 // -x == -y --> x == y
6145 if (match(Op0, m_Neg(m_Value(A))) &&
6146 match(Op1, m_Neg(m_Value(B))))
6147 return new ICmpInst(I.getPredicate(), A, B);
6148
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006149 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6150 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6151 Value *OtherVal = A == Op1 ? B : A;
6152 return new ICmpInst(I.getPredicate(), OtherVal,
6153 Constant::getNullValue(A->getType()));
6154 }
6155
6156 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6157 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006158 ConstantInt *C1, *C2;
6159 if (match(B, m_ConstantInt(C1)) &&
6160 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6161 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6162 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6163 return new ICmpInst(I.getPredicate(), A,
6164 InsertNewInstBefore(Xor, I));
6165 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006166
6167 // A^B == A^D -> B == D
6168 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6169 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6170 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6171 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6172 }
6173 }
6174
6175 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6176 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006177 // A == (A^B) -> B == 0
6178 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006179 return new ICmpInst(I.getPredicate(), OtherVal,
6180 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006181 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006182
6183 // (A-B) == A -> B == 0
6184 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6185 return new ICmpInst(I.getPredicate(), B,
6186 Constant::getNullValue(B->getType()));
6187
6188 // A == (A-B) -> B == 0
6189 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006190 return new ICmpInst(I.getPredicate(), B,
6191 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006192
Chris Lattner9c2328e2006-11-14 06:06:06 +00006193 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6194 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6195 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6196 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6197 Value *X = 0, *Y = 0, *Z = 0;
6198
6199 if (A == C) {
6200 X = B; Y = D; Z = A;
6201 } else if (A == D) {
6202 X = B; Y = C; Z = A;
6203 } else if (B == C) {
6204 X = A; Y = D; Z = B;
6205 } else if (B == D) {
6206 X = A; Y = C; Z = B;
6207 }
6208
6209 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006210 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6211 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006212 I.setOperand(0, Op1);
6213 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6214 return &I;
6215 }
6216 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006217 }
Chris Lattner7e708292002-06-25 16:13:24 +00006218 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006219}
6220
Chris Lattner562ef782007-06-20 23:46:26 +00006221
6222/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6223/// and CmpRHS are both known to be integer constants.
6224Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6225 ConstantInt *DivRHS) {
6226 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6227 const APInt &CmpRHSV = CmpRHS->getValue();
6228
6229 // FIXME: If the operand types don't match the type of the divide
6230 // then don't attempt this transform. The code below doesn't have the
6231 // logic to deal with a signed divide and an unsigned compare (and
6232 // vice versa). This is because (x /s C1) <s C2 produces different
6233 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6234 // (x /u C1) <u C2. Simply casting the operands and result won't
6235 // work. :( The if statement below tests that condition and bails
6236 // if it finds it.
6237 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6238 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6239 return 0;
6240 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006241 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006242 if (DivIsSigned && DivRHS->isAllOnesValue())
6243 return 0; // The overflow computation also screws up here
6244 if (DivRHS->isOne())
6245 return 0; // Not worth bothering, and eliminates some funny cases
6246 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006247
6248 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6249 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6250 // C2 (CI). By solving for X we can turn this into a range check
6251 // instead of computing a divide.
6252 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6253
6254 // Determine if the product overflows by seeing if the product is
6255 // not equal to the divide. Make sure we do the same kind of divide
6256 // as in the LHS instruction that we're folding.
6257 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6258 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6259
6260 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006261 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006262
Chris Lattner1dbfd482007-06-21 18:11:19 +00006263 // Figure out the interval that is being checked. For example, a comparison
6264 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6265 // Compute this interval based on the constants involved and the signedness of
6266 // the compare/divide. This computes a half-open interval, keeping track of
6267 // whether either value in the interval overflows. After analysis each
6268 // overflow variable is set to 0 if it's corresponding bound variable is valid
6269 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6270 int LoOverflow = 0, HiOverflow = 0;
6271 ConstantInt *LoBound = 0, *HiBound = 0;
6272
Chris Lattner562ef782007-06-20 23:46:26 +00006273 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006274 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006275 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006276 HiOverflow = LoOverflow = ProdOV;
6277 if (!HiOverflow)
6278 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006279 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006280 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006281 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006282 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6283 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006284 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006285 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6286 HiOverflow = LoOverflow = ProdOV;
6287 if (!HiOverflow)
6288 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006289 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006290 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006291 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006292 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6293 if (!LoOverflow) {
6294 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6295 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6296 true) ? -1 : 0;
6297 }
Chris Lattner562ef782007-06-20 23:46:26 +00006298 }
Dan Gohman76491272008-02-13 22:09:18 +00006299 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006300 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006301 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006302 LoBound = AddOne(DivRHS);
6303 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006304 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6305 HiOverflow = 1; // [INTMIN+1, overflow)
6306 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6307 }
Dan Gohman76491272008-02-13 22:09:18 +00006308 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006309 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnera6321b42008-10-11 22:55:00 +00006310 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006311 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006312 if (!LoOverflow)
Chris Lattnera6321b42008-10-11 22:55:00 +00006313 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006314 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006315 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6316 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006317 if (!HiOverflow)
6318 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006319 }
6320
Chris Lattner1dbfd482007-06-21 18:11:19 +00006321 // Dividing by a negative swaps the condition. LT <-> GT
6322 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006323 }
6324
6325 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006326 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006327 default: assert(0 && "Unhandled icmp opcode!");
6328 case ICmpInst::ICMP_EQ:
6329 if (LoOverflow && HiOverflow)
6330 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6331 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006332 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006333 ICmpInst::ICMP_UGE, X, LoBound);
6334 else if (LoOverflow)
6335 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6336 ICmpInst::ICMP_ULT, X, HiBound);
6337 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006338 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006339 case ICmpInst::ICMP_NE:
6340 if (LoOverflow && HiOverflow)
6341 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6342 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006343 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006344 ICmpInst::ICMP_ULT, X, LoBound);
6345 else if (LoOverflow)
6346 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6347 ICmpInst::ICMP_UGE, X, HiBound);
6348 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006349 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006350 case ICmpInst::ICMP_ULT:
6351 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006352 if (LoOverflow == +1) // Low bound is greater than input range.
6353 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6354 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006355 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006356 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006357 case ICmpInst::ICMP_UGT:
6358 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006359 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006360 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006361 else if (HiOverflow == -1) // High bound less than input range.
6362 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6363 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006364 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6365 else
6366 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6367 }
6368}
6369
6370
Chris Lattner01deb9d2007-04-03 17:43:25 +00006371/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6372///
6373Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6374 Instruction *LHSI,
6375 ConstantInt *RHS) {
6376 const APInt &RHSV = RHS->getValue();
6377
6378 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006379 case Instruction::Trunc:
6380 if (ICI.isEquality() && LHSI->hasOneUse()) {
6381 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6382 // of the high bits truncated out of x are known.
6383 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6384 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6385 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6386 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6387 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6388
6389 // If all the high bits are known, we can do this xform.
6390 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6391 // Pull in the high bits from known-ones set.
6392 APInt NewRHS(RHS->getValue());
6393 NewRHS.zext(SrcBits);
6394 NewRHS |= KnownOne;
6395 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6396 ConstantInt::get(NewRHS));
6397 }
6398 }
6399 break;
6400
Duncan Sands0091bf22007-04-04 06:42:45 +00006401 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006402 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6403 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6404 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006405 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6406 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006407 Value *CompareVal = LHSI->getOperand(0);
6408
6409 // If the sign bit of the XorCST is not set, there is no change to
6410 // the operation, just stop using the Xor.
6411 if (!XorCST->getValue().isNegative()) {
6412 ICI.setOperand(0, CompareVal);
6413 AddToWorkList(LHSI);
6414 return &ICI;
6415 }
6416
6417 // Was the old condition true if the operand is positive?
6418 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6419
6420 // If so, the new one isn't.
6421 isTrueIfPositive ^= true;
6422
6423 if (isTrueIfPositive)
6424 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6425 else
6426 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6427 }
6428 }
6429 break;
6430 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6431 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6432 LHSI->getOperand(0)->hasOneUse()) {
6433 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6434
6435 // If the LHS is an AND of a truncating cast, we can widen the
6436 // and/compare to be the input width without changing the value
6437 // produced, eliminating a cast.
6438 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6439 // We can do this transformation if either the AND constant does not
6440 // have its sign bit set or if it is an equality comparison.
6441 // Extending a relational comparison when we're checking the sign
6442 // bit would not work.
6443 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006444 (ICI.isEquality() ||
6445 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006446 uint32_t BitWidth =
6447 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6448 APInt NewCST = AndCST->getValue();
6449 NewCST.zext(BitWidth);
6450 APInt NewCI = RHSV;
6451 NewCI.zext(BitWidth);
6452 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006453 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006454 ConstantInt::get(NewCST),LHSI->getName());
6455 InsertNewInstBefore(NewAnd, ICI);
6456 return new ICmpInst(ICI.getPredicate(), NewAnd,
6457 ConstantInt::get(NewCI));
6458 }
6459 }
6460
6461 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6462 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6463 // happens a LOT in code produced by the C front-end, for bitfield
6464 // access.
6465 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6466 if (Shift && !Shift->isShift())
6467 Shift = 0;
6468
6469 ConstantInt *ShAmt;
6470 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6471 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6472 const Type *AndTy = AndCST->getType(); // Type of the and.
6473
6474 // We can fold this as long as we can't shift unknown bits
6475 // into the mask. This can only happen with signed shift
6476 // rights, as they sign-extend.
6477 if (ShAmt) {
6478 bool CanFold = Shift->isLogicalShift();
6479 if (!CanFold) {
6480 // To test for the bad case of the signed shr, see if any
6481 // of the bits shifted in could be tested after the mask.
6482 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6483 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6484
6485 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6486 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6487 AndCST->getValue()) == 0)
6488 CanFold = true;
6489 }
6490
6491 if (CanFold) {
6492 Constant *NewCst;
6493 if (Shift->getOpcode() == Instruction::Shl)
6494 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6495 else
6496 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6497
6498 // Check to see if we are shifting out any of the bits being
6499 // compared.
6500 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6501 // If we shifted bits out, the fold is not going to work out.
6502 // As a special case, check to see if this means that the
6503 // result is always true or false now.
6504 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6505 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6506 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6507 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6508 } else {
6509 ICI.setOperand(1, NewCst);
6510 Constant *NewAndCST;
6511 if (Shift->getOpcode() == Instruction::Shl)
6512 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6513 else
6514 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6515 LHSI->setOperand(1, NewAndCST);
6516 LHSI->setOperand(0, Shift->getOperand(0));
6517 AddToWorkList(Shift); // Shift is dead.
6518 AddUsesToWorkList(ICI);
6519 return &ICI;
6520 }
6521 }
6522 }
6523
6524 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6525 // preferable because it allows the C<<Y expression to be hoisted out
6526 // of a loop if Y is invariant and X is not.
6527 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6528 ICI.isEquality() && !Shift->isArithmeticShift() &&
6529 isa<Instruction>(Shift->getOperand(0))) {
6530 // Compute C << Y.
6531 Value *NS;
6532 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006533 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006534 Shift->getOperand(1), "tmp");
6535 } else {
6536 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006537 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006538 Shift->getOperand(1), "tmp");
6539 }
6540 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6541
6542 // Compute X & (C << Y).
6543 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006544 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006545 InsertNewInstBefore(NewAnd, ICI);
6546
6547 ICI.setOperand(0, NewAnd);
6548 return &ICI;
6549 }
6550 }
6551 break;
6552
Chris Lattnera0141b92007-07-15 20:42:37 +00006553 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6554 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6555 if (!ShAmt) break;
6556
6557 uint32_t TypeBits = RHSV.getBitWidth();
6558
6559 // Check that the shift amount is in range. If not, don't perform
6560 // undefined shifts. When the shift is visited it will be
6561 // simplified.
6562 if (ShAmt->uge(TypeBits))
6563 break;
6564
6565 if (ICI.isEquality()) {
6566 // If we are comparing against bits always shifted out, the
6567 // comparison cannot succeed.
6568 Constant *Comp =
6569 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6570 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6571 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6572 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6573 return ReplaceInstUsesWith(ICI, Cst);
6574 }
6575
6576 if (LHSI->hasOneUse()) {
6577 // Otherwise strength reduce the shift into an and.
6578 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6579 Constant *Mask =
6580 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006581
Chris Lattnera0141b92007-07-15 20:42:37 +00006582 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006583 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006584 Mask, LHSI->getName()+".mask");
6585 Value *And = InsertNewInstBefore(AndI, ICI);
6586 return new ICmpInst(ICI.getPredicate(), And,
6587 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006588 }
6589 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006590
6591 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6592 bool TrueIfSigned = false;
6593 if (LHSI->hasOneUse() &&
6594 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6595 // (X << 31) <s 0 --> (X&1) != 0
6596 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6597 (TypeBits-ShAmt->getZExtValue()-1));
6598 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006599 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006600 Mask, LHSI->getName()+".mask");
6601 Value *And = InsertNewInstBefore(AndI, ICI);
6602
6603 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6604 And, Constant::getNullValue(And->getType()));
6605 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006606 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006607 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006608
6609 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006610 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006611 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006612 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006613 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006614
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006615 // Check that the shift amount is in range. If not, don't perform
6616 // undefined shifts. When the shift is visited it will be
6617 // simplified.
6618 uint32_t TypeBits = RHSV.getBitWidth();
6619 if (ShAmt->uge(TypeBits))
6620 break;
6621
6622 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006623
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006624 // If we are comparing against bits always shifted out, the
6625 // comparison cannot succeed.
6626 APInt Comp = RHSV << ShAmtVal;
6627 if (LHSI->getOpcode() == Instruction::LShr)
6628 Comp = Comp.lshr(ShAmtVal);
6629 else
6630 Comp = Comp.ashr(ShAmtVal);
6631
6632 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6633 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6634 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6635 return ReplaceInstUsesWith(ICI, Cst);
6636 }
6637
6638 // Otherwise, check to see if the bits shifted out are known to be zero.
6639 // If so, we can compare against the unshifted value:
6640 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006641 if (LHSI->hasOneUse() &&
6642 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006643 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6644 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6645 ConstantExpr::getShl(RHS, ShAmt));
6646 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006647
Evan Chengf30752c2008-04-23 00:38:06 +00006648 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006649 // Otherwise strength reduce the shift into an and.
6650 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6651 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006652
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006653 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006654 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006655 Mask, LHSI->getName()+".mask");
6656 Value *And = InsertNewInstBefore(AndI, ICI);
6657 return new ICmpInst(ICI.getPredicate(), And,
6658 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006659 }
6660 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006661 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006662
6663 case Instruction::SDiv:
6664 case Instruction::UDiv:
6665 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6666 // Fold this div into the comparison, producing a range check.
6667 // Determine, based on the divide type, what the range is being
6668 // checked. If there is an overflow on the low or high side, remember
6669 // it, otherwise compute the range [low, hi) bounding the new value.
6670 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006671 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6672 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6673 DivRHS))
6674 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006675 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006676
6677 case Instruction::Add:
6678 // Fold: icmp pred (add, X, C1), C2
6679
6680 if (!ICI.isEquality()) {
6681 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6682 if (!LHSC) break;
6683 const APInt &LHSV = LHSC->getValue();
6684
6685 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6686 .subtract(LHSV);
6687
6688 if (ICI.isSignedPredicate()) {
6689 if (CR.getLower().isSignBit()) {
6690 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6691 ConstantInt::get(CR.getUpper()));
6692 } else if (CR.getUpper().isSignBit()) {
6693 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6694 ConstantInt::get(CR.getLower()));
6695 }
6696 } else {
6697 if (CR.getLower().isMinValue()) {
6698 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6699 ConstantInt::get(CR.getUpper()));
6700 } else if (CR.getUpper().isMinValue()) {
6701 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6702 ConstantInt::get(CR.getLower()));
6703 }
6704 }
6705 }
6706 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006707 }
6708
6709 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6710 if (ICI.isEquality()) {
6711 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6712
6713 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6714 // the second operand is a constant, simplify a bit.
6715 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6716 switch (BO->getOpcode()) {
6717 case Instruction::SRem:
6718 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6719 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6720 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6721 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6722 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006723 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006724 BO->getName());
6725 InsertNewInstBefore(NewRem, ICI);
6726 return new ICmpInst(ICI.getPredicate(), NewRem,
6727 Constant::getNullValue(BO->getType()));
6728 }
6729 }
6730 break;
6731 case Instruction::Add:
6732 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6733 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6734 if (BO->hasOneUse())
6735 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6736 Subtract(RHS, BOp1C));
6737 } else if (RHSV == 0) {
6738 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6739 // efficiently invertible, or if the add has just this one use.
6740 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6741
6742 if (Value *NegVal = dyn_castNegVal(BOp1))
6743 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6744 else if (Value *NegVal = dyn_castNegVal(BOp0))
6745 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6746 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006747 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006748 InsertNewInstBefore(Neg, ICI);
6749 Neg->takeName(BO);
6750 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6751 }
6752 }
6753 break;
6754 case Instruction::Xor:
6755 // For the xor case, we can xor two constants together, eliminating
6756 // the explicit xor.
6757 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6758 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6759 ConstantExpr::getXor(RHS, BOC));
6760
6761 // FALLTHROUGH
6762 case Instruction::Sub:
6763 // Replace (([sub|xor] A, B) != 0) with (A != B)
6764 if (RHSV == 0)
6765 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6766 BO->getOperand(1));
6767 break;
6768
6769 case Instruction::Or:
6770 // If bits are being or'd in that are not present in the constant we
6771 // are comparing against, then the comparison could never succeed!
6772 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6773 Constant *NotCI = ConstantExpr::getNot(RHS);
6774 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6775 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6776 isICMP_NE));
6777 }
6778 break;
6779
6780 case Instruction::And:
6781 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6782 // If bits are being compared against that are and'd out, then the
6783 // comparison can never succeed!
6784 if ((RHSV & ~BOC->getValue()) != 0)
6785 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6786 isICMP_NE));
6787
6788 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6789 if (RHS == BOC && RHSV.isPowerOf2())
6790 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6791 ICmpInst::ICMP_NE, LHSI,
6792 Constant::getNullValue(RHS->getType()));
6793
6794 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006795 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006796 Value *X = BO->getOperand(0);
6797 Constant *Zero = Constant::getNullValue(X->getType());
6798 ICmpInst::Predicate pred = isICMP_NE ?
6799 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6800 return new ICmpInst(pred, X, Zero);
6801 }
6802
6803 // ((X & ~7) == 0) --> X < 8
6804 if (RHSV == 0 && isHighOnes(BOC)) {
6805 Value *X = BO->getOperand(0);
6806 Constant *NegX = ConstantExpr::getNeg(BOC);
6807 ICmpInst::Predicate pred = isICMP_NE ?
6808 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6809 return new ICmpInst(pred, X, NegX);
6810 }
6811 }
6812 default: break;
6813 }
6814 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6815 // Handle icmp {eq|ne} <intrinsic>, intcst.
6816 if (II->getIntrinsicID() == Intrinsic::bswap) {
6817 AddToWorkList(II);
6818 ICI.setOperand(0, II->getOperand(1));
6819 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6820 return &ICI;
6821 }
6822 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006823 }
6824 return 0;
6825}
6826
6827/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6828/// We only handle extending casts so far.
6829///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006830Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6831 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006832 Value *LHSCIOp = LHSCI->getOperand(0);
6833 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006834 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006835 Value *RHSCIOp;
6836
Chris Lattner8c756c12007-05-05 22:41:33 +00006837 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6838 // integer type is the same size as the pointer type.
6839 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6840 getTargetData().getPointerSizeInBits() ==
6841 cast<IntegerType>(DestTy)->getBitWidth()) {
6842 Value *RHSOp = 0;
6843 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006844 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006845 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6846 RHSOp = RHSC->getOperand(0);
6847 // If the pointer types don't match, insert a bitcast.
6848 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006849 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006850 }
6851
6852 if (RHSOp)
6853 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6854 }
6855
6856 // The code below only handles extension cast instructions, so far.
6857 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006858 if (LHSCI->getOpcode() != Instruction::ZExt &&
6859 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006860 return 0;
6861
Reid Spencere4d87aa2006-12-23 06:05:41 +00006862 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6863 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006864
Reid Spencere4d87aa2006-12-23 06:05:41 +00006865 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006866 // Not an extension from the same type?
6867 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006868 if (RHSCIOp->getType() != LHSCIOp->getType())
6869 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006870
Nick Lewycky4189a532008-01-28 03:48:02 +00006871 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006872 // and the other is a zext), then we can't handle this.
6873 if (CI->getOpcode() != LHSCI->getOpcode())
6874 return 0;
6875
Nick Lewycky4189a532008-01-28 03:48:02 +00006876 // Deal with equality cases early.
6877 if (ICI.isEquality())
6878 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6879
6880 // A signed comparison of sign extended values simplifies into a
6881 // signed comparison.
6882 if (isSignedCmp && isSignedExt)
6883 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6884
6885 // The other three cases all fold into an unsigned comparison.
6886 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006887 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006888
Reid Spencere4d87aa2006-12-23 06:05:41 +00006889 // If we aren't dealing with a constant on the RHS, exit early
6890 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6891 if (!CI)
6892 return 0;
6893
6894 // Compute the constant that would happen if we truncated to SrcTy then
6895 // reextended to DestTy.
6896 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6897 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6898
6899 // If the re-extended constant didn't change...
6900 if (Res2 == CI) {
6901 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6902 // For example, we might have:
6903 // %A = sext short %X to uint
6904 // %B = icmp ugt uint %A, 1330
6905 // It is incorrect to transform this into
6906 // %B = icmp ugt short %X, 1330
6907 // because %A may have negative value.
6908 //
Chris Lattnerf2991842008-07-11 04:09:09 +00006909 // However, we allow this when the compare is EQ/NE, because they are
6910 // signless.
6911 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006912 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00006913 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006914 }
6915
6916 // The re-extended constant changed so the constant cannot be represented
6917 // in the shorter type. Consequently, we cannot emit a simple comparison.
6918
6919 // First, handle some easy cases. We know the result cannot be equal at this
6920 // point so handle the ICI.isEquality() cases
6921 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006922 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006923 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006924 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006925
6926 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6927 // should have been folded away previously and not enter in here.
6928 Value *Result;
6929 if (isSignedCmp) {
6930 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006931 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006932 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006933 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006934 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006935 } else {
6936 // We're performing an unsigned comparison.
6937 if (isSignedExt) {
6938 // We're performing an unsigned comp with a sign extended value.
6939 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006940 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006941 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6942 NegOne, ICI.getName()), ICI);
6943 } else {
6944 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006945 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006946 }
6947 }
6948
6949 // Finally, return the value computed.
6950 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00006951 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006952 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00006953
6954 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6955 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6956 "ICmp should be folded!");
6957 if (Constant *CI = dyn_cast<Constant>(Result))
6958 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6959 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00006960}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006961
Reid Spencer832254e2007-02-02 02:16:23 +00006962Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6963 return commonShiftTransforms(I);
6964}
6965
6966Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6967 return commonShiftTransforms(I);
6968}
6969
6970Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006971 if (Instruction *R = commonShiftTransforms(I))
6972 return R;
6973
6974 Value *Op0 = I.getOperand(0);
6975
6976 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6977 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6978 if (CSI->isAllOnesValue())
6979 return ReplaceInstUsesWith(I, CSI);
6980
6981 // See if we can turn a signed shr into an unsigned shr.
Nate Begeman5bc1ea02008-07-29 15:49:41 +00006982 if (!isa<VectorType>(I.getType()) &&
6983 MaskedValueIsZero(Op0,
Chris Lattner348f6652007-12-06 01:59:46 +00006984 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006985 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006986
6987 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006988}
6989
6990Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6991 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006992 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006993
6994 // shl X, 0 == X and shr X, 0 == X
6995 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006996 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006997 Op0 == Constant::getNullValue(Op0->getType()))
6998 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006999
Reid Spencere4d87aa2006-12-23 06:05:41 +00007000 if (isa<UndefValue>(Op0)) {
7001 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007002 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007003 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007004 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7005 }
7006 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007007 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7008 return ReplaceInstUsesWith(I, Op0);
7009 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007010 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007011 }
7012
Chris Lattner2eefe512004-04-09 19:05:30 +00007013 // Try to fold constant and into select arguments.
7014 if (isa<Constant>(Op0))
7015 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007016 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007017 return R;
7018
Reid Spencerb83eb642006-10-20 07:07:24 +00007019 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007020 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7021 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007022 return 0;
7023}
7024
Reid Spencerb83eb642006-10-20 07:07:24 +00007025Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007026 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007027 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007028
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007029 // See if we can simplify any instructions used by the instruction whose sole
7030 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00007031 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +00007032 if (SimplifyDemandedInstructionBits(I))
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007033 return &I;
7034
Chris Lattner4d5542c2006-01-06 07:12:35 +00007035 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7036 // of a signed value.
7037 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007038 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007039 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007040 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7041 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007042 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007043 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007044 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007045 }
7046
7047 // ((X*C1) << C2) == (X * (C1 << C2))
7048 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7049 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7050 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007051 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007052 ConstantExpr::getShl(BOOp, Op1));
7053
7054 // Try to fold constant and into select arguments.
7055 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7056 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7057 return R;
7058 if (isa<PHINode>(Op0))
7059 if (Instruction *NV = FoldOpIntoPhi(I))
7060 return NV;
7061
Chris Lattner8999dd32007-12-22 09:07:47 +00007062 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7063 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7064 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7065 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7066 // place. Don't try to do this transformation in this case. Also, we
7067 // require that the input operand is a shift-by-constant so that we have
7068 // confidence that the shifts will get folded together. We could do this
7069 // xform in more cases, but it is unlikely to be profitable.
7070 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7071 isa<ConstantInt>(TrOp->getOperand(1))) {
7072 // Okay, we'll do this xform. Make the shift of shift.
7073 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007074 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007075 I.getName());
7076 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7077
7078 // For logical shifts, the truncation has the effect of making the high
7079 // part of the register be zeros. Emulate this by inserting an AND to
7080 // clear the top bits as needed. This 'and' will usually be zapped by
7081 // other xforms later if dead.
7082 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7083 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7084 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7085
7086 // The mask we constructed says what the trunc would do if occurring
7087 // between the shifts. We want to know the effect *after* the second
7088 // shift. We know that it is a logical shift by a constant, so adjust the
7089 // mask as appropriate.
7090 if (I.getOpcode() == Instruction::Shl)
7091 MaskV <<= Op1->getZExtValue();
7092 else {
7093 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7094 MaskV = MaskV.lshr(Op1->getZExtValue());
7095 }
7096
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007097 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007098 TI->getName());
7099 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7100
7101 // Return the value truncated to the interesting size.
7102 return new TruncInst(And, I.getType());
7103 }
7104 }
7105
Chris Lattner4d5542c2006-01-06 07:12:35 +00007106 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007107 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7108 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7109 Value *V1, *V2;
7110 ConstantInt *CC;
7111 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007112 default: break;
7113 case Instruction::Add:
7114 case Instruction::And:
7115 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007116 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007117 // These operators commute.
7118 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007119 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007120 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007121 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007122 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007123 Op0BO->getName());
7124 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007125 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007126 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007127 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007128 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007129 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007130 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007131 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007132 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007133
Chris Lattner150f12a2005-09-18 06:30:59 +00007134 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007135 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007136 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007137 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007138 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7139 m_ConstantInt(CC))) &&
7140 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007141 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007142 Op0BO->getOperand(0), Op1,
7143 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007144 InsertNewInstBefore(YS, I); // (Y << C)
7145 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007146 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007147 V1->getName()+".mask");
7148 InsertNewInstBefore(XM, I); // X & (CC << C)
7149
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007150 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007151 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007152 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007153
Reid Spencera07cb7d2007-02-02 14:41:37 +00007154 // FALL THROUGH.
7155 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007156 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007157 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007158 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007159 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007160 Op0BO->getOperand(1), Op1,
7161 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007162 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007163 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007164 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007165 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007166 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007167 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007168 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007169 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007170 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007171
Chris Lattner13d4ab42006-05-31 21:14:00 +00007172 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007173 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7174 match(Op0BO->getOperand(0),
7175 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007176 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007177 cast<BinaryOperator>(Op0BO->getOperand(0))
7178 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007179 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007180 Op0BO->getOperand(1), Op1,
7181 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007182 InsertNewInstBefore(YS, I); // (Y << C)
7183 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007184 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007185 V1->getName()+".mask");
7186 InsertNewInstBefore(XM, I); // X & (CC << C)
7187
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007188 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007189 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007190
Chris Lattner11021cb2005-09-18 05:12:10 +00007191 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007192 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007193 }
7194
7195
7196 // If the operand is an bitwise operator with a constant RHS, and the
7197 // shift is the only use, we can pull it out of the shift.
7198 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7199 bool isValid = true; // Valid only for And, Or, Xor
7200 bool highBitSet = false; // Transform if high bit of constant set?
7201
7202 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007203 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007204 case Instruction::Add:
7205 isValid = isLeftShift;
7206 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007207 case Instruction::Or:
7208 case Instruction::Xor:
7209 highBitSet = false;
7210 break;
7211 case Instruction::And:
7212 highBitSet = true;
7213 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007214 }
7215
7216 // If this is a signed shift right, and the high bit is modified
7217 // by the logical operation, do not perform the transformation.
7218 // The highBitSet boolean indicates the value of the high bit of
7219 // the constant which would cause it to be modified for this
7220 // operation.
7221 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007222 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007223 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007224
7225 if (isValid) {
7226 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7227
7228 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007229 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007230 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007231 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007232
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007233 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007234 NewRHS);
7235 }
7236 }
7237 }
7238 }
7239
Chris Lattnerad0124c2006-01-06 07:52:12 +00007240 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007241 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7242 if (ShiftOp && !ShiftOp->isShift())
7243 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007244
Reid Spencerb83eb642006-10-20 07:07:24 +00007245 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007246 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007247 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7248 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007249 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7250 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7251 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007252
Zhou Sheng4351c642007-04-02 08:20:41 +00007253 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007254 if (AmtSum > TypeBits)
7255 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007256
7257 const IntegerType *Ty = cast<IntegerType>(I.getType());
7258
7259 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007260 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007261 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007262 ConstantInt::get(Ty, AmtSum));
7263 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7264 I.getOpcode() == Instruction::AShr) {
7265 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007266 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007267 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7268 I.getOpcode() == Instruction::LShr) {
7269 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7270 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007271 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007272 InsertNewInstBefore(Shift, I);
7273
Zhou Shenge9e03f62007-03-28 15:02:20 +00007274 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007275 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007276 }
7277
Chris Lattnerb87056f2007-02-05 00:57:54 +00007278 // Okay, if we get here, one shift must be left, and the other shift must be
7279 // right. See if the amounts are equal.
7280 if (ShiftAmt1 == ShiftAmt2) {
7281 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7282 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007283 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007284 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007285 }
7286 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7287 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007288 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007289 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007290 }
7291 // We can simplify ((X << C) >>s C) into a trunc + sext.
7292 // NOTE: we could do this for any C, but that would make 'unusual' integer
7293 // types. For now, just stick to ones well-supported by the code
7294 // generators.
7295 const Type *SExtType = 0;
7296 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007297 case 1 :
7298 case 8 :
7299 case 16 :
7300 case 32 :
7301 case 64 :
7302 case 128:
7303 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7304 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007305 default: break;
7306 }
7307 if (SExtType) {
7308 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7309 InsertNewInstBefore(NewTrunc, I);
7310 return new SExtInst(NewTrunc, Ty);
7311 }
7312 // Otherwise, we can't handle it yet.
7313 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007314 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007315
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007316 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007317 if (I.getOpcode() == Instruction::Shl) {
7318 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7319 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007320 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007321 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007322 InsertNewInstBefore(Shift, I);
7323
Reid Spencer55702aa2007-03-25 21:11:44 +00007324 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007325 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007326 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007327
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007328 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007329 if (I.getOpcode() == Instruction::LShr) {
7330 assert(ShiftOp->getOpcode() == Instruction::Shl);
7331 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007332 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007333 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007334
Reid Spencerd5e30f02007-03-26 17:18:58 +00007335 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007336 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007337 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007338
7339 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7340 } else {
7341 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007342 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007343
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007344 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007345 if (I.getOpcode() == Instruction::Shl) {
7346 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7347 ShiftOp->getOpcode() == Instruction::AShr);
7348 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007349 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007350 ConstantInt::get(Ty, ShiftDiff));
7351 InsertNewInstBefore(Shift, I);
7352
Reid Spencer55702aa2007-03-25 21:11:44 +00007353 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007354 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007355 }
7356
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007357 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007358 if (I.getOpcode() == Instruction::LShr) {
7359 assert(ShiftOp->getOpcode() == Instruction::Shl);
7360 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007361 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007362 InsertNewInstBefore(Shift, I);
7363
Reid Spencer68d27cf2007-03-26 23:45:51 +00007364 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007365 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007366 }
7367
7368 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007369 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007370 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007371 return 0;
7372}
7373
Chris Lattnera1be5662002-05-02 17:06:02 +00007374
Chris Lattnercfd65102005-10-29 04:36:15 +00007375/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7376/// expression. If so, decompose it, returning some value X, such that Val is
7377/// X*Scale+Offset.
7378///
7379static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007380 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007381 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007382 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007383 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007384 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007385 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007386 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7387 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7388 if (I->getOpcode() == Instruction::Shl) {
7389 // This is a value scaled by '1 << the shift amt'.
7390 Scale = 1U << RHS->getZExtValue();
7391 Offset = 0;
7392 return I->getOperand(0);
7393 } else if (I->getOpcode() == Instruction::Mul) {
7394 // This value is scaled by 'RHS'.
7395 Scale = RHS->getZExtValue();
7396 Offset = 0;
7397 return I->getOperand(0);
7398 } else if (I->getOpcode() == Instruction::Add) {
7399 // We have X+C. Check to see if we really have (X*C2)+C1,
7400 // where C1 is divisible by C2.
7401 unsigned SubScale;
7402 Value *SubVal =
7403 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7404 Offset += RHS->getZExtValue();
7405 Scale = SubScale;
7406 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007407 }
7408 }
7409 }
7410
7411 // Otherwise, we can't look past this.
7412 Scale = 1;
7413 Offset = 0;
7414 return Val;
7415}
7416
7417
Chris Lattnerb3f83972005-10-24 06:03:58 +00007418/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7419/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007420Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007421 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007422 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007423
Chris Lattnerb53c2382005-10-24 06:22:12 +00007424 // Remove any uses of AI that are dead.
7425 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007426
Chris Lattnerb53c2382005-10-24 06:22:12 +00007427 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7428 Instruction *User = cast<Instruction>(*UI++);
7429 if (isInstructionTriviallyDead(User)) {
7430 while (UI != E && *UI == User)
7431 ++UI; // If this instruction uses AI more than once, don't break UI.
7432
Chris Lattnerb53c2382005-10-24 06:22:12 +00007433 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007434 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007435 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007436 }
7437 }
7438
Chris Lattnerb3f83972005-10-24 06:03:58 +00007439 // Get the type really allocated and the type casted to.
7440 const Type *AllocElTy = AI.getAllocatedType();
7441 const Type *CastElTy = PTy->getElementType();
7442 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007443
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007444 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7445 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007446 if (CastElTyAlign < AllocElTyAlign) return 0;
7447
Chris Lattner39387a52005-10-24 06:35:18 +00007448 // If the allocation has multiple uses, only promote it if we are strictly
7449 // increasing the alignment of the resultant allocation. If we keep it the
7450 // same, we open the door to infinite loops of various kinds.
7451 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7452
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007453 uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7454 uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007455 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007456
Chris Lattner455fcc82005-10-29 03:19:53 +00007457 // See if we can satisfy the modulus by pulling a scale out of the array
7458 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007459 unsigned ArraySizeScale;
7460 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007461 Value *NumElements = // See if the array size is a decomposable linear expr.
7462 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7463
Chris Lattner455fcc82005-10-29 03:19:53 +00007464 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7465 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007466 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7467 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007468
Chris Lattner455fcc82005-10-29 03:19:53 +00007469 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7470 Value *Amt = 0;
7471 if (Scale == 1) {
7472 Amt = NumElements;
7473 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007474 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007475 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7476 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007477 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007478 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007479 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007480 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007481 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007482 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007483 }
7484
Jeff Cohen86796be2007-04-04 16:58:57 +00007485 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7486 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007487 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007488 Amt = InsertNewInstBefore(Tmp, AI);
7489 }
7490
Chris Lattnerb3f83972005-10-24 06:03:58 +00007491 AllocationInst *New;
7492 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007493 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007494 else
Chris Lattner6934a042007-02-11 01:23:03 +00007495 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007496 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007497 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007498
7499 // If the allocation has multiple uses, insert a cast and change all things
7500 // that used it to use the new cast. This will also hack on CI, but it will
7501 // die soon.
7502 if (!AI.hasOneUse()) {
7503 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007504 // New is the allocation instruction, pointer typed. AI is the original
7505 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7506 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007507 InsertNewInstBefore(NewCast, AI);
7508 AI.replaceAllUsesWith(NewCast);
7509 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007510 return ReplaceInstUsesWith(CI, New);
7511}
7512
Chris Lattner70074e02006-05-13 02:06:03 +00007513/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007514/// and return it as type Ty without inserting any new casts and without
7515/// changing the computed value. This is used by code that tries to decide
7516/// whether promoting or shrinking integer operations to wider or smaller types
7517/// will allow us to eliminate a truncate or extend.
7518///
7519/// This is a truncation operation if Ty is smaller than V->getType(), or an
7520/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007521///
7522/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7523/// should return true if trunc(V) can be computed by computing V in the smaller
7524/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7525/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7526/// efficiently truncated.
7527///
7528/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7529/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7530/// the final result.
Evan Cheng4e56ab22009-01-16 02:11:43 +00007531bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7532 unsigned CastOpc,
7533 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007534 // We can always evaluate constants in another type.
7535 if (isa<ConstantInt>(V))
7536 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007537
7538 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007539 if (!I) return false;
7540
7541 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007542
Chris Lattner951626b2007-08-02 06:11:14 +00007543 // If this is an extension or truncate, we can often eliminate it.
7544 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7545 // If this is a cast from the destination type, we can trivially eliminate
7546 // it, and this will remove a cast overall.
7547 if (I->getOperand(0)->getType() == Ty) {
7548 // If the first operand is itself a cast, and is eliminable, do not count
7549 // this as an eliminable cast. We would prefer to eliminate those two
7550 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007551 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007552 ++NumCastsRemoved;
7553 return true;
7554 }
7555 }
7556
7557 // We can't extend or shrink something that has multiple uses: doing so would
7558 // require duplicating the instruction in general, which isn't profitable.
7559 if (!I->hasOneUse()) return false;
7560
Evan Chengf35fd542009-01-15 17:01:23 +00007561 unsigned Opc = I->getOpcode();
7562 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007563 case Instruction::Add:
7564 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007565 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007566 case Instruction::And:
7567 case Instruction::Or:
7568 case Instruction::Xor:
7569 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007570 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007571 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007572 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007573 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007574
Chris Lattner46b96052006-11-29 07:18:39 +00007575 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007576 // If we are truncating the result of this SHL, and if it's a shift of a
7577 // constant amount, we can always perform a SHL in a smaller type.
7578 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007579 uint32_t BitWidth = Ty->getBitWidth();
7580 if (BitWidth < OrigTy->getBitWidth() &&
7581 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007582 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007583 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007584 }
7585 break;
7586 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007587 // If this is a truncate of a logical shr, we can truncate it to a smaller
7588 // lshr iff we know that the bits we would otherwise be shifting in are
7589 // already zeros.
7590 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007591 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7592 uint32_t BitWidth = Ty->getBitWidth();
7593 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007594 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007595 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7596 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007597 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007598 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007599 }
7600 }
Chris Lattner46b96052006-11-29 07:18:39 +00007601 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007602 case Instruction::ZExt:
7603 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007604 case Instruction::Trunc:
7605 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007606 // can safely replace it. Note that replacing it does not reduce the number
7607 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007608 if (Opc == CastOpc)
7609 return true;
7610
7611 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007612 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007613 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007614 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007615 case Instruction::Select: {
7616 SelectInst *SI = cast<SelectInst>(I);
7617 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007618 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007619 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007620 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007621 }
Chris Lattner8114b712008-06-18 04:00:49 +00007622 case Instruction::PHI: {
7623 // We can change a phi if we can change all operands.
7624 PHINode *PN = cast<PHINode>(I);
7625 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7626 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007627 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007628 return false;
7629 return true;
7630 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007631 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007632 // TODO: Can handle more cases here.
7633 break;
7634 }
7635
7636 return false;
7637}
7638
7639/// EvaluateInDifferentType - Given an expression that
7640/// CanEvaluateInDifferentType returns true for, actually insert the code to
7641/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007642Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007643 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007644 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007645 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007646
7647 // Otherwise, it must be an instruction.
7648 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007649 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007650 unsigned Opc = I->getOpcode();
7651 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007652 case Instruction::Add:
7653 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007654 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007655 case Instruction::And:
7656 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007657 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007658 case Instruction::AShr:
7659 case Instruction::LShr:
7660 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007661 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007662 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007663 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007664 break;
7665 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007666 case Instruction::Trunc:
7667 case Instruction::ZExt:
7668 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007669 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007670 // just return the source. There's no need to insert it because it is not
7671 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007672 if (I->getOperand(0)->getType() == Ty)
7673 return I->getOperand(0);
7674
Chris Lattner8114b712008-06-18 04:00:49 +00007675 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007676 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007677 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007678 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007679 case Instruction::Select: {
7680 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7681 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7682 Res = SelectInst::Create(I->getOperand(0), True, False);
7683 break;
7684 }
Chris Lattner8114b712008-06-18 04:00:49 +00007685 case Instruction::PHI: {
7686 PHINode *OPN = cast<PHINode>(I);
7687 PHINode *NPN = PHINode::Create(Ty);
7688 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7689 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7690 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7691 }
7692 Res = NPN;
7693 break;
7694 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007695 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007696 // TODO: Can handle more cases here.
7697 assert(0 && "Unreachable!");
7698 break;
7699 }
7700
Chris Lattner8114b712008-06-18 04:00:49 +00007701 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007702 return InsertNewInstBefore(Res, *I);
7703}
7704
Reid Spencer3da59db2006-11-27 01:05:10 +00007705/// @brief Implement the transforms common to all CastInst visitors.
7706Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007707 Value *Src = CI.getOperand(0);
7708
Dan Gohman23d9d272007-05-11 21:10:54 +00007709 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007710 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007711 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007712 if (Instruction::CastOps opc =
7713 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7714 // The first cast (CSrc) is eliminable so we need to fix up or replace
7715 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007716 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007717 }
7718 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007719
Reid Spencer3da59db2006-11-27 01:05:10 +00007720 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007721 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7722 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7723 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007724
7725 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007726 if (isa<PHINode>(Src))
7727 if (Instruction *NV = FoldOpIntoPhi(CI))
7728 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007729
Reid Spencer3da59db2006-11-27 01:05:10 +00007730 return 0;
7731}
7732
Chris Lattner46cd5a12009-01-09 05:44:56 +00007733/// FindElementAtOffset - Given a type and a constant offset, determine whether
7734/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00007735/// the specified offset. If so, fill them into NewIndices and return the
7736/// resultant element type, otherwise return null.
7737static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7738 SmallVectorImpl<Value*> &NewIndices,
7739 const TargetData *TD) {
7740 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007741
7742 // Start with the index over the outer type. Note that the type size
7743 // might be zero (even if the offset isn't zero) if the indexed type
7744 // is something like [0 x {int, int}]
7745 const Type *IntPtrTy = TD->getIntPtrType();
7746 int64_t FirstIdx = 0;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007747 if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00007748 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00007749 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007750
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007751 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00007752 if (Offset < 0) {
7753 --FirstIdx;
7754 Offset += TySize;
7755 assert(Offset >= 0);
7756 }
7757 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7758 }
7759
7760 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7761
7762 // Index into the types. If we fail, set OrigBase to null.
7763 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007764 // Indexing into tail padding between struct/array elements.
7765 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00007766 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007767
Chris Lattner46cd5a12009-01-09 05:44:56 +00007768 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7769 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007770 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7771 "Offset must stay within the indexed type");
7772
Chris Lattner46cd5a12009-01-09 05:44:56 +00007773 unsigned Elt = SL->getElementContainingOffset(Offset);
7774 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7775
7776 Offset -= SL->getElementOffset(Elt);
7777 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00007778 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007779 uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007780 assert(EltSize && "Cannot index into a zero-sized array");
7781 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7782 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00007783 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007784 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007785 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00007786 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007787 }
7788 }
7789
Chris Lattner3914f722009-01-24 01:00:13 +00007790 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007791}
7792
Chris Lattnerd3e28342007-04-27 17:44:50 +00007793/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7794Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7795 Value *Src = CI.getOperand(0);
7796
Chris Lattnerd3e28342007-04-27 17:44:50 +00007797 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007798 // If casting the result of a getelementptr instruction with no offset, turn
7799 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007800 if (GEP->hasAllZeroIndices()) {
7801 // Changing the cast operand is usually not a good idea but it is safe
7802 // here because the pointer operand is being replaced with another
7803 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007804 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007805 CI.setOperand(0, GEP->getOperand(0));
7806 return &CI;
7807 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007808
7809 // If the GEP has a single use, and the base pointer is a bitcast, and the
7810 // GEP computes a constant offset, see if we can convert these three
7811 // instructions into fewer. This typically happens with unions and other
7812 // non-type-safe code.
7813 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7814 if (GEP->hasAllConstantIndices()) {
7815 // We are guaranteed to get a constant from EmitGEPOffset.
7816 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7817 int64_t Offset = OffsetV->getSExtValue();
7818
7819 // Get the base pointer input of the bitcast, and the type it points to.
7820 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7821 const Type *GEPIdxTy =
7822 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007823 SmallVector<Value*, 8> NewIndices;
7824 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7825 // If we were able to index down into an element, create the GEP
7826 // and bitcast the result. This eliminates one bitcast, potentially
7827 // two.
7828 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7829 NewIndices.begin(),
7830 NewIndices.end(), "");
7831 InsertNewInstBefore(NGEP, CI);
7832 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00007833
Chris Lattner46cd5a12009-01-09 05:44:56 +00007834 if (isa<BitCastInst>(CI))
7835 return new BitCastInst(NGEP, CI.getType());
7836 assert(isa<PtrToIntInst>(CI));
7837 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00007838 }
7839 }
7840 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007841 }
7842
7843 return commonCastTransforms(CI);
7844}
7845
7846
Chris Lattnerc739cd62007-03-03 05:27:34 +00007847/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7848/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007849/// cases.
7850/// @brief Implement the transforms common to CastInst with integer operands
7851Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7852 if (Instruction *Result = commonCastTransforms(CI))
7853 return Result;
7854
7855 Value *Src = CI.getOperand(0);
7856 const Type *SrcTy = Src->getType();
7857 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007858 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7859 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007860
Reid Spencer3da59db2006-11-27 01:05:10 +00007861 // See if we can simplify any instructions used by the LHS whose sole
7862 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00007863 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00007864 return &CI;
7865
7866 // If the source isn't an instruction or has more than one use then we
7867 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007868 Instruction *SrcI = dyn_cast<Instruction>(Src);
7869 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007870 return 0;
7871
Chris Lattnerc739cd62007-03-03 05:27:34 +00007872 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007873 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007874 if (!isa<BitCastInst>(CI) &&
7875 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Evan Cheng4e56ab22009-01-16 02:11:43 +00007876 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007877 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007878 // eliminates the cast, so it is always a win. If this is a zero-extension,
7879 // we need to do an AND to maintain the clear top-part of the computation,
7880 // so we require that the input have eliminated at least one cast. If this
7881 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007882 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00007883 bool DoXForm = false;
7884 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007885 switch (CI.getOpcode()) {
7886 default:
7887 // All the others use floating point so we shouldn't actually
7888 // get here because of the check above.
7889 assert(0 && "Unknown cast type");
7890 case Instruction::Trunc:
7891 DoXForm = true;
7892 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007893 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007894 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00007895 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00007896 // If it's unnecessary to issue an AND to clear the high bits, it's
7897 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00007898 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007899 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7900 if (MaskedValueIsZero(TryRes, Mask))
7901 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00007902
7903 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00007904 if (TryI->use_empty())
7905 EraseInstFromFunction(*TryI);
7906 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007907 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007908 }
Evan Chengf35fd542009-01-15 17:01:23 +00007909 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007910 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00007911 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00007912 // If we do not have to emit the truncate + sext pair, then it's always
7913 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00007914 //
7915 // It's not safe to eliminate the trunc + sext pair if one of the
7916 // eliminated cast is a truncate. e.g.
7917 // t2 = trunc i32 t1 to i16
7918 // t3 = sext i16 t2 to i32
7919 // !=
7920 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00007921 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007922 unsigned NumSignBits = ComputeNumSignBits(TryRes);
7923 if (NumSignBits > (DestBitSize - SrcBitSize))
7924 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00007925
7926 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00007927 if (TryI->use_empty())
7928 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00007929 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007930 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007931 }
Evan Chengf35fd542009-01-15 17:01:23 +00007932 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007933
7934 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00007935 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
7936 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00007937 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7938 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007939 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00007940 // Just replace this cast with the result.
7941 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007942
Reid Spencer3da59db2006-11-27 01:05:10 +00007943 assert(Res->getType() == DestTy);
7944 switch (CI.getOpcode()) {
7945 default: assert(0 && "Unknown cast type!");
7946 case Instruction::Trunc:
7947 case Instruction::BitCast:
7948 // Just replace this cast with the result.
7949 return ReplaceInstUsesWith(CI, Res);
7950 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00007951 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00007952
7953 // If the high bits are already zero, just replace this cast with the
7954 // result.
7955 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7956 if (MaskedValueIsZero(Res, Mask))
7957 return ReplaceInstUsesWith(CI, Res);
7958
7959 // We need to emit an AND to clear the high bits.
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007960 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7961 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007962 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007963 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00007964 case Instruction::SExt: {
7965 // If the high bits are already filled with sign bit, just replace this
7966 // cast with the result.
7967 unsigned NumSignBits = ComputeNumSignBits(Res);
7968 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00007969 return ReplaceInstUsesWith(CI, Res);
7970
Reid Spencer3da59db2006-11-27 01:05:10 +00007971 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007972 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007973 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7974 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007975 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00007976 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007977 }
7978 }
7979
7980 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7981 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7982
7983 switch (SrcI->getOpcode()) {
7984 case Instruction::Add:
7985 case Instruction::Mul:
7986 case Instruction::And:
7987 case Instruction::Or:
7988 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007989 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007990 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7991 // Don't insert two casts if they cannot be eliminated. We allow
7992 // two casts to be inserted if the sizes are the same. This could
7993 // only be converting signedness, which is a noop.
7994 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007995 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7996 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007997 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00007998 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7999 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008000 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008001 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008002 }
8003 }
8004
8005 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8006 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8007 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008008 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008009 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008010 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008011 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008012 }
8013 break;
8014 case Instruction::SDiv:
8015 case Instruction::UDiv:
8016 case Instruction::SRem:
8017 case Instruction::URem:
8018 // If we are just changing the sign, rewrite.
8019 if (DestBitSize == SrcBitSize) {
8020 // Don't insert two casts if they cannot be eliminated. We allow
8021 // two casts to be inserted if the sizes are the same. This could
8022 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008023 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8024 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008025 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8026 Op0, DestTy, *SrcI);
8027 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8028 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008029 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00008030 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8031 }
8032 }
8033 break;
8034
8035 case Instruction::Shl:
8036 // Allow changing the sign of the source operand. Do not allow
8037 // changing the size of the shift, UNLESS the shift amount is a
8038 // constant. We must not change variable sized shifts to a smaller
8039 // size, because it is undefined to shift more bits out than exist
8040 // in the value.
8041 if (DestBitSize == SrcBitSize ||
8042 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00008043 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8044 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008045 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8046 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008047 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008048 }
8049 break;
8050 case Instruction::AShr:
8051 // If this is a signed shr, and if all bits shifted in are about to be
8052 // truncated off, turn it into an unsigned shr to allow greater
8053 // simplifications.
8054 if (DestBitSize < SrcBitSize &&
8055 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008056 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00008057 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8058 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008059 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008060 }
8061 }
8062 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008063 }
8064 return 0;
8065}
8066
Chris Lattner8a9f5712007-04-11 06:57:46 +00008067Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008068 if (Instruction *Result = commonIntCastTransforms(CI))
8069 return Result;
8070
8071 Value *Src = CI.getOperand(0);
8072 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00008073 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8074 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008075
8076 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8077 switch (SrcI->getOpcode()) {
8078 default: break;
8079 case Instruction::LShr:
8080 // We can shrink lshr to something smaller if we know the bits shifted in
8081 // are already zeros.
8082 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008083 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008084
8085 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00008086 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00008087 Value* SrcIOp0 = SrcI->getOperand(0);
8088 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008089 if (ShAmt >= DestBitWidth) // All zeros.
8090 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8091
8092 // Okay, we can shrink this. Truncate the input, then return a new
8093 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00008094 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8095 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8096 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008097 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008098 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008099 } else { // This is a variable shr.
8100
8101 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
8102 // more LLVM instructions, but allows '1 << Y' to be hoisted if
8103 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00008104 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008105 Value *One = ConstantInt::get(SrcI->getType(), 1);
8106
Reid Spencer832254e2007-02-02 02:16:23 +00008107 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008108 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00008109 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008110 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008111 SrcI->getOperand(0),
8112 "tmp"), CI);
8113 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00008114 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008115 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008116 }
8117 break;
8118 }
8119 }
8120
8121 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008122}
8123
Evan Chengb98a10e2008-03-24 00:21:34 +00008124/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8125/// in order to eliminate the icmp.
8126Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8127 bool DoXform) {
8128 // If we are just checking for a icmp eq of a single bit and zext'ing it
8129 // to an integer, then shift the bit to the appropriate place and then
8130 // cast to integer to avoid the comparison.
8131 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8132 const APInt &Op1CV = Op1C->getValue();
8133
8134 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8135 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8136 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8137 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8138 if (!DoXform) return ICI;
8139
8140 Value *In = ICI->getOperand(0);
8141 Value *Sh = ConstantInt::get(In->getType(),
8142 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008143 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008144 In->getName()+".lobit"),
8145 CI);
8146 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008147 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008148 false/*ZExt*/, "tmp", &CI);
8149
8150 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8151 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008152 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008153 In->getName()+".not"),
8154 CI);
8155 }
8156
8157 return ReplaceInstUsesWith(CI, In);
8158 }
8159
8160
8161
8162 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8163 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8164 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8165 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8166 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8167 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8168 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8169 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8170 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8171 // This only works for EQ and NE
8172 ICI->isEquality()) {
8173 // If Op1C some other power of two, convert:
8174 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8175 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8176 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8177 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8178
8179 APInt KnownZeroMask(~KnownZero);
8180 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8181 if (!DoXform) return ICI;
8182
8183 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8184 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8185 // (X&4) == 2 --> false
8186 // (X&4) != 2 --> true
8187 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8188 Res = ConstantExpr::getZExt(Res, CI.getType());
8189 return ReplaceInstUsesWith(CI, Res);
8190 }
8191
8192 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8193 Value *In = ICI->getOperand(0);
8194 if (ShiftAmt) {
8195 // Perform a logical shr by shiftamt.
8196 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008197 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008198 ConstantInt::get(In->getType(), ShiftAmt),
8199 In->getName()+".lobit"), CI);
8200 }
8201
8202 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8203 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008204 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008205 InsertNewInstBefore(cast<Instruction>(In), CI);
8206 }
8207
8208 if (CI.getType() == In->getType())
8209 return ReplaceInstUsesWith(CI, In);
8210 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008211 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008212 }
8213 }
8214 }
8215
8216 return 0;
8217}
8218
Chris Lattner8a9f5712007-04-11 06:57:46 +00008219Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008220 // If one of the common conversion will work ..
8221 if (Instruction *Result = commonIntCastTransforms(CI))
8222 return Result;
8223
8224 Value *Src = CI.getOperand(0);
8225
8226 // If this is a cast of a cast
8227 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008228 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8229 // types and if the sizes are just right we can convert this into a logical
8230 // 'and' which will be much cheaper than the pair of casts.
8231 if (isa<TruncInst>(CSrc)) {
8232 // Get the sizes of the types involved
8233 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008234 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8235 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8236 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008237 // If we're actually extending zero bits and the trunc is a no-op
8238 if (MidSize < DstSize && SrcSize == DstSize) {
8239 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00008240 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00008241 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00008242 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008243 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00008244 // Unfortunately, if the type changed, we need to cast it back.
8245 if (And->getType() != CI.getType()) {
8246 And->setName(CSrc->getName()+".mask");
8247 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008248 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00008249 }
8250 return And;
8251 }
8252 }
8253 }
8254
Evan Chengb98a10e2008-03-24 00:21:34 +00008255 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8256 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008257
Evan Chengb98a10e2008-03-24 00:21:34 +00008258 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8259 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8260 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8261 // of the (zext icmp) will be transformed.
8262 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8263 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8264 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8265 (transformZExtICmp(LHS, CI, false) ||
8266 transformZExtICmp(RHS, CI, false))) {
8267 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8268 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008269 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008270 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008271 }
8272
Reid Spencer3da59db2006-11-27 01:05:10 +00008273 return 0;
8274}
8275
Chris Lattner8a9f5712007-04-11 06:57:46 +00008276Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008277 if (Instruction *I = commonIntCastTransforms(CI))
8278 return I;
8279
Chris Lattner8a9f5712007-04-11 06:57:46 +00008280 Value *Src = CI.getOperand(0);
8281
Dan Gohman1975d032008-10-30 20:40:10 +00008282 // Canonicalize sign-extend from i1 to a select.
8283 if (Src->getType() == Type::Int1Ty)
8284 return SelectInst::Create(Src,
8285 ConstantInt::getAllOnesValue(CI.getType()),
8286 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008287
8288 // See if the value being truncated is already sign extended. If so, just
8289 // eliminate the trunc/sext pair.
8290 if (getOpcode(Src) == Instruction::Trunc) {
8291 Value *Op = cast<User>(Src)->getOperand(0);
8292 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8293 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8294 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8295 unsigned NumSignBits = ComputeNumSignBits(Op);
8296
8297 if (OpBits == DestBits) {
8298 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8299 // bits, it is already ready.
8300 if (NumSignBits > DestBits-MidBits)
8301 return ReplaceInstUsesWith(CI, Op);
8302 } else if (OpBits < DestBits) {
8303 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8304 // bits, just sext from i32.
8305 if (NumSignBits > OpBits-MidBits)
8306 return new SExtInst(Op, CI.getType(), "tmp");
8307 } else {
8308 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8309 // bits, just truncate to i32.
8310 if (NumSignBits > OpBits-MidBits)
8311 return new TruncInst(Op, CI.getType(), "tmp");
8312 }
8313 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008314
8315 // If the input is a shl/ashr pair of a same constant, then this is a sign
8316 // extension from a smaller value. If we could trust arbitrary bitwidth
8317 // integers, we could turn this into a truncate to the smaller bit and then
8318 // use a sext for the whole extension. Since we don't, look deeper and check
8319 // for a truncate. If the source and dest are the same type, eliminate the
8320 // trunc and extend and just do shifts. For example, turn:
8321 // %a = trunc i32 %i to i8
8322 // %b = shl i8 %a, 6
8323 // %c = ashr i8 %b, 6
8324 // %d = sext i8 %c to i32
8325 // into:
8326 // %a = shl i32 %i, 30
8327 // %d = ashr i32 %a, 30
8328 Value *A = 0;
8329 ConstantInt *BA = 0, *CA = 0;
8330 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8331 m_ConstantInt(CA))) &&
8332 BA == CA && isa<TruncInst>(A)) {
8333 Value *I = cast<TruncInst>(A)->getOperand(0);
8334 if (I->getType() == CI.getType()) {
8335 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8336 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8337 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8338 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8339 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8340 CI.getName()), CI);
8341 return BinaryOperator::CreateAShr(I, ShAmtV);
8342 }
8343 }
8344
Chris Lattnerba417832007-04-11 06:12:58 +00008345 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008346}
8347
Chris Lattnerb7530652008-01-27 05:29:54 +00008348/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8349/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008350static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008351 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008352 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008353 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8354 if (!losesInfo)
Chris Lattner02a260a2008-04-20 00:41:09 +00008355 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008356 return 0;
8357}
8358
8359/// LookThroughFPExtensions - If this is an fp extension instruction, look
8360/// through it until we get the source value.
8361static Value *LookThroughFPExtensions(Value *V) {
8362 if (Instruction *I = dyn_cast<Instruction>(V))
8363 if (I->getOpcode() == Instruction::FPExt)
8364 return LookThroughFPExtensions(I->getOperand(0));
8365
8366 // If this value is a constant, return the constant in the smallest FP type
8367 // that can accurately represent it. This allows us to turn
8368 // (float)((double)X+2.0) into x+2.0f.
8369 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8370 if (CFP->getType() == Type::PPC_FP128Ty)
8371 return V; // No constant folding of this.
8372 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008373 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008374 return V;
8375 if (CFP->getType() == Type::DoubleTy)
8376 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008377 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008378 return V;
8379 // Don't try to shrink to various long double types.
8380 }
8381
8382 return V;
8383}
8384
8385Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8386 if (Instruction *I = commonCastTransforms(CI))
8387 return I;
8388
8389 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8390 // smaller than the destination type, we can eliminate the truncate by doing
8391 // the add as the smaller type. This applies to add/sub/mul/div as well as
8392 // many builtins (sqrt, etc).
8393 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8394 if (OpI && OpI->hasOneUse()) {
8395 switch (OpI->getOpcode()) {
8396 default: break;
8397 case Instruction::Add:
8398 case Instruction::Sub:
8399 case Instruction::Mul:
8400 case Instruction::FDiv:
8401 case Instruction::FRem:
8402 const Type *SrcTy = OpI->getType();
8403 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8404 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8405 if (LHSTrunc->getType() != SrcTy &&
8406 RHSTrunc->getType() != SrcTy) {
8407 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8408 // If the source types were both smaller than the destination type of
8409 // the cast, do this xform.
8410 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8411 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8412 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8413 CI.getType(), CI);
8414 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8415 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008416 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008417 }
8418 }
8419 break;
8420 }
8421 }
8422 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008423}
8424
8425Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8426 return commonCastTransforms(CI);
8427}
8428
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008429Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008430 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8431 if (OpI == 0)
8432 return commonCastTransforms(FI);
8433
8434 // fptoui(uitofp(X)) --> X
8435 // fptoui(sitofp(X)) --> X
8436 // This is safe if the intermediate type has enough bits in its mantissa to
8437 // accurately represent all values of X. For example, do not do this with
8438 // i64->float->i64. This is also safe for sitofp case, because any negative
8439 // 'X' value would cause an undefined result for the fptoui.
8440 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8441 OpI->getOperand(0)->getType() == FI.getType() &&
8442 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8443 OpI->getType()->getFPMantissaWidth())
8444 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008445
8446 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008447}
8448
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008449Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008450 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8451 if (OpI == 0)
8452 return commonCastTransforms(FI);
8453
8454 // fptosi(sitofp(X)) --> X
8455 // fptosi(uitofp(X)) --> X
8456 // This is safe if the intermediate type has enough bits in its mantissa to
8457 // accurately represent all values of X. For example, do not do this with
8458 // i64->float->i64. This is also safe for sitofp case, because any negative
8459 // 'X' value would cause an undefined result for the fptoui.
8460 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8461 OpI->getOperand(0)->getType() == FI.getType() &&
8462 (int)FI.getType()->getPrimitiveSizeInBits() <=
8463 OpI->getType()->getFPMantissaWidth())
8464 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008465
8466 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008467}
8468
8469Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8470 return commonCastTransforms(CI);
8471}
8472
8473Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8474 return commonCastTransforms(CI);
8475}
8476
8477Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008478 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008479}
8480
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008481Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8482 if (Instruction *I = commonCastTransforms(CI))
8483 return I;
8484
8485 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8486 if (!DestPointee->isSized()) return 0;
8487
8488 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8489 ConstantInt *Cst;
8490 Value *X;
8491 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8492 m_ConstantInt(Cst)))) {
8493 // If the source and destination operands have the same type, see if this
8494 // is a single-index GEP.
8495 if (X->getType() == CI.getType()) {
8496 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008497 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008498
8499 // Convert the constant to intptr type.
8500 APInt Offset = Cst->getValue();
8501 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8502
8503 // If Offset is evenly divisible by Size, we can do this xform.
8504 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8505 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008506 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008507 }
8508 }
8509 // TODO: Could handle other cases, e.g. where add is indexing into field of
8510 // struct etc.
8511 } else if (CI.getOperand(0)->hasOneUse() &&
8512 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8513 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8514 // "inttoptr+GEP" instead of "add+intptr".
8515
8516 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008517 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008518
8519 // Convert the constant to intptr type.
8520 APInt Offset = Cst->getValue();
8521 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8522
8523 // If Offset is evenly divisible by Size, we can do this xform.
8524 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8525 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8526
8527 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8528 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008529 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008530 }
8531 }
8532 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008533}
8534
Chris Lattnerd3e28342007-04-27 17:44:50 +00008535Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008536 // If the operands are integer typed then apply the integer transforms,
8537 // otherwise just apply the common ones.
8538 Value *Src = CI.getOperand(0);
8539 const Type *SrcTy = Src->getType();
8540 const Type *DestTy = CI.getType();
8541
Chris Lattner42a75512007-01-15 02:27:26 +00008542 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008543 if (Instruction *Result = commonIntCastTransforms(CI))
8544 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008545 } else if (isa<PointerType>(SrcTy)) {
8546 if (Instruction *I = commonPointerCastTransforms(CI))
8547 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008548 } else {
8549 if (Instruction *Result = commonCastTransforms(CI))
8550 return Result;
8551 }
8552
8553
8554 // Get rid of casts from one type to the same type. These are useless and can
8555 // be replaced by the operand.
8556 if (DestTy == Src->getType())
8557 return ReplaceInstUsesWith(CI, Src);
8558
Reid Spencer3da59db2006-11-27 01:05:10 +00008559 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008560 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8561 const Type *DstElTy = DstPTy->getElementType();
8562 const Type *SrcElTy = SrcPTy->getElementType();
8563
Nate Begeman83ad90a2008-03-31 00:22:16 +00008564 // If the address spaces don't match, don't eliminate the bitcast, which is
8565 // required for changing types.
8566 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8567 return 0;
8568
Chris Lattnerd3e28342007-04-27 17:44:50 +00008569 // If we are casting a malloc or alloca to a pointer to a type of the same
8570 // size, rewrite the allocation instruction to allocate the "right" type.
8571 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8572 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8573 return V;
8574
Chris Lattnerd717c182007-05-05 22:32:24 +00008575 // If the source and destination are pointers, and this cast is equivalent
8576 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008577 // This can enhance SROA and other transforms that want type-safe pointers.
8578 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8579 unsigned NumZeros = 0;
8580 while (SrcElTy != DstElTy &&
8581 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8582 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8583 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8584 ++NumZeros;
8585 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008586
Chris Lattnerd3e28342007-04-27 17:44:50 +00008587 // If we found a path from the src to dest, create the getelementptr now.
8588 if (SrcElTy == DstElTy) {
8589 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008590 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8591 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008592 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008593 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008594
Reid Spencer3da59db2006-11-27 01:05:10 +00008595 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8596 if (SVI->hasOneUse()) {
8597 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8598 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008599 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008600 cast<VectorType>(DestTy)->getNumElements() ==
8601 SVI->getType()->getNumElements() &&
8602 SVI->getType()->getNumElements() ==
8603 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008604 CastInst *Tmp;
8605 // If either of the operands is a cast from CI.getType(), then
8606 // evaluating the shuffle in the casted destination's type will allow
8607 // us to eliminate at least one cast.
8608 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8609 Tmp->getOperand(0)->getType() == DestTy) ||
8610 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8611 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008612 Value *LHS = InsertCastBefore(Instruction::BitCast,
8613 SVI->getOperand(0), DestTy, CI);
8614 Value *RHS = InsertCastBefore(Instruction::BitCast,
8615 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008616 // Return a new shuffle vector. Use the same element ID's, as we
8617 // know the vector types match #elts.
8618 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008619 }
8620 }
8621 }
8622 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008623 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008624}
8625
Chris Lattnere576b912004-04-09 23:46:01 +00008626/// GetSelectFoldableOperands - We want to turn code that looks like this:
8627/// %C = or %A, %B
8628/// %D = select %cond, %C, %A
8629/// into:
8630/// %C = select %cond, %B, 0
8631/// %D = or %A, %C
8632///
8633/// Assuming that the specified instruction is an operand to the select, return
8634/// a bitmask indicating which operands of this instruction are foldable if they
8635/// equal the other incoming value of the select.
8636///
8637static unsigned GetSelectFoldableOperands(Instruction *I) {
8638 switch (I->getOpcode()) {
8639 case Instruction::Add:
8640 case Instruction::Mul:
8641 case Instruction::And:
8642 case Instruction::Or:
8643 case Instruction::Xor:
8644 return 3; // Can fold through either operand.
8645 case Instruction::Sub: // Can only fold on the amount subtracted.
8646 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008647 case Instruction::LShr:
8648 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008649 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008650 default:
8651 return 0; // Cannot fold
8652 }
8653}
8654
8655/// GetSelectFoldableConstant - For the same transformation as the previous
8656/// function, return the identity constant that goes into the select.
8657static Constant *GetSelectFoldableConstant(Instruction *I) {
8658 switch (I->getOpcode()) {
8659 default: assert(0 && "This cannot happen!"); abort();
8660 case Instruction::Add:
8661 case Instruction::Sub:
8662 case Instruction::Or:
8663 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008664 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008665 case Instruction::LShr:
8666 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008667 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008668 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008669 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008670 case Instruction::Mul:
8671 return ConstantInt::get(I->getType(), 1);
8672 }
8673}
8674
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008675/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8676/// have the same opcode and only one use each. Try to simplify this.
8677Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8678 Instruction *FI) {
8679 if (TI->getNumOperands() == 1) {
8680 // If this is a non-volatile load or a cast from the same type,
8681 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008682 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008683 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8684 return 0;
8685 } else {
8686 return 0; // unknown unary op.
8687 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008688
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008689 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008690 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8691 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008692 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008693 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008694 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008695 }
8696
Reid Spencer832254e2007-02-02 02:16:23 +00008697 // Only handle binary operators here.
8698 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008699 return 0;
8700
8701 // Figure out if the operations have any operands in common.
8702 Value *MatchOp, *OtherOpT, *OtherOpF;
8703 bool MatchIsOpZero;
8704 if (TI->getOperand(0) == FI->getOperand(0)) {
8705 MatchOp = TI->getOperand(0);
8706 OtherOpT = TI->getOperand(1);
8707 OtherOpF = FI->getOperand(1);
8708 MatchIsOpZero = true;
8709 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8710 MatchOp = TI->getOperand(1);
8711 OtherOpT = TI->getOperand(0);
8712 OtherOpF = FI->getOperand(0);
8713 MatchIsOpZero = false;
8714 } else if (!TI->isCommutative()) {
8715 return 0;
8716 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8717 MatchOp = TI->getOperand(0);
8718 OtherOpT = TI->getOperand(1);
8719 OtherOpF = FI->getOperand(0);
8720 MatchIsOpZero = true;
8721 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8722 MatchOp = TI->getOperand(1);
8723 OtherOpT = TI->getOperand(0);
8724 OtherOpF = FI->getOperand(1);
8725 MatchIsOpZero = true;
8726 } else {
8727 return 0;
8728 }
8729
8730 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008731 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8732 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008733 InsertNewInstBefore(NewSI, SI);
8734
8735 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8736 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008737 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008738 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008739 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008740 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008741 assert(0 && "Shouldn't get here");
8742 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008743}
8744
Dan Gohman81b28ce2008-09-16 18:46:06 +00008745/// visitSelectInstWithICmp - Visit a SelectInst that has an
8746/// ICmpInst as its first operand.
8747///
8748Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8749 ICmpInst *ICI) {
8750 bool Changed = false;
8751 ICmpInst::Predicate Pred = ICI->getPredicate();
8752 Value *CmpLHS = ICI->getOperand(0);
8753 Value *CmpRHS = ICI->getOperand(1);
8754 Value *TrueVal = SI.getTrueValue();
8755 Value *FalseVal = SI.getFalseValue();
8756
8757 // Check cases where the comparison is with a constant that
8758 // can be adjusted to fit the min/max idiom. We may edit ICI in
8759 // place here, so make sure the select is the only user.
8760 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00008761 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00008762 switch (Pred) {
8763 default: break;
8764 case ICmpInst::ICMP_ULT:
8765 case ICmpInst::ICMP_SLT: {
8766 // X < MIN ? T : F --> F
8767 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8768 return ReplaceInstUsesWith(SI, FalseVal);
8769 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8770 Constant *AdjustedRHS = SubOne(CI);
8771 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8772 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8773 Pred = ICmpInst::getSwappedPredicate(Pred);
8774 CmpRHS = AdjustedRHS;
8775 std::swap(FalseVal, TrueVal);
8776 ICI->setPredicate(Pred);
8777 ICI->setOperand(1, CmpRHS);
8778 SI.setOperand(1, TrueVal);
8779 SI.setOperand(2, FalseVal);
8780 Changed = true;
8781 }
8782 break;
8783 }
8784 case ICmpInst::ICMP_UGT:
8785 case ICmpInst::ICMP_SGT: {
8786 // X > MAX ? T : F --> F
8787 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8788 return ReplaceInstUsesWith(SI, FalseVal);
8789 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8790 Constant *AdjustedRHS = AddOne(CI);
8791 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8792 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8793 Pred = ICmpInst::getSwappedPredicate(Pred);
8794 CmpRHS = AdjustedRHS;
8795 std::swap(FalseVal, TrueVal);
8796 ICI->setPredicate(Pred);
8797 ICI->setOperand(1, CmpRHS);
8798 SI.setOperand(1, TrueVal);
8799 SI.setOperand(2, FalseVal);
8800 Changed = true;
8801 }
8802 break;
8803 }
8804 }
8805
Dan Gohman1975d032008-10-30 20:40:10 +00008806 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8807 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00008808 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner159c35b2009-01-05 23:53:12 +00008809 if (match(TrueVal, m_ConstantInt<-1>()) &&
8810 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008811 Pred = ICI->getPredicate();
Chris Lattner159c35b2009-01-05 23:53:12 +00008812 else if (match(TrueVal, m_ConstantInt<0>()) &&
8813 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008814 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8815
Dan Gohman1975d032008-10-30 20:40:10 +00008816 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8817 // If we are just checking for a icmp eq of a single bit and zext'ing it
8818 // to an integer, then shift the bit to the appropriate place and then
8819 // cast to integer to avoid the comparison.
8820 const APInt &Op1CV = CI->getValue();
8821
8822 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8823 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8824 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00008825 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00008826 Value *In = ICI->getOperand(0);
8827 Value *Sh = ConstantInt::get(In->getType(),
8828 In->getType()->getPrimitiveSizeInBits()-1);
8829 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8830 In->getName()+".lobit"),
8831 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00008832 if (In->getType() != SI.getType())
8833 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00008834 true/*SExt*/, "tmp", ICI);
8835
8836 if (Pred == ICmpInst::ICMP_SGT)
8837 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8838 In->getName()+".not"), *ICI);
8839
8840 return ReplaceInstUsesWith(SI, In);
8841 }
8842 }
8843 }
8844
Dan Gohman81b28ce2008-09-16 18:46:06 +00008845 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8846 // Transform (X == Y) ? X : Y -> Y
8847 if (Pred == ICmpInst::ICMP_EQ)
8848 return ReplaceInstUsesWith(SI, FalseVal);
8849 // Transform (X != Y) ? X : Y -> X
8850 if (Pred == ICmpInst::ICMP_NE)
8851 return ReplaceInstUsesWith(SI, TrueVal);
8852 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8853
8854 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8855 // Transform (X == Y) ? Y : X -> X
8856 if (Pred == ICmpInst::ICMP_EQ)
8857 return ReplaceInstUsesWith(SI, FalseVal);
8858 // Transform (X != Y) ? Y : X -> Y
8859 if (Pred == ICmpInst::ICMP_NE)
8860 return ReplaceInstUsesWith(SI, TrueVal);
8861 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8862 }
8863
8864 /// NOTE: if we wanted to, this is where to detect integer ABS
8865
8866 return Changed ? &SI : 0;
8867}
8868
Chris Lattner3d69f462004-03-12 05:52:32 +00008869Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008870 Value *CondVal = SI.getCondition();
8871 Value *TrueVal = SI.getTrueValue();
8872 Value *FalseVal = SI.getFalseValue();
8873
8874 // select true, X, Y -> X
8875 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008876 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008877 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008878
8879 // select C, X, X -> X
8880 if (TrueVal == FalseVal)
8881 return ReplaceInstUsesWith(SI, TrueVal);
8882
Chris Lattnere87597f2004-10-16 18:11:37 +00008883 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8884 return ReplaceInstUsesWith(SI, FalseVal);
8885 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8886 return ReplaceInstUsesWith(SI, TrueVal);
8887 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8888 if (isa<Constant>(TrueVal))
8889 return ReplaceInstUsesWith(SI, TrueVal);
8890 else
8891 return ReplaceInstUsesWith(SI, FalseVal);
8892 }
8893
Reid Spencer4fe16d62007-01-11 18:21:29 +00008894 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008895 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008896 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008897 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008898 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008899 } else {
8900 // Change: A = select B, false, C --> A = and !B, C
8901 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008902 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008903 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008904 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008905 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008906 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008907 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008908 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008909 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008910 } else {
8911 // Change: A = select B, C, true --> A = or !B, C
8912 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008913 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008914 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008915 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008916 }
8917 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008918
8919 // select a, b, a -> a&b
8920 // select a, a, b -> a|b
8921 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008922 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008923 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008924 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008925 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008926
Chris Lattner2eefe512004-04-09 19:05:30 +00008927 // Selecting between two integer constants?
8928 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8929 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008930 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008931 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008932 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008933 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008934 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008935 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008936 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008937 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008938 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008939 }
Chris Lattner457dd822004-06-09 07:59:58 +00008940
Reid Spencere4d87aa2006-12-23 06:05:41 +00008941 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008942
Reid Spencere4d87aa2006-12-23 06:05:41 +00008943 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008944 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008945 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008946 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008947 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008948 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008949 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008950 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008951 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008952 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008953 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008954 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008955
8956 // Then cast to the appropriate width.
8957 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00008958 }
8959 }
8960
8961
8962 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008963 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008964 // non-constant value, eliminate this whole mess. This corresponds to
8965 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008966 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008967 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008968 cast<Constant>(IC->getOperand(1))->isNullValue())
8969 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8970 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008971 isa<ConstantInt>(ICA->getOperand(1)) &&
8972 (ICA->getOperand(1) == TrueValC ||
8973 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008974 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8975 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008976 // know whether we have a icmp_ne or icmp_eq and whether the
8977 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008978 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008979 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008980 Value *V = ICA;
8981 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008982 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008983 Instruction::Xor, V, ICA->getOperand(1)), SI);
8984 return ReplaceInstUsesWith(SI, V);
8985 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008986 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008987 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008988
8989 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008990 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8991 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008992 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008993 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8994 // This is not safe in general for floating point:
8995 // consider X== -0, Y== +0.
8996 // It becomes safe if either operand is a nonzero constant.
8997 ConstantFP *CFPt, *CFPf;
8998 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8999 !CFPt->getValueAPF().isZero()) ||
9000 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9001 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009002 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009003 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009004 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009005 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009006 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009007 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009008
Reid Spencere4d87aa2006-12-23 06:05:41 +00009009 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009010 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009011 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9012 // This is not safe in general for floating point:
9013 // consider X== -0, Y== +0.
9014 // It becomes safe if either operand is a nonzero constant.
9015 ConstantFP *CFPt, *CFPf;
9016 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9017 !CFPt->getValueAPF().isZero()) ||
9018 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9019 !CFPf->getValueAPF().isZero()))
9020 return ReplaceInstUsesWith(SI, FalseVal);
9021 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009022 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009023 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9024 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009025 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009026 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009027 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009028 }
9029
9030 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009031 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9032 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9033 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009034
Chris Lattner87875da2005-01-13 22:52:24 +00009035 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9036 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9037 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009038 Instruction *AddOp = 0, *SubOp = 0;
9039
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009040 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9041 if (TI->getOpcode() == FI->getOpcode())
9042 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9043 return IV;
9044
9045 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9046 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00009047 if (TI->getOpcode() == Instruction::Sub &&
9048 FI->getOpcode() == Instruction::Add) {
9049 AddOp = FI; SubOp = TI;
9050 } else if (FI->getOpcode() == Instruction::Sub &&
9051 TI->getOpcode() == Instruction::Add) {
9052 AddOp = TI; SubOp = FI;
9053 }
9054
9055 if (AddOp) {
9056 Value *OtherAddOp = 0;
9057 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9058 OtherAddOp = AddOp->getOperand(1);
9059 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9060 OtherAddOp = AddOp->getOperand(0);
9061 }
9062
9063 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009064 // So at this point we know we have (Y -> OtherAddOp):
9065 // select C, (add X, Y), (sub X, Z)
9066 Value *NegVal; // Compute -Z
9067 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9068 NegVal = ConstantExpr::getNeg(C);
9069 } else {
9070 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009071 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009072 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009073
9074 Value *NewTrueOp = OtherAddOp;
9075 Value *NewFalseOp = NegVal;
9076 if (AddOp != TI)
9077 std::swap(NewTrueOp, NewFalseOp);
9078 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009079 SelectInst::Create(CondVal, NewTrueOp,
9080 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009081
9082 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009083 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009084 }
9085 }
9086 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009087
Chris Lattnere576b912004-04-09 23:46:01 +00009088 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009089 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00009090 // See the comment above GetSelectFoldableOperands for a description of the
9091 // transformation we are doing here.
9092 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9093 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9094 !isa<Constant>(FalseVal))
9095 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9096 unsigned OpToFold = 0;
9097 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9098 OpToFold = 1;
9099 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9100 OpToFold = 2;
9101 }
9102
9103 if (OpToFold) {
9104 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009105 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009106 SelectInst::Create(SI.getCondition(),
9107 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00009108 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00009109 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009110 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009111 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00009112 else {
9113 assert(0 && "Unknown instruction!!");
9114 }
9115 }
9116 }
Chris Lattnera96879a2004-09-29 17:40:11 +00009117
Chris Lattnere576b912004-04-09 23:46:01 +00009118 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9119 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9120 !isa<Constant>(TrueVal))
9121 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9122 unsigned OpToFold = 0;
9123 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9124 OpToFold = 1;
9125 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9126 OpToFold = 2;
9127 }
9128
9129 if (OpToFold) {
9130 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009131 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009132 SelectInst::Create(SI.getCondition(), C,
9133 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00009134 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00009135 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009136 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009137 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00009138 else
Chris Lattnere576b912004-04-09 23:46:01 +00009139 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00009140 }
9141 }
9142 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009143
9144 if (BinaryOperator::isNot(CondVal)) {
9145 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9146 SI.setOperand(1, FalseVal);
9147 SI.setOperand(2, TrueVal);
9148 return &SI;
9149 }
9150
Chris Lattner3d69f462004-03-12 05:52:32 +00009151 return 0;
9152}
9153
Dan Gohmaneee962e2008-04-10 18:43:06 +00009154/// EnforceKnownAlignment - If the specified pointer points to an object that
9155/// we control, modify the object's alignment to PrefAlign. This isn't
9156/// often possible though. If alignment is important, a more reliable approach
9157/// is to simply align all global variables and allocation instructions to
9158/// their preferred alignment from the beginning.
9159///
9160static unsigned EnforceKnownAlignment(Value *V,
9161 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009162
Dan Gohmaneee962e2008-04-10 18:43:06 +00009163 User *U = dyn_cast<User>(V);
9164 if (!U) return Align;
9165
9166 switch (getOpcode(U)) {
9167 default: break;
9168 case Instruction::BitCast:
9169 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9170 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009171 // If all indexes are zero, it is just the alignment of the base pointer.
9172 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009173 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009174 if (!isa<Constant>(*i) ||
9175 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009176 AllZeroOperands = false;
9177 break;
9178 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009179
9180 if (AllZeroOperands) {
9181 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009182 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009183 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009184 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009185 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009186 }
9187
9188 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9189 // If there is a large requested alignment and we can, bump up the alignment
9190 // of the global.
9191 if (!GV->isDeclaration()) {
9192 GV->setAlignment(PrefAlign);
9193 Align = PrefAlign;
9194 }
9195 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9196 // If there is a requested alignment and if this is an alloca, round up. We
9197 // don't do this for malloc, because some systems can't respect the request.
9198 if (isa<AllocaInst>(AI)) {
9199 AI->setAlignment(PrefAlign);
9200 Align = PrefAlign;
9201 }
9202 }
9203
9204 return Align;
9205}
9206
9207/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9208/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9209/// and it is more than the alignment of the ultimate object, see if we can
9210/// increase the alignment of the ultimate object, making this check succeed.
9211unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9212 unsigned PrefAlign) {
9213 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9214 sizeof(PrefAlign) * CHAR_BIT;
9215 APInt Mask = APInt::getAllOnesValue(BitWidth);
9216 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9217 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9218 unsigned TrailZ = KnownZero.countTrailingOnes();
9219 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9220
9221 if (PrefAlign > Align)
9222 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9223
9224 // We don't need to make any adjustment.
9225 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009226}
9227
Chris Lattnerf497b022008-01-13 23:50:23 +00009228Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009229 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9230 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009231 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9232 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9233
9234 if (CopyAlign < MinAlign) {
9235 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9236 return MI;
9237 }
9238
9239 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9240 // load/store.
9241 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9242 if (MemOpLength == 0) return 0;
9243
Chris Lattner37ac6082008-01-14 00:28:35 +00009244 // Source and destination pointer types are always "i8*" for intrinsic. See
9245 // if the size is something we can handle with a single primitive load/store.
9246 // A single load+store correctly handles overlapping memory in the memmove
9247 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009248 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009249 if (Size == 0) return MI; // Delete this mem transfer.
9250
9251 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009252 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009253
Chris Lattner37ac6082008-01-14 00:28:35 +00009254 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009255 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009256
9257 // Memcpy forces the use of i8* for the source and destination. That means
9258 // that if you're using memcpy to move one double around, you'll get a cast
9259 // from double* to i8*. We'd much rather use a double load+store rather than
9260 // an i64 load+store, here because this improves the odds that the source or
9261 // dest address will be promotable. See if we can find a better type than the
9262 // integer datatype.
9263 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9264 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9265 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9266 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9267 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009268 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009269 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9270 if (STy->getNumElements() == 1)
9271 SrcETy = STy->getElementType(0);
9272 else
9273 break;
9274 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9275 if (ATy->getNumElements() == 1)
9276 SrcETy = ATy->getElementType();
9277 else
9278 break;
9279 } else
9280 break;
9281 }
9282
Dan Gohman8f8e2692008-05-23 01:52:21 +00009283 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009284 NewPtrTy = PointerType::getUnqual(SrcETy);
9285 }
9286 }
9287
9288
Chris Lattnerf497b022008-01-13 23:50:23 +00009289 // If the memcpy/memmove provides better alignment info than we can
9290 // infer, use it.
9291 SrcAlign = std::max(SrcAlign, CopyAlign);
9292 DstAlign = std::max(DstAlign, CopyAlign);
9293
9294 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9295 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009296 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9297 InsertNewInstBefore(L, *MI);
9298 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9299
9300 // Set the size of the copy to 0, it will be deleted on the next iteration.
9301 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9302 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009303}
Chris Lattner3d69f462004-03-12 05:52:32 +00009304
Chris Lattner69ea9d22008-04-30 06:39:11 +00009305Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9306 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9307 if (MI->getAlignment()->getZExtValue() < Alignment) {
9308 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9309 return MI;
9310 }
9311
9312 // Extract the length and alignment and fill if they are constant.
9313 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9314 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9315 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9316 return 0;
9317 uint64_t Len = LenC->getZExtValue();
9318 Alignment = MI->getAlignment()->getZExtValue();
9319
9320 // If the length is zero, this is a no-op
9321 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9322
9323 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9324 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9325 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9326
9327 Value *Dest = MI->getDest();
9328 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9329
9330 // Alignment 0 is identity for alignment 1 for memset, but not store.
9331 if (Alignment == 0) Alignment = 1;
9332
9333 // Extract the fill value and store.
9334 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9335 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9336 Alignment), *MI);
9337
9338 // Set the size of the copy to 0, it will be deleted on the next iteration.
9339 MI->setLength(Constant::getNullValue(LenC->getType()));
9340 return MI;
9341 }
9342
9343 return 0;
9344}
9345
9346
Chris Lattner8b0ea312006-01-13 20:11:04 +00009347/// visitCallInst - CallInst simplification. This mostly only handles folding
9348/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9349/// the heavy lifting.
9350///
Chris Lattner9fe38862003-06-19 17:00:31 +00009351Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009352 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9353 if (!II) return visitCallSite(&CI);
9354
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009355 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9356 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009357 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009358 bool Changed = false;
9359
9360 // memmove/cpy/set of zero bytes is a noop.
9361 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9362 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9363
Chris Lattner35b9e482004-10-12 04:52:52 +00009364 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009365 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009366 // Replace the instruction with just byte operations. We would
9367 // transform other cases to loads/stores, but we don't know if
9368 // alignment is sufficient.
9369 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009370 }
9371
Chris Lattner35b9e482004-10-12 04:52:52 +00009372 // If we have a memmove and the source operation is a constant global,
9373 // then the source and dest pointers can't alias, so we can change this
9374 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009375 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009376 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9377 if (GVSrc->isConstant()) {
9378 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009379 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9380 const Type *Tys[1];
9381 Tys[0] = CI.getOperand(3)->getType();
9382 CI.setOperand(0,
9383 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009384 Changed = true;
9385 }
Chris Lattnera935db82008-05-28 05:30:41 +00009386
9387 // memmove(x,x,size) -> noop.
9388 if (MMI->getSource() == MMI->getDest())
9389 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009390 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009391
Chris Lattner95a959d2006-03-06 20:18:44 +00009392 // If we can determine a pointer alignment that is bigger than currently
9393 // set, update the alignment.
9394 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009395 if (Instruction *I = SimplifyMemTransfer(MI))
9396 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009397 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9398 if (Instruction *I = SimplifyMemSet(MSI))
9399 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009400 }
9401
Chris Lattner8b0ea312006-01-13 20:11:04 +00009402 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009403 }
9404
9405 switch (II->getIntrinsicID()) {
9406 default: break;
9407 case Intrinsic::bswap:
9408 // bswap(bswap(x)) -> x
9409 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9410 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9411 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9412 break;
9413 case Intrinsic::ppc_altivec_lvx:
9414 case Intrinsic::ppc_altivec_lvxl:
9415 case Intrinsic::x86_sse_loadu_ps:
9416 case Intrinsic::x86_sse2_loadu_pd:
9417 case Intrinsic::x86_sse2_loadu_dq:
9418 // Turn PPC lvx -> load if the pointer is known aligned.
9419 // Turn X86 loadups -> load if the pointer is known aligned.
9420 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9421 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9422 PointerType::getUnqual(II->getType()),
9423 CI);
9424 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009425 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009426 break;
9427 case Intrinsic::ppc_altivec_stvx:
9428 case Intrinsic::ppc_altivec_stvxl:
9429 // Turn stvx -> store if the pointer is known aligned.
9430 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9431 const Type *OpPtrTy =
9432 PointerType::getUnqual(II->getOperand(1)->getType());
9433 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9434 return new StoreInst(II->getOperand(1), Ptr);
9435 }
9436 break;
9437 case Intrinsic::x86_sse_storeu_ps:
9438 case Intrinsic::x86_sse2_storeu_pd:
9439 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009440 // Turn X86 storeu -> store if the pointer is known aligned.
9441 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9442 const Type *OpPtrTy =
9443 PointerType::getUnqual(II->getOperand(2)->getType());
9444 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9445 return new StoreInst(II->getOperand(2), Ptr);
9446 }
9447 break;
9448
9449 case Intrinsic::x86_sse_cvttss2si: {
9450 // These intrinsics only demands the 0th element of its input vector. If
9451 // we can simplify the input based on that, do so now.
9452 uint64_t UndefElts;
9453 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9454 UndefElts)) {
9455 II->setOperand(1, V);
9456 return II;
9457 }
9458 break;
9459 }
9460
9461 case Intrinsic::ppc_altivec_vperm:
9462 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9463 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9464 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009465
Chris Lattner0521e3c2008-06-18 04:33:20 +00009466 // Check that all of the elements are integer constants or undefs.
9467 bool AllEltsOk = true;
9468 for (unsigned i = 0; i != 16; ++i) {
9469 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9470 !isa<UndefValue>(Mask->getOperand(i))) {
9471 AllEltsOk = false;
9472 break;
9473 }
9474 }
9475
9476 if (AllEltsOk) {
9477 // Cast the input vectors to byte vectors.
9478 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9479 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9480 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009481
Chris Lattner0521e3c2008-06-18 04:33:20 +00009482 // Only extract each element once.
9483 Value *ExtractedElts[32];
9484 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9485
Chris Lattnere2ed0572006-04-06 19:19:17 +00009486 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009487 if (isa<UndefValue>(Mask->getOperand(i)))
9488 continue;
9489 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9490 Idx &= 31; // Match the hardware behavior.
9491
9492 if (ExtractedElts[Idx] == 0) {
9493 Instruction *Elt =
9494 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9495 InsertNewInstBefore(Elt, CI);
9496 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009497 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009498
Chris Lattner0521e3c2008-06-18 04:33:20 +00009499 // Insert this value into the result vector.
9500 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9501 i, "tmp");
9502 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009503 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009504 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009505 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009506 }
9507 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009508
Chris Lattner0521e3c2008-06-18 04:33:20 +00009509 case Intrinsic::stackrestore: {
9510 // If the save is right next to the restore, remove the restore. This can
9511 // happen when variable allocas are DCE'd.
9512 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9513 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9514 BasicBlock::iterator BI = SS;
9515 if (&*++BI == II)
9516 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009517 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009518 }
9519
9520 // Scan down this block to see if there is another stack restore in the
9521 // same block without an intervening call/alloca.
9522 BasicBlock::iterator BI = II;
9523 TerminatorInst *TI = II->getParent()->getTerminator();
9524 bool CannotRemove = false;
9525 for (++BI; &*BI != TI; ++BI) {
9526 if (isa<AllocaInst>(BI)) {
9527 CannotRemove = true;
9528 break;
9529 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009530 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9531 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9532 // If there is a stackrestore below this one, remove this one.
9533 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9534 return EraseInstFromFunction(CI);
9535 // Otherwise, ignore the intrinsic.
9536 } else {
9537 // If we found a non-intrinsic call, we can't remove the stack
9538 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009539 CannotRemove = true;
9540 break;
9541 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009542 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009543 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009544
9545 // If the stack restore is in a return/unwind block and if there are no
9546 // allocas or calls between the restore and the return, nuke the restore.
9547 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9548 return EraseInstFromFunction(CI);
9549 break;
9550 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009551 }
9552
Chris Lattner8b0ea312006-01-13 20:11:04 +00009553 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009554}
9555
9556// InvokeInst simplification
9557//
9558Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009559 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009560}
9561
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009562/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9563/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009564static bool isSafeToEliminateVarargsCast(const CallSite CS,
9565 const CastInst * const CI,
9566 const TargetData * const TD,
9567 const int ix) {
9568 if (!CI->isLosslessCast())
9569 return false;
9570
9571 // The size of ByVal arguments is derived from the type, so we
9572 // can't change to a type with a different size. If the size were
9573 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009574 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009575 return true;
9576
9577 const Type* SrcTy =
9578 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9579 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9580 if (!SrcTy->isSized() || !DstTy->isSized())
9581 return false;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00009582 if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009583 return false;
9584 return true;
9585}
9586
Chris Lattnera44d8a22003-10-07 22:32:43 +00009587// visitCallSite - Improvements for call and invoke instructions.
9588//
9589Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009590 bool Changed = false;
9591
9592 // If the callee is a constexpr cast of a function, attempt to move the cast
9593 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009594 if (transformConstExprCastCall(CS)) return 0;
9595
Chris Lattner6c266db2003-10-07 22:54:13 +00009596 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009597
Chris Lattner08b22ec2005-05-13 07:09:09 +00009598 if (Function *CalleeF = dyn_cast<Function>(Callee))
9599 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9600 Instruction *OldCall = CS.getInstruction();
9601 // If the call and callee calling conventions don't match, this call must
9602 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009603 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009604 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9605 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009606 if (!OldCall->use_empty())
9607 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9608 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9609 return EraseInstFromFunction(*OldCall);
9610 return 0;
9611 }
9612
Chris Lattner17be6352004-10-18 02:59:09 +00009613 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9614 // This instruction is not reachable, just remove it. We insert a store to
9615 // undef so that we know that this code is not reachable, despite the fact
9616 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009617 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009618 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009619 CS.getInstruction());
9620
9621 if (!CS.getInstruction()->use_empty())
9622 CS.getInstruction()->
9623 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9624
9625 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9626 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009627 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9628 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009629 }
Chris Lattner17be6352004-10-18 02:59:09 +00009630 return EraseInstFromFunction(*CS.getInstruction());
9631 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009632
Duncan Sandscdb6d922007-09-17 10:26:40 +00009633 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9634 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9635 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9636 return transformCallThroughTrampoline(CS);
9637
Chris Lattner6c266db2003-10-07 22:54:13 +00009638 const PointerType *PTy = cast<PointerType>(Callee->getType());
9639 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9640 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009641 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009642 // See if we can optimize any arguments passed through the varargs area of
9643 // the call.
9644 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009645 E = CS.arg_end(); I != E; ++I, ++ix) {
9646 CastInst *CI = dyn_cast<CastInst>(*I);
9647 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9648 *I = CI->getOperand(0);
9649 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009650 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009651 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009652 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009653
Duncan Sandsf0c33542007-12-19 21:13:37 +00009654 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009655 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009656 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009657 Changed = true;
9658 }
9659
Chris Lattner6c266db2003-10-07 22:54:13 +00009660 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009661}
9662
Chris Lattner9fe38862003-06-19 17:00:31 +00009663// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9664// attempt to move the cast to the arguments of the call/invoke.
9665//
9666bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9667 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9668 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009669 if (CE->getOpcode() != Instruction::BitCast ||
9670 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009671 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009672 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009673 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009674 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009675
9676 // Okay, this is a cast from a function to a different type. Unless doing so
9677 // would cause a type conversion of one of our arguments, change this call to
9678 // be a direct call with arguments casted to the appropriate types.
9679 //
9680 const FunctionType *FT = Callee->getFunctionType();
9681 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009682 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009683
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009684 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009685 return false; // TODO: Handle multiple return values.
9686
Chris Lattnerf78616b2004-01-14 06:06:08 +00009687 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009688 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009689 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009690 // Conversion is ok if changing from one pointer type to another or from
9691 // a pointer to an integer of the same size.
9692 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00009693 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00009694 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009695
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009696 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009697 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009698 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009699 return false; // Cannot transform this return value.
9700
Chris Lattner58d74912008-03-12 17:45:29 +00009701 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009702 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009703 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009704 return false; // Attribute not compatible with transformed value.
9705 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009706
Chris Lattnerf78616b2004-01-14 06:06:08 +00009707 // If the callsite is an invoke instruction, and the return value is used by
9708 // a PHI node in a successor, we cannot change the return type of the call
9709 // because there is no place to put the cast instruction (without breaking
9710 // the critical edge). Bail out in this case.
9711 if (!Caller->use_empty())
9712 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9713 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9714 UI != E; ++UI)
9715 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9716 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009717 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009718 return false;
9719 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009720
9721 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9722 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009723
Chris Lattner9fe38862003-06-19 17:00:31 +00009724 CallSite::arg_iterator AI = CS.arg_begin();
9725 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9726 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009727 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009728
9729 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009730 return false; // Cannot transform this parameter value.
9731
Devang Patel19c87462008-09-26 22:53:05 +00009732 if (CallerPAL.getParamAttributes(i + 1)
9733 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00009734 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009735
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009736 // Converting from one pointer type to another or between a pointer and an
9737 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00009738 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009739 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9740 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00009741 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009742 }
9743
9744 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009745 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009746 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009747
Chris Lattner58d74912008-03-12 17:45:29 +00009748 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9749 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009750 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009751 // won't be dropping them. Check that these extra arguments have attributes
9752 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009753 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9754 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009755 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00009756 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00009757 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00009758 return false;
9759 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009760
Chris Lattner9fe38862003-06-19 17:00:31 +00009761 // Okay, we decided that this is a safe thing to do: go ahead and start
9762 // inserting cast instructions as necessary...
9763 std::vector<Value*> Args;
9764 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00009765 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009766 attrVec.reserve(NumCommonArgs);
9767
9768 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009769 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009770
9771 // If the return value is not being used, the type may not be compatible
9772 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00009773 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009774
9775 // Add the new return attributes.
9776 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00009777 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009778
9779 AI = CS.arg_begin();
9780 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9781 const Type *ParamTy = FT->getParamType(i);
9782 if ((*AI)->getType() == ParamTy) {
9783 Args.push_back(*AI);
9784 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009785 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009786 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009787 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009788 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009789 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009790
9791 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009792 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009793 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009794 }
9795
9796 // If the function takes more arguments than the call was taking, add them
9797 // now...
9798 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9799 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9800
9801 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009802 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009803 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009804 cerr << "WARNING: While resolving call to function '"
9805 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009806 } else {
9807 // Add all of the arguments in their promoted form to the arg list...
9808 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9809 const Type *PTy = getPromotedType((*AI)->getType());
9810 if (PTy != (*AI)->getType()) {
9811 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009812 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9813 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009814 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009815 InsertNewInstBefore(Cast, *Caller);
9816 Args.push_back(Cast);
9817 } else {
9818 Args.push_back(*AI);
9819 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009820
Duncan Sandse1e520f2008-01-13 08:02:44 +00009821 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009822 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009823 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00009824 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009825 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009826 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009827
Devang Patel19c87462008-09-26 22:53:05 +00009828 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9829 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9830
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009831 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009832 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009833
Devang Patel05988662008-09-25 21:00:45 +00009834 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009835
Chris Lattner9fe38862003-06-19 17:00:31 +00009836 Instruction *NC;
9837 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009838 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009839 Args.begin(), Args.end(),
9840 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009841 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009842 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009843 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009844 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9845 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009846 CallInst *CI = cast<CallInst>(Caller);
9847 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009848 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009849 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009850 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009851 }
9852
Chris Lattner6934a042007-02-11 01:23:03 +00009853 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009854 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009855 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009856 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009857 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009858 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009859 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009860
9861 // If this is an invoke instruction, we should insert it after the first
9862 // non-phi, instruction in the normal successor block.
9863 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009864 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009865 InsertNewInstBefore(NC, *I);
9866 } else {
9867 // Otherwise, it's a call, just insert cast right after the call instr
9868 InsertNewInstBefore(NC, *Caller);
9869 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009870 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009871 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009872 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009873 }
9874 }
9875
9876 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9877 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009878 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009879 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009880 return true;
9881}
9882
Duncan Sandscdb6d922007-09-17 10:26:40 +00009883// transformCallThroughTrampoline - Turn a call to a function created by the
9884// init_trampoline intrinsic into a direct call to the underlying function.
9885//
9886Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9887 Value *Callee = CS.getCalledValue();
9888 const PointerType *PTy = cast<PointerType>(Callee->getType());
9889 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00009890 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009891
9892 // If the call already has the 'nest' attribute somewhere then give up -
9893 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00009894 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009895 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009896
9897 IntrinsicInst *Tramp =
9898 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9899
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009900 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009901 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9902 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9903
Devang Patel05988662008-09-25 21:00:45 +00009904 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00009905 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009906 unsigned NestIdx = 1;
9907 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00009908 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009909
9910 // Look for a parameter marked with the 'nest' attribute.
9911 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9912 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00009913 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009914 // Record the parameter type and any other attributes.
9915 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00009916 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009917 break;
9918 }
9919
9920 if (NestTy) {
9921 Instruction *Caller = CS.getInstruction();
9922 std::vector<Value*> NewArgs;
9923 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9924
Devang Patel05988662008-09-25 21:00:45 +00009925 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00009926 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009927
Duncan Sandscdb6d922007-09-17 10:26:40 +00009928 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009929 // mean appending it. Likewise for attributes.
9930
Devang Patel19c87462008-09-26 22:53:05 +00009931 // Add any result attributes.
9932 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00009933 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009934
Duncan Sandscdb6d922007-09-17 10:26:40 +00009935 {
9936 unsigned Idx = 1;
9937 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9938 do {
9939 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009940 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009941 Value *NestVal = Tramp->getOperand(3);
9942 if (NestVal->getType() != NestTy)
9943 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9944 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00009945 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009946 }
9947
9948 if (I == E)
9949 break;
9950
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009951 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009952 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +00009953 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009954 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +00009955 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009956
9957 ++Idx, ++I;
9958 } while (1);
9959 }
9960
Devang Patel19c87462008-09-26 22:53:05 +00009961 // Add any function attributes.
9962 if (Attributes Attr = Attrs.getFnAttributes())
9963 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9964
Duncan Sandscdb6d922007-09-17 10:26:40 +00009965 // The trampoline may have been bitcast to a bogus type (FTy).
9966 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009967 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009968
Duncan Sandscdb6d922007-09-17 10:26:40 +00009969 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009970 NewTypes.reserve(FTy->getNumParams()+1);
9971
Duncan Sandscdb6d922007-09-17 10:26:40 +00009972 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009973 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009974 {
9975 unsigned Idx = 1;
9976 FunctionType::param_iterator I = FTy->param_begin(),
9977 E = FTy->param_end();
9978
9979 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009980 if (Idx == NestIdx)
9981 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009982 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009983
9984 if (I == E)
9985 break;
9986
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009987 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009988 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009989
9990 ++Idx, ++I;
9991 } while (1);
9992 }
9993
9994 // Replace the trampoline call with a direct call. Let the generic
9995 // code sort out any function type mismatches.
9996 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009997 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009998 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9999 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010000 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010001
10002 Instruction *NewCaller;
10003 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010004 NewCaller = InvokeInst::Create(NewCallee,
10005 II->getNormalDest(), II->getUnwindDest(),
10006 NewArgs.begin(), NewArgs.end(),
10007 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010008 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010009 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010010 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010011 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10012 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010013 if (cast<CallInst>(Caller)->isTailCall())
10014 cast<CallInst>(NewCaller)->setTailCall();
10015 cast<CallInst>(NewCaller)->
10016 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010017 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010018 }
10019 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10020 Caller->replaceAllUsesWith(NewCaller);
10021 Caller->eraseFromParent();
10022 RemoveFromWorkList(Caller);
10023 return 0;
10024 }
10025 }
10026
10027 // Replace the trampoline call with a direct call. Since there is no 'nest'
10028 // parameter, there is no need to adjust the argument list. Let the generic
10029 // code sort out any function type mismatches.
10030 Constant *NewCallee =
10031 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10032 CS.setCalledFunction(NewCallee);
10033 return CS.getInstruction();
10034}
10035
Chris Lattner7da52b22006-11-01 04:51:18 +000010036/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10037/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10038/// and a single binop.
10039Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10040 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010041 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010042 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010043 Value *LHSVal = FirstInst->getOperand(0);
10044 Value *RHSVal = FirstInst->getOperand(1);
10045
10046 const Type *LHSType = LHSVal->getType();
10047 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010048
10049 // Scan to see if all operands are the same opcode, all have one use, and all
10050 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010051 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010052 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010053 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010054 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010055 // types or GEP's with different index types.
10056 I->getOperand(0)->getType() != LHSType ||
10057 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010058 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010059
10060 // If they are CmpInst instructions, check their predicates
10061 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10062 if (cast<CmpInst>(I)->getPredicate() !=
10063 cast<CmpInst>(FirstInst)->getPredicate())
10064 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010065
10066 // Keep track of which operand needs a phi node.
10067 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10068 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010069 }
10070
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010071 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010072
Chris Lattner7da52b22006-11-01 04:51:18 +000010073 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010074 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010075 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010076 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010077 NewLHS = PHINode::Create(LHSType,
10078 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010079 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10080 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010081 InsertNewInstBefore(NewLHS, PN);
10082 LHSVal = NewLHS;
10083 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010084
10085 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010086 NewRHS = PHINode::Create(RHSType,
10087 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010088 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10089 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010090 InsertNewInstBefore(NewRHS, PN);
10091 RHSVal = NewRHS;
10092 }
10093
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010094 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010095 if (NewLHS || NewRHS) {
10096 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10097 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10098 if (NewLHS) {
10099 Value *NewInLHS = InInst->getOperand(0);
10100 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10101 }
10102 if (NewRHS) {
10103 Value *NewInRHS = InInst->getOperand(1);
10104 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10105 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010106 }
10107 }
10108
Chris Lattner7da52b22006-11-01 04:51:18 +000010109 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010110 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010111 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10112 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10113 RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010114}
10115
Chris Lattner05f18922008-12-01 02:34:36 +000010116Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10117 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10118
10119 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10120 FirstInst->op_end());
10121
10122 // Scan to see if all operands are the same opcode, all have one use, and all
10123 // kill their operands (i.e. the operands have one use).
10124 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10125 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10126 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10127 GEP->getNumOperands() != FirstInst->getNumOperands())
10128 return 0;
10129
10130 // Compare the operand lists.
10131 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10132 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10133 continue;
10134
10135 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10136 // if one of the PHIs has a constant for the index. The index may be
10137 // substantially cheaper to compute for the constants, so making it a
10138 // variable index could pessimize the path. This also handles the case
10139 // for struct indices, which must always be constant.
10140 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10141 isa<ConstantInt>(GEP->getOperand(op)))
10142 return 0;
10143
10144 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10145 return 0;
10146 FixedOperands[op] = 0; // Needs a PHI.
10147 }
10148 }
10149
10150 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10151 // that is variable.
10152 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10153
10154 bool HasAnyPHIs = false;
10155 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10156 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10157 Value *FirstOp = FirstInst->getOperand(i);
10158 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10159 FirstOp->getName()+".pn");
10160 InsertNewInstBefore(NewPN, PN);
10161
10162 NewPN->reserveOperandSpace(e);
10163 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10164 OperandPhis[i] = NewPN;
10165 FixedOperands[i] = NewPN;
10166 HasAnyPHIs = true;
10167 }
10168
10169
10170 // Add all operands to the new PHIs.
10171 if (HasAnyPHIs) {
10172 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10173 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10174 BasicBlock *InBB = PN.getIncomingBlock(i);
10175
10176 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10177 if (PHINode *OpPhi = OperandPhis[op])
10178 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10179 }
10180 }
10181
10182 Value *Base = FixedOperands[0];
10183 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10184 FixedOperands.end());
10185}
10186
10187
Chris Lattner76c73142006-11-01 07:13:54 +000010188/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10189/// of the block that defines it. This means that it must be obvious the value
10190/// of the load is not changed from the point of the load to the end of the
10191/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010192///
10193/// Finally, it is safe, but not profitable, to sink a load targetting a
10194/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10195/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +000010196static bool isSafeToSinkLoad(LoadInst *L) {
10197 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10198
10199 for (++BBI; BBI != E; ++BBI)
10200 if (BBI->mayWriteToMemory())
10201 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010202
10203 // Check for non-address taken alloca. If not address-taken already, it isn't
10204 // profitable to do this xform.
10205 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10206 bool isAddressTaken = false;
10207 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10208 UI != E; ++UI) {
10209 if (isa<LoadInst>(UI)) continue;
10210 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10211 // If storing TO the alloca, then the address isn't taken.
10212 if (SI->getOperand(1) == AI) continue;
10213 }
10214 isAddressTaken = true;
10215 break;
10216 }
10217
10218 if (!isAddressTaken)
10219 return false;
10220 }
10221
Chris Lattner76c73142006-11-01 07:13:54 +000010222 return true;
10223}
10224
Chris Lattner9fe38862003-06-19 17:00:31 +000010225
Chris Lattnerbac32862004-11-14 19:13:23 +000010226// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10227// operator and they all are only used by the PHI, PHI together their
10228// inputs, and do the operation once, to the result of the PHI.
10229Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10230 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10231
10232 // Scan the instruction, looking for input operations that can be folded away.
10233 // If all input operands to the phi are the same instruction (e.g. a cast from
10234 // the same type or "+42") we can pull the operation through the PHI, reducing
10235 // code size and simplifying code.
10236 Constant *ConstantOp = 0;
10237 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010238 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010239 if (isa<CastInst>(FirstInst)) {
10240 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010241 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010242 // Can fold binop, compare or shift here if the RHS is a constant,
10243 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010244 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010245 if (ConstantOp == 0)
10246 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010247 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10248 isVolatile = LI->isVolatile();
10249 // We can't sink the load if the loaded value could be modified between the
10250 // load and the PHI.
10251 if (LI->getParent() != PN.getIncomingBlock(0) ||
10252 !isSafeToSinkLoad(LI))
10253 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010254
10255 // If the PHI is of volatile loads and the load block has multiple
10256 // successors, sinking it would remove a load of the volatile value from
10257 // the path through the other successor.
10258 if (isVolatile &&
10259 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10260 return 0;
10261
Chris Lattner9c080502006-11-01 07:43:41 +000010262 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010263 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010264 } else {
10265 return 0; // Cannot fold this operation.
10266 }
10267
10268 // Check to see if all arguments are the same operation.
10269 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10270 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10271 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010272 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010273 return 0;
10274 if (CastSrcTy) {
10275 if (I->getOperand(0)->getType() != CastSrcTy)
10276 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010277 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010278 // We can't sink the load if the loaded value could be modified between
10279 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010280 if (LI->isVolatile() != isVolatile ||
10281 LI->getParent() != PN.getIncomingBlock(i) ||
10282 !isSafeToSinkLoad(LI))
10283 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010284
Chris Lattner71042962008-07-08 17:18:32 +000010285 // If the PHI is of volatile loads and the load block has multiple
10286 // successors, sinking it would remove a load of the volatile value from
10287 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010288 if (isVolatile &&
10289 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10290 return 0;
10291
10292
Chris Lattnerbac32862004-11-14 19:13:23 +000010293 } else if (I->getOperand(1) != ConstantOp) {
10294 return 0;
10295 }
10296 }
10297
10298 // Okay, they are all the same operation. Create a new PHI node of the
10299 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010300 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10301 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010302 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010303
10304 Value *InVal = FirstInst->getOperand(0);
10305 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010306
10307 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010308 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10309 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10310 if (NewInVal != InVal)
10311 InVal = 0;
10312 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10313 }
10314
10315 Value *PhiVal;
10316 if (InVal) {
10317 // The new PHI unions all of the same values together. This is really
10318 // common, so we handle it intelligently here for compile-time speed.
10319 PhiVal = InVal;
10320 delete NewPN;
10321 } else {
10322 InsertNewInstBefore(NewPN, PN);
10323 PhiVal = NewPN;
10324 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010325
Chris Lattnerbac32862004-11-14 19:13:23 +000010326 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010327 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010328 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010329 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010330 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010331 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010332 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010333 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010334 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10335
10336 // If this was a volatile load that we are merging, make sure to loop through
10337 // and mark all the input loads as non-volatile. If we don't do this, we will
10338 // insert a new volatile load and the old ones will not be deletable.
10339 if (isVolatile)
10340 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10341 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10342
10343 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010344}
Chris Lattnera1be5662002-05-02 17:06:02 +000010345
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010346/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10347/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010348static bool DeadPHICycle(PHINode *PN,
10349 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010350 if (PN->use_empty()) return true;
10351 if (!PN->hasOneUse()) return false;
10352
10353 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010354 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010355 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010356
10357 // Don't scan crazily complex things.
10358 if (PotentiallyDeadPHIs.size() == 16)
10359 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010360
10361 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10362 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010363
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010364 return false;
10365}
10366
Chris Lattnercf5008a2007-11-06 21:52:06 +000010367/// PHIsEqualValue - Return true if this phi node is always equal to
10368/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10369/// z = some value; x = phi (y, z); y = phi (x, z)
10370static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10371 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10372 // See if we already saw this PHI node.
10373 if (!ValueEqualPHIs.insert(PN))
10374 return true;
10375
10376 // Don't scan crazily complex things.
10377 if (ValueEqualPHIs.size() == 16)
10378 return false;
10379
10380 // Scan the operands to see if they are either phi nodes or are equal to
10381 // the value.
10382 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10383 Value *Op = PN->getIncomingValue(i);
10384 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10385 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10386 return false;
10387 } else if (Op != NonPhiInVal)
10388 return false;
10389 }
10390
10391 return true;
10392}
10393
10394
Chris Lattner473945d2002-05-06 18:06:38 +000010395// PHINode simplification
10396//
Chris Lattner7e708292002-06-25 16:13:24 +000010397Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010398 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010399 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010400
Owen Anderson7e057142006-07-10 22:03:18 +000010401 if (Value *V = PN.hasConstantValue())
10402 return ReplaceInstUsesWith(PN, V);
10403
Owen Anderson7e057142006-07-10 22:03:18 +000010404 // If all PHI operands are the same operation, pull them through the PHI,
10405 // reducing code size.
10406 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010407 isa<Instruction>(PN.getIncomingValue(1)) &&
10408 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10409 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10410 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10411 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010412 PN.getIncomingValue(0)->hasOneUse())
10413 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10414 return Result;
10415
10416 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10417 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10418 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010419 if (PN.hasOneUse()) {
10420 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10421 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010422 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010423 PotentiallyDeadPHIs.insert(&PN);
10424 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10425 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10426 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010427
10428 // If this phi has a single use, and if that use just computes a value for
10429 // the next iteration of a loop, delete the phi. This occurs with unused
10430 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10431 // common case here is good because the only other things that catch this
10432 // are induction variable analysis (sometimes) and ADCE, which is only run
10433 // late.
10434 if (PHIUser->hasOneUse() &&
10435 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10436 PHIUser->use_back() == &PN) {
10437 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10438 }
10439 }
Owen Anderson7e057142006-07-10 22:03:18 +000010440
Chris Lattnercf5008a2007-11-06 21:52:06 +000010441 // We sometimes end up with phi cycles that non-obviously end up being the
10442 // same value, for example:
10443 // z = some value; x = phi (y, z); y = phi (x, z)
10444 // where the phi nodes don't necessarily need to be in the same block. Do a
10445 // quick check to see if the PHI node only contains a single non-phi value, if
10446 // so, scan to see if the phi cycle is actually equal to that value.
10447 {
10448 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10449 // Scan for the first non-phi operand.
10450 while (InValNo != NumOperandVals &&
10451 isa<PHINode>(PN.getIncomingValue(InValNo)))
10452 ++InValNo;
10453
10454 if (InValNo != NumOperandVals) {
10455 Value *NonPhiInVal = PN.getOperand(InValNo);
10456
10457 // Scan the rest of the operands to see if there are any conflicts, if so
10458 // there is no need to recursively scan other phis.
10459 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10460 Value *OpVal = PN.getIncomingValue(InValNo);
10461 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10462 break;
10463 }
10464
10465 // If we scanned over all operands, then we have one unique value plus
10466 // phi values. Scan PHI nodes to see if they all merge in each other or
10467 // the value.
10468 if (InValNo == NumOperandVals) {
10469 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10470 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10471 return ReplaceInstUsesWith(PN, NonPhiInVal);
10472 }
10473 }
10474 }
Chris Lattner60921c92003-12-19 05:58:40 +000010475 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010476}
10477
Reid Spencer17212df2006-12-12 09:18:51 +000010478static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10479 Instruction *InsertPoint,
10480 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010481 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10482 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010483 // We must cast correctly to the pointer type. Ensure that we
10484 // sign extend the integer value if it is smaller as this is
10485 // used for address computation.
10486 Instruction::CastOps opcode =
10487 (VTySize < PtrSize ? Instruction::SExt :
10488 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10489 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010490}
10491
Chris Lattnera1be5662002-05-02 17:06:02 +000010492
Chris Lattner7e708292002-06-25 16:13:24 +000010493Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010494 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010495 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010496 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010497 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010498 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010499
Chris Lattnere87597f2004-10-16 18:11:37 +000010500 if (isa<UndefValue>(GEP.getOperand(0)))
10501 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10502
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010503 bool HasZeroPointerIndex = false;
10504 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10505 HasZeroPointerIndex = C->isNullValue();
10506
10507 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010508 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010509
Chris Lattner28977af2004-04-05 01:30:19 +000010510 // Eliminate unneeded casts for indices.
10511 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010512
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010513 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010514 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10515 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010516 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010517 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010518 if (CI->getOpcode() == Instruction::ZExt ||
10519 CI->getOpcode() == Instruction::SExt) {
10520 const Type *SrcTy = CI->getOperand(0)->getType();
10521 // We can eliminate a cast from i32 to i64 iff the target
10522 // is a 32-bit pointer target.
10523 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10524 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010525 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010526 }
10527 }
10528 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010529 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010530 // to what we need. If narrower, sign-extend it to what we need.
10531 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010532 // insert it. This explicit cast can make subsequent optimizations more
10533 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010534 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010535 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010536 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010537 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010538 MadeChange = true;
10539 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010540 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10541 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010542 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010543 MadeChange = true;
10544 }
Dan Gohman4f833d42008-09-11 23:06:38 +000010545 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10546 if (Constant *C = dyn_cast<Constant>(Op)) {
10547 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10548 MadeChange = true;
10549 } else {
10550 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10551 GEP);
10552 *i = Op;
10553 MadeChange = true;
10554 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010555 }
Chris Lattner28977af2004-04-05 01:30:19 +000010556 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010557 }
Chris Lattner28977af2004-04-05 01:30:19 +000010558 if (MadeChange) return &GEP;
10559
Chris Lattner90ac28c2002-08-02 19:29:35 +000010560 // Combine Indices - If the source pointer to this getelementptr instruction
10561 // is a getelementptr instruction, combine the indices of the two
10562 // getelementptr instructions into a single instruction.
10563 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010564 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010565 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010566 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010567
10568 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010569 // Note that if our source is a gep chain itself that we wait for that
10570 // chain to be resolved before we perform this transformation. This
10571 // avoids us creating a TON of code in some cases.
10572 //
10573 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10574 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10575 return 0; // Wait until our source is folded to completion.
10576
Chris Lattner72588fc2007-02-15 22:48:32 +000010577 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010578
10579 // Find out whether the last index in the source GEP is a sequential idx.
10580 bool EndsWithSequential = false;
10581 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10582 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010583 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010584
Chris Lattner90ac28c2002-08-02 19:29:35 +000010585 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010586 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010587 // Replace: gep (gep %P, long B), long A, ...
10588 // With: T = long A+B; gep %P, T, ...
10589 //
Chris Lattner620ce142004-05-07 22:09:22 +000010590 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010591 if (SO1 == Constant::getNullValue(SO1->getType())) {
10592 Sum = GO1;
10593 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10594 Sum = SO1;
10595 } else {
10596 // If they aren't the same type, convert both to an integer of the
10597 // target's pointer size.
10598 if (SO1->getType() != GO1->getType()) {
10599 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010600 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010601 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010602 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010603 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010604 unsigned PS = TD->getPointerSizeInBits();
10605 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010606 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010607 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010608
Duncan Sands514ab342007-11-01 20:53:16 +000010609 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010610 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010611 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010612 } else {
10613 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010614 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10615 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010616 }
10617 }
10618 }
Chris Lattner620ce142004-05-07 22:09:22 +000010619 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10620 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10621 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010622 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010623 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010624 }
Chris Lattner28977af2004-04-05 01:30:19 +000010625 }
Chris Lattner620ce142004-05-07 22:09:22 +000010626
10627 // Recycle the GEP we already have if possible.
10628 if (SrcGEPOperands.size() == 2) {
10629 GEP.setOperand(0, SrcGEPOperands[0]);
10630 GEP.setOperand(1, Sum);
10631 return &GEP;
10632 } else {
10633 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10634 SrcGEPOperands.end()-1);
10635 Indices.push_back(Sum);
10636 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10637 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010638 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010639 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010640 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010641 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010642 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10643 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010644 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10645 }
10646
10647 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010648 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10649 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010650
Chris Lattner620ce142004-05-07 22:09:22 +000010651 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010652 // GEP of global variable. If all of the indices for this GEP are
10653 // constants, we can promote this to a constexpr instead of an instruction.
10654
10655 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010656 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010657 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10658 for (; I != E && isa<Constant>(*I); ++I)
10659 Indices.push_back(cast<Constant>(*I));
10660
10661 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010662 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10663 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010664
10665 // Replace all uses of the GEP with the new constexpr...
10666 return ReplaceInstUsesWith(GEP, CE);
10667 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010668 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010669 if (!isa<PointerType>(X->getType())) {
10670 // Not interesting. Source pointer must be a cast from pointer.
10671 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010672 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10673 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010674 //
10675 // This occurs when the program declares an array extern like "int X[];"
10676 //
10677 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10678 const PointerType *XTy = cast<PointerType>(X->getType());
10679 if (const ArrayType *XATy =
10680 dyn_cast<ArrayType>(XTy->getElementType()))
10681 if (const ArrayType *CATy =
10682 dyn_cast<ArrayType>(CPTy->getElementType()))
10683 if (CATy->getElementType() == XATy->getElementType()) {
10684 // At this point, we know that the cast source type is a pointer
10685 // to an array of the same type as the destination pointer
10686 // array. Because the array type is never stepped over (there
10687 // is a leading zero) we can fold the cast into this GEP.
10688 GEP.setOperand(0, X);
10689 return &GEP;
10690 }
10691 } else if (GEP.getNumOperands() == 2) {
10692 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010693 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10694 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010695 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10696 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10697 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010698 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10699 TD->getTypePaddedSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010700 Value *Idx[2];
10701 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10702 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010703 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010704 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010705 // V and GEP are both pointer types --> BitCast
10706 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010707 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010708
10709 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010710 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010711 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010712 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010713
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010714 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010715 uint64_t ArrayEltSize =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010716 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010717
10718 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10719 // allow either a mul, shift, or constant here.
10720 Value *NewIdx = 0;
10721 ConstantInt *Scale = 0;
10722 if (ArrayEltSize == 1) {
10723 NewIdx = GEP.getOperand(1);
10724 Scale = ConstantInt::get(NewIdx->getType(), 1);
10725 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010726 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010727 Scale = CI;
10728 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10729 if (Inst->getOpcode() == Instruction::Shl &&
10730 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010731 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10732 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10733 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010734 NewIdx = Inst->getOperand(0);
10735 } else if (Inst->getOpcode() == Instruction::Mul &&
10736 isa<ConstantInt>(Inst->getOperand(1))) {
10737 Scale = cast<ConstantInt>(Inst->getOperand(1));
10738 NewIdx = Inst->getOperand(0);
10739 }
10740 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010741
Chris Lattner7835cdd2005-09-13 18:36:04 +000010742 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010743 // out, perform the transformation. Note, we don't know whether Scale is
10744 // signed or not. We'll use unsigned version of division/modulo
10745 // operation after making sure Scale doesn't have the sign bit set.
10746 if (Scale && Scale->getSExtValue() >= 0LL &&
10747 Scale->getZExtValue() % ArrayEltSize == 0) {
10748 Scale = ConstantInt::get(Scale->getType(),
10749 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010750 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010751 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010752 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010753 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010754 NewIdx = InsertNewInstBefore(Sc, GEP);
10755 }
10756
10757 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010758 Value *Idx[2];
10759 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10760 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010761 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010762 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010763 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10764 // The NewGEP must be pointer typed, so must the old one -> BitCast
10765 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010766 }
10767 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010768 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010769 }
Chris Lattner58407792009-01-09 04:53:57 +000010770
Chris Lattner46cd5a12009-01-09 05:44:56 +000010771 /// See if we can simplify:
10772 /// X = bitcast A to B*
10773 /// Y = gep X, <...constant indices...>
10774 /// into a gep of the original struct. This is important for SROA and alias
10775 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000010776 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000010777 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10778 // Determine how much the GEP moves the pointer. We are guaranteed to get
10779 // a constant back from EmitGEPOffset.
10780 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10781 int64_t Offset = OffsetV->getSExtValue();
10782
10783 // If this GEP instruction doesn't move the pointer, just replace the GEP
10784 // with a bitcast of the real input to the dest type.
10785 if (Offset == 0) {
10786 // If the bitcast is of an allocation, and the allocation will be
10787 // converted to match the type of the cast, don't touch this.
10788 if (isa<AllocationInst>(BCI->getOperand(0))) {
10789 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10790 if (Instruction *I = visitBitCast(*BCI)) {
10791 if (I != BCI) {
10792 I->takeName(BCI);
10793 BCI->getParent()->getInstList().insert(BCI, I);
10794 ReplaceInstUsesWith(*BCI, I);
10795 }
10796 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000010797 }
Chris Lattner58407792009-01-09 04:53:57 +000010798 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010799 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000010800 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010801
10802 // Otherwise, if the offset is non-zero, we need to find out if there is a
10803 // field at Offset in 'A's type. If so, we can pull the cast through the
10804 // GEP.
10805 SmallVector<Value*, 8> NewIndices;
10806 const Type *InTy =
10807 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10808 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10809 Instruction *NGEP =
10810 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10811 NewIndices.end());
10812 if (NGEP->getType() == GEP.getType()) return NGEP;
10813 InsertNewInstBefore(NGEP, GEP);
10814 NGEP->takeName(&GEP);
10815 return new BitCastInst(NGEP, GEP.getType());
10816 }
Chris Lattner58407792009-01-09 04:53:57 +000010817 }
10818 }
10819
Chris Lattner8a2a3112001-12-14 16:52:21 +000010820 return 0;
10821}
10822
Chris Lattner0864acf2002-11-04 16:18:53 +000010823Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10824 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010825 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010826 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10827 const Type *NewTy =
10828 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010829 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010830
10831 // Create and insert the replacement instruction...
10832 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010833 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010834 else {
10835 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010836 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010837 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010838
10839 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010840
Chris Lattner0864acf2002-11-04 16:18:53 +000010841 // Scan to the end of the allocation instructions, to skip over a block of
10842 // allocas if possible...
10843 //
10844 BasicBlock::iterator It = New;
10845 while (isa<AllocationInst>(*It)) ++It;
10846
10847 // Now that I is pointing to the first non-allocation-inst in the block,
10848 // insert our getelementptr instruction...
10849 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010850 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010851 Value *Idx[2];
10852 Idx[0] = NullIdx;
10853 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010854 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10855 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010856
10857 // Now make everything use the getelementptr instead of the original
10858 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010859 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010860 } else if (isa<UndefValue>(AI.getArraySize())) {
10861 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010862 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010863 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010864
Dan Gohman6893cd72009-01-13 20:18:38 +000010865 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10866 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10867 // Note that we only do this for alloca's, because malloc should allocate and
10868 // return a unique pointer, even for a zero byte allocation.
10869 if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10870 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10871
10872 // If the alignment is 0 (unspecified), assign it the preferred alignment.
10873 if (AI.getAlignment() == 0)
10874 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10875 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010876
Chris Lattner0864acf2002-11-04 16:18:53 +000010877 return 0;
10878}
10879
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010880Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10881 Value *Op = FI.getOperand(0);
10882
Chris Lattner17be6352004-10-18 02:59:09 +000010883 // free undef -> unreachable.
10884 if (isa<UndefValue>(Op)) {
10885 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010886 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010887 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010888 return EraseInstFromFunction(FI);
10889 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010890
Chris Lattner6160e852004-02-28 04:57:37 +000010891 // If we have 'free null' delete the instruction. This can happen in stl code
10892 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010893 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010894 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010895
10896 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10897 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10898 FI.setOperand(0, CI->getOperand(0));
10899 return &FI;
10900 }
10901
10902 // Change free (gep X, 0,0,0,0) into free(X)
10903 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10904 if (GEPI->hasAllZeroIndices()) {
10905 AddToWorkList(GEPI);
10906 FI.setOperand(0, GEPI->getOperand(0));
10907 return &FI;
10908 }
10909 }
10910
10911 // Change free(malloc) into nothing, if the malloc has a single use.
10912 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10913 if (MI->hasOneUse()) {
10914 EraseInstFromFunction(FI);
10915 return EraseInstFromFunction(*MI);
10916 }
Chris Lattner6160e852004-02-28 04:57:37 +000010917
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010918 return 0;
10919}
10920
10921
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010922/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010923static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010924 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010925 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010926 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010927
Devang Patel99db6ad2007-10-18 19:52:32 +000010928 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10929 // Instead of loading constant c string, use corresponding integer value
10930 // directly if string length is small enough.
Evan Cheng0ff39b32008-06-30 07:31:25 +000010931 std::string Str;
10932 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010933 unsigned len = Str.length();
10934 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10935 unsigned numBits = Ty->getPrimitiveSizeInBits();
10936 // Replace LI with immediate integer store.
10937 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010938 APInt StrVal(numBits, 0);
10939 APInt SingleChar(numBits, 0);
10940 if (TD->isLittleEndian()) {
10941 for (signed i = len-1; i >= 0; i--) {
10942 SingleChar = (uint64_t) Str[i];
10943 StrVal = (StrVal << 8) | SingleChar;
10944 }
10945 } else {
10946 for (unsigned i = 0; i < len; i++) {
10947 SingleChar = (uint64_t) Str[i];
10948 StrVal = (StrVal << 8) | SingleChar;
10949 }
10950 // Append NULL at the end.
10951 SingleChar = 0;
10952 StrVal = (StrVal << 8) | SingleChar;
10953 }
10954 Value *NL = ConstantInt::get(StrVal);
10955 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010956 }
10957 }
10958 }
10959
Chris Lattnerb89e0712004-07-13 01:49:43 +000010960 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010961 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010962 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010963
Reid Spencer42230162007-01-22 05:51:25 +000010964 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010965 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010966 // If the source is an array, the code below will not succeed. Check to
10967 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10968 // constants.
10969 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10970 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10971 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010972 Value *Idxs[2];
10973 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10974 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010975 SrcTy = cast<PointerType>(CastOp->getType());
10976 SrcPTy = SrcTy->getElementType();
10977 }
10978
Reid Spencer42230162007-01-22 05:51:25 +000010979 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010980 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010981 // Do not allow turning this into a load of an integer, which is then
10982 // casted to a pointer, this pessimizes pointer analysis a lot.
10983 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010984 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10985 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010986
Chris Lattnerf9527852005-01-31 04:50:46 +000010987 // Okay, we are casting from one integer or pointer type to another of
10988 // the same size. Instead of casting the pointer before the load, cast
10989 // the result of the loaded value.
10990 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10991 CI->getName(),
10992 LI.isVolatile()),LI);
10993 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010994 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010995 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010996 }
10997 }
10998 return 0;
10999}
11000
Chris Lattnerc10aced2004-09-19 18:43:46 +000011001/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000011002/// from this value cannot trap. If it is not obviously safe to load from the
11003/// specified pointer, we do a quick local scan of the basic block containing
11004/// ScanFrom, to determine if the address is already accessed.
11005static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000011006 // If it is an alloca it is always safe to load from.
11007 if (isa<AllocaInst>(V)) return true;
11008
Duncan Sands46318cd2007-09-19 10:25:38 +000011009 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000011010 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000011011 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000011012 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000011013
11014 // Otherwise, be a little bit agressive by scanning the local block where we
11015 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011016 // from/to. If so, the previous load or store would have already trapped,
11017 // so there is no harm doing an extra load (also, CSE will later eliminate
11018 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000011019 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11020
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011021 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000011022 --BBI;
11023
Chris Lattner2de3fec2008-06-20 05:12:56 +000011024 // If we see a free or a call (which might do a free) the pointer could be
11025 // marked invalid.
11026 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
11027 return false;
11028
Chris Lattner8a375202004-09-19 19:18:10 +000011029 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11030 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011031 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000011032 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011033 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011034
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011035 }
Chris Lattner8a375202004-09-19 19:18:10 +000011036 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000011037}
11038
Chris Lattner833b8a42003-06-26 05:06:25 +000011039Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11040 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011041
Dan Gohman9941f742007-07-20 16:34:21 +000011042 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000011043 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
11044 if (KnownAlign >
11045 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11046 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011047 LI.setAlignment(KnownAlign);
11048
Chris Lattner37366c12005-05-01 04:24:53 +000011049 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011050 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011051 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011052 return Res;
11053
11054 // None of the following transforms are legal for volatile loads.
11055 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011056
Dan Gohman2276a7b2008-10-15 23:19:35 +000011057 // Do really simple store-to-load forwarding and load CSE, to catch cases
11058 // where there are several consequtive memory accesses to the same location,
11059 // separated by a few arithmetic operations.
11060 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011061 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11062 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011063
Christopher Lambb15147e2007-12-29 07:56:53 +000011064 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11065 const Value *GEPI0 = GEPI->getOperand(0);
11066 // TODO: Consider a target hook for valid address spaces for this xform.
11067 if (isa<ConstantPointerNull>(GEPI0) &&
11068 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011069 // Insert a new store to null instruction before the load to indicate
11070 // that this code is not reachable. We do this instead of inserting
11071 // an unreachable instruction directly because we cannot modify the
11072 // CFG.
11073 new StoreInst(UndefValue::get(LI.getType()),
11074 Constant::getNullValue(Op->getType()), &LI);
11075 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11076 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011077 }
Chris Lattner37366c12005-05-01 04:24:53 +000011078
Chris Lattnere87597f2004-10-16 18:11:37 +000011079 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011080 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011081 // TODO: Consider a target hook for valid address spaces for this xform.
11082 if (isa<UndefValue>(C) || (C->isNullValue() &&
11083 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011084 // Insert a new store to null instruction before the load to indicate that
11085 // this code is not reachable. We do this instead of inserting an
11086 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000011087 new StoreInst(UndefValue::get(LI.getType()),
11088 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000011089 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011090 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011091
Chris Lattnere87597f2004-10-16 18:11:37 +000011092 // Instcombine load (constant global) into the value loaded.
11093 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000011094 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000011095 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011096
Chris Lattnere87597f2004-10-16 18:11:37 +000011097 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011098 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011099 if (CE->getOpcode() == Instruction::GetElementPtr) {
11100 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000011101 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000011102 if (Constant *V =
11103 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011104 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011105 if (CE->getOperand(0)->isNullValue()) {
11106 // Insert a new store to null instruction before the load to indicate
11107 // that this code is not reachable. We do this instead of inserting
11108 // an unreachable instruction directly because we cannot modify the
11109 // CFG.
11110 new StoreInst(UndefValue::get(LI.getType()),
11111 Constant::getNullValue(Op->getType()), &LI);
11112 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11113 }
11114
Reid Spencer3da59db2006-11-27 01:05:10 +000011115 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011116 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011117 return Res;
11118 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011119 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011120 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011121
11122 // If this load comes from anywhere in a constant global, and if the global
11123 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011124 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Chris Lattner8d2e8882007-08-11 18:48:48 +000011125 if (GV->isConstant() && GV->hasInitializer()) {
11126 if (GV->getInitializer()->isNullValue())
11127 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11128 else if (isa<UndefValue>(GV->getInitializer()))
11129 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11130 }
11131 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011132
Chris Lattner37366c12005-05-01 04:24:53 +000011133 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011134 // Change select and PHI nodes to select values instead of addresses: this
11135 // helps alias analysis out a lot, allows many others simplifications, and
11136 // exposes redundancy in the code.
11137 //
11138 // Note that we cannot do the transformation unless we know that the
11139 // introduced loads cannot trap! Something like this is valid as long as
11140 // the condition is always false: load (select bool %C, int* null, int* %G),
11141 // but it would not be valid if we transformed it to load from null
11142 // unconditionally.
11143 //
11144 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11145 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011146 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11147 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011148 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011149 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011150 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011151 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011152 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011153 }
11154
Chris Lattner684fe212004-09-23 15:46:00 +000011155 // load (select (cond, null, P)) -> load P
11156 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11157 if (C->isNullValue()) {
11158 LI.setOperand(0, SI->getOperand(2));
11159 return &LI;
11160 }
11161
11162 // load (select (cond, P, null)) -> load P
11163 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11164 if (C->isNullValue()) {
11165 LI.setOperand(0, SI->getOperand(1));
11166 return &LI;
11167 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011168 }
11169 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011170 return 0;
11171}
11172
Reid Spencer55af2b52007-01-19 21:20:31 +000011173/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011174/// when possible. This makes it generally easy to do alias analysis and/or
11175/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011176static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11177 User *CI = cast<User>(SI.getOperand(1));
11178 Value *CastOp = CI->getOperand(0);
11179
11180 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011181 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11182 if (SrcTy == 0) return 0;
11183
11184 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011185
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011186 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11187 return 0;
11188
Chris Lattner3914f722009-01-24 01:00:13 +000011189 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11190 /// to its first element. This allows us to handle things like:
11191 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11192 /// on 32-bit hosts.
11193 SmallVector<Value*, 4> NewGEPIndices;
11194
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011195 // If the source is an array, the code below will not succeed. Check to
11196 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11197 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011198 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11199 // Index through pointer.
11200 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11201 NewGEPIndices.push_back(Zero);
11202
11203 while (1) {
11204 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011205 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011206 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011207 NewGEPIndices.push_back(Zero);
11208 SrcPTy = STy->getElementType(0);
11209 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11210 NewGEPIndices.push_back(Zero);
11211 SrcPTy = ATy->getElementType();
11212 } else {
11213 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011214 }
Chris Lattner3914f722009-01-24 01:00:13 +000011215 }
11216
11217 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11218 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011219
11220 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11221 return 0;
11222
Chris Lattner71759c42009-01-16 20:12:52 +000011223 // If the pointers point into different address spaces or if they point to
11224 // values with different sizes, we can't do the transformation.
11225 if (SrcTy->getAddressSpace() !=
11226 cast<PointerType>(CI->getType())->getAddressSpace() ||
11227 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011228 IC.getTargetData().getTypeSizeInBits(DestPTy))
11229 return 0;
11230
11231 // Okay, we are casting from one integer or pointer type to another of
11232 // the same size. Instead of casting the pointer before
11233 // the store, cast the value to be stored.
11234 Value *NewCast;
11235 Value *SIOp0 = SI.getOperand(0);
11236 Instruction::CastOps opcode = Instruction::BitCast;
11237 const Type* CastSrcTy = SIOp0->getType();
11238 const Type* CastDstTy = SrcPTy;
11239 if (isa<PointerType>(CastDstTy)) {
11240 if (CastSrcTy->isInteger())
11241 opcode = Instruction::IntToPtr;
11242 } else if (isa<IntegerType>(CastDstTy)) {
11243 if (isa<PointerType>(SIOp0->getType()))
11244 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011245 }
Chris Lattner3914f722009-01-24 01:00:13 +000011246
11247 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11248 // emit a GEP to index into its first field.
11249 if (!NewGEPIndices.empty()) {
11250 if (Constant *C = dyn_cast<Constant>(CastOp))
11251 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11252 NewGEPIndices.size());
11253 else
11254 CastOp = IC.InsertNewInstBefore(
11255 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11256 NewGEPIndices.end()), SI);
11257 }
11258
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011259 if (Constant *C = dyn_cast<Constant>(SIOp0))
11260 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11261 else
11262 NewCast = IC.InsertNewInstBefore(
11263 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11264 SI);
11265 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011266}
11267
Chris Lattner4aebaee2008-11-27 08:56:30 +000011268/// equivalentAddressValues - Test if A and B will obviously have the same
11269/// value. This includes recognizing that %t0 and %t1 will have the same
11270/// value in code like this:
11271/// %t0 = getelementptr @a, 0, 3
11272/// store i32 0, i32* %t0
11273/// %t1 = getelementptr @a, 0, 3
11274/// %t2 = load i32* %t1
11275///
11276static bool equivalentAddressValues(Value *A, Value *B) {
11277 // Test if the values are trivially equivalent.
11278 if (A == B) return true;
11279
11280 // Test if the values come form identical arithmetic instructions.
11281 if (isa<BinaryOperator>(A) ||
11282 isa<CastInst>(A) ||
11283 isa<PHINode>(A) ||
11284 isa<GetElementPtrInst>(A))
11285 if (Instruction *BI = dyn_cast<Instruction>(B))
11286 if (cast<Instruction>(A)->isIdenticalTo(BI))
11287 return true;
11288
11289 // Otherwise they may not be equivalent.
11290 return false;
11291}
11292
Chris Lattner2f503e62005-01-31 05:36:43 +000011293Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11294 Value *Val = SI.getOperand(0);
11295 Value *Ptr = SI.getOperand(1);
11296
11297 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011298 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011299 ++NumCombined;
11300 return 0;
11301 }
Chris Lattner836692d2007-01-15 06:51:56 +000011302
11303 // If the RHS is an alloca with a single use, zapify the store, making the
11304 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000011305 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000011306 if (isa<AllocaInst>(Ptr)) {
11307 EraseInstFromFunction(SI);
11308 ++NumCombined;
11309 return 0;
11310 }
11311
11312 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11313 if (isa<AllocaInst>(GEP->getOperand(0)) &&
11314 GEP->getOperand(0)->hasOneUse()) {
11315 EraseInstFromFunction(SI);
11316 ++NumCombined;
11317 return 0;
11318 }
11319 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011320
Dan Gohman9941f742007-07-20 16:34:21 +000011321 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000011322 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11323 if (KnownAlign >
11324 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11325 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011326 SI.setAlignment(KnownAlign);
11327
Chris Lattner9ca96412006-02-08 03:25:32 +000011328 // Do really simple DSE, to catch cases where there are several consequtive
11329 // stores to the same location, separated by a few arithmetic operations. This
11330 // situation often occurs with bitfield accesses.
11331 BasicBlock::iterator BBI = &SI;
11332 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11333 --ScanInsts) {
11334 --BBI;
11335
11336 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11337 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011338 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11339 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011340 ++NumDeadStore;
11341 ++BBI;
11342 EraseInstFromFunction(*PrevSI);
11343 continue;
11344 }
11345 break;
11346 }
11347
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011348 // If this is a load, we have to stop. However, if the loaded value is from
11349 // the pointer we're loading and is producing the pointer we're storing,
11350 // then *this* store is dead (X = load P; store X -> P).
11351 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011352 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11353 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011354 EraseInstFromFunction(SI);
11355 ++NumCombined;
11356 return 0;
11357 }
11358 // Otherwise, this is a load from some other location. Stores before it
11359 // may not be dead.
11360 break;
11361 }
11362
Chris Lattner9ca96412006-02-08 03:25:32 +000011363 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011364 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011365 break;
11366 }
11367
11368
11369 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011370
11371 // store X, null -> turns into 'unreachable' in SimplifyCFG
11372 if (isa<ConstantPointerNull>(Ptr)) {
11373 if (!isa<UndefValue>(Val)) {
11374 SI.setOperand(0, UndefValue::get(Val->getType()));
11375 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011376 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011377 ++NumCombined;
11378 }
11379 return 0; // Do not modify these!
11380 }
11381
11382 // store undef, Ptr -> noop
11383 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011384 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011385 ++NumCombined;
11386 return 0;
11387 }
11388
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011389 // If the pointer destination is a cast, see if we can fold the cast into the
11390 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011391 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011392 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11393 return Res;
11394 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011395 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011396 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11397 return Res;
11398
Chris Lattner408902b2005-09-12 23:23:25 +000011399
11400 // If this store is the last instruction in the basic block, and if the block
11401 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000011402 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000011403 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011404 if (BI->isUnconditional())
11405 if (SimplifyStoreAtEndOfBlock(SI))
11406 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011407
Chris Lattner2f503e62005-01-31 05:36:43 +000011408 return 0;
11409}
11410
Chris Lattner3284d1f2007-04-15 00:07:55 +000011411/// SimplifyStoreAtEndOfBlock - Turn things like:
11412/// if () { *P = v1; } else { *P = v2 }
11413/// into a phi node with a store in the successor.
11414///
Chris Lattner31755a02007-04-15 01:02:18 +000011415/// Simplify things like:
11416/// *P = v1; if () { *P = v2; }
11417/// into a phi node with a store in the successor.
11418///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011419bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11420 BasicBlock *StoreBB = SI.getParent();
11421
11422 // Check to see if the successor block has exactly two incoming edges. If
11423 // so, see if the other predecessor contains a store to the same location.
11424 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011425 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011426
11427 // Determine whether Dest has exactly two predecessors and, if so, compute
11428 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011429 pred_iterator PI = pred_begin(DestBB);
11430 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011431 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011432 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011433 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011434 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011435 return false;
11436
11437 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011438 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011439 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011440 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011441 }
Chris Lattner31755a02007-04-15 01:02:18 +000011442 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011443 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011444
11445 // Bail out if all the relevant blocks aren't distinct (this can happen,
11446 // for example, if SI is in an infinite loop)
11447 if (StoreBB == DestBB || OtherBB == DestBB)
11448 return false;
11449
Chris Lattner31755a02007-04-15 01:02:18 +000011450 // Verify that the other block ends in a branch and is not otherwise empty.
11451 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011452 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011453 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011454 return false;
11455
Chris Lattner31755a02007-04-15 01:02:18 +000011456 // If the other block ends in an unconditional branch, check for the 'if then
11457 // else' case. there is an instruction before the branch.
11458 StoreInst *OtherStore = 0;
11459 if (OtherBr->isUnconditional()) {
11460 // If this isn't a store, or isn't a store to the same location, bail out.
11461 --BBI;
11462 OtherStore = dyn_cast<StoreInst>(BBI);
11463 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11464 return false;
11465 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011466 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011467 // destinations is StoreBB, then we have the if/then case.
11468 if (OtherBr->getSuccessor(0) != StoreBB &&
11469 OtherBr->getSuccessor(1) != StoreBB)
11470 return false;
11471
11472 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011473 // if/then triangle. See if there is a store to the same ptr as SI that
11474 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011475 for (;; --BBI) {
11476 // Check to see if we find the matching store.
11477 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11478 if (OtherStore->getOperand(1) != SI.getOperand(1))
11479 return false;
11480 break;
11481 }
Eli Friedman6903a242008-06-13 22:02:12 +000011482 // If we find something that may be using or overwriting the stored
11483 // value, or if we run out of instructions, we can't do the xform.
11484 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011485 BBI == OtherBB->begin())
11486 return false;
11487 }
11488
11489 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011490 // make sure nothing reads or overwrites the stored value in
11491 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011492 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11493 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011494 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011495 return false;
11496 }
11497 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011498
Chris Lattner31755a02007-04-15 01:02:18 +000011499 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011500 Value *MergedVal = OtherStore->getOperand(0);
11501 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011502 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011503 PN->reserveOperandSpace(2);
11504 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011505 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11506 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011507 }
11508
11509 // Advance to a place where it is safe to insert the new store and
11510 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011511 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011512 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11513 OtherStore->isVolatile()), *BBI);
11514
11515 // Nuke the old stores.
11516 EraseInstFromFunction(SI);
11517 EraseInstFromFunction(*OtherStore);
11518 ++NumCombined;
11519 return true;
11520}
11521
Chris Lattner2f503e62005-01-31 05:36:43 +000011522
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011523Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11524 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011525 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011526 BasicBlock *TrueDest;
11527 BasicBlock *FalseDest;
11528 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11529 !isa<Constant>(X)) {
11530 // Swap Destinations and condition...
11531 BI.setCondition(X);
11532 BI.setSuccessor(0, FalseDest);
11533 BI.setSuccessor(1, TrueDest);
11534 return &BI;
11535 }
11536
Reid Spencere4d87aa2006-12-23 06:05:41 +000011537 // Cannonicalize fcmp_one -> fcmp_oeq
11538 FCmpInst::Predicate FPred; Value *Y;
11539 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11540 TrueDest, FalseDest)))
11541 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11542 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11543 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011544 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011545 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11546 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011547 // Swap Destinations and condition...
11548 BI.setCondition(NewSCC);
11549 BI.setSuccessor(0, FalseDest);
11550 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011551 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011552 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011553 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011554 return &BI;
11555 }
11556
11557 // Cannonicalize icmp_ne -> icmp_eq
11558 ICmpInst::Predicate IPred;
11559 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11560 TrueDest, FalseDest)))
11561 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11562 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11563 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11564 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011565 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011566 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11567 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011568 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011569 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011570 BI.setSuccessor(0, FalseDest);
11571 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011572 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011573 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011574 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011575 return &BI;
11576 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011577
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011578 return 0;
11579}
Chris Lattner0864acf2002-11-04 16:18:53 +000011580
Chris Lattner46238a62004-07-03 00:26:11 +000011581Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11582 Value *Cond = SI.getCondition();
11583 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11584 if (I->getOpcode() == Instruction::Add)
11585 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11586 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11587 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011588 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011589 AddRHS));
11590 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011591 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011592 return &SI;
11593 }
11594 }
11595 return 0;
11596}
11597
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011598Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011599 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011600
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011601 if (!EV.hasIndices())
11602 return ReplaceInstUsesWith(EV, Agg);
11603
11604 if (Constant *C = dyn_cast<Constant>(Agg)) {
11605 if (isa<UndefValue>(C))
11606 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11607
11608 if (isa<ConstantAggregateZero>(C))
11609 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11610
11611 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11612 // Extract the element indexed by the first index out of the constant
11613 Value *V = C->getOperand(*EV.idx_begin());
11614 if (EV.getNumIndices() > 1)
11615 // Extract the remaining indices out of the constant indexed by the
11616 // first index
11617 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11618 else
11619 return ReplaceInstUsesWith(EV, V);
11620 }
11621 return 0; // Can't handle other constants
11622 }
11623 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11624 // We're extracting from an insertvalue instruction, compare the indices
11625 const unsigned *exti, *exte, *insi, *inse;
11626 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11627 exte = EV.idx_end(), inse = IV->idx_end();
11628 exti != exte && insi != inse;
11629 ++exti, ++insi) {
11630 if (*insi != *exti)
11631 // The insert and extract both reference distinctly different elements.
11632 // This means the extract is not influenced by the insert, and we can
11633 // replace the aggregate operand of the extract with the aggregate
11634 // operand of the insert. i.e., replace
11635 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11636 // %E = extractvalue { i32, { i32 } } %I, 0
11637 // with
11638 // %E = extractvalue { i32, { i32 } } %A, 0
11639 return ExtractValueInst::Create(IV->getAggregateOperand(),
11640 EV.idx_begin(), EV.idx_end());
11641 }
11642 if (exti == exte && insi == inse)
11643 // Both iterators are at the end: Index lists are identical. Replace
11644 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11645 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11646 // with "i32 42"
11647 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11648 if (exti == exte) {
11649 // The extract list is a prefix of the insert list. i.e. replace
11650 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11651 // %E = extractvalue { i32, { i32 } } %I, 1
11652 // with
11653 // %X = extractvalue { i32, { i32 } } %A, 1
11654 // %E = insertvalue { i32 } %X, i32 42, 0
11655 // by switching the order of the insert and extract (though the
11656 // insertvalue should be left in, since it may have other uses).
11657 Value *NewEV = InsertNewInstBefore(
11658 ExtractValueInst::Create(IV->getAggregateOperand(),
11659 EV.idx_begin(), EV.idx_end()),
11660 EV);
11661 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11662 insi, inse);
11663 }
11664 if (insi == inse)
11665 // The insert list is a prefix of the extract list
11666 // We can simply remove the common indices from the extract and make it
11667 // operate on the inserted value instead of the insertvalue result.
11668 // i.e., replace
11669 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11670 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11671 // with
11672 // %E extractvalue { i32 } { i32 42 }, 0
11673 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11674 exti, exte);
11675 }
11676 // Can't simplify extracts from other values. Note that nested extracts are
11677 // already simplified implicitely by the above (extract ( extract (insert) )
11678 // will be translated into extract ( insert ( extract ) ) first and then just
11679 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011680 return 0;
11681}
11682
Chris Lattner220b0cf2006-03-05 00:22:33 +000011683/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11684/// is to leave as a vector operation.
11685static bool CheapToScalarize(Value *V, bool isConstant) {
11686 if (isa<ConstantAggregateZero>(V))
11687 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011688 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011689 if (isConstant) return true;
11690 // If all elts are the same, we can extract.
11691 Constant *Op0 = C->getOperand(0);
11692 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11693 if (C->getOperand(i) != Op0)
11694 return false;
11695 return true;
11696 }
11697 Instruction *I = dyn_cast<Instruction>(V);
11698 if (!I) return false;
11699
11700 // Insert element gets simplified to the inserted element or is deleted if
11701 // this is constant idx extract element and its a constant idx insertelt.
11702 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11703 isa<ConstantInt>(I->getOperand(2)))
11704 return true;
11705 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11706 return true;
11707 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11708 if (BO->hasOneUse() &&
11709 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11710 CheapToScalarize(BO->getOperand(1), isConstant)))
11711 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011712 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11713 if (CI->hasOneUse() &&
11714 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11715 CheapToScalarize(CI->getOperand(1), isConstant)))
11716 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011717
11718 return false;
11719}
11720
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011721/// Read and decode a shufflevector mask.
11722///
11723/// It turns undef elements into values that are larger than the number of
11724/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011725static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11726 unsigned NElts = SVI->getType()->getNumElements();
11727 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11728 return std::vector<unsigned>(NElts, 0);
11729 if (isa<UndefValue>(SVI->getOperand(2)))
11730 return std::vector<unsigned>(NElts, 2*NElts);
11731
11732 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011733 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000011734 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11735 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000011736 Result.push_back(NElts*2); // undef -> 8
11737 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000011738 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011739 return Result;
11740}
11741
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011742/// FindScalarElement - Given a vector and an element number, see if the scalar
11743/// value is already around as a register, for example if it were inserted then
11744/// extracted from the vector.
11745static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011746 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11747 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011748 unsigned Width = PTy->getNumElements();
11749 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011750 return UndefValue::get(PTy->getElementType());
11751
11752 if (isa<UndefValue>(V))
11753 return UndefValue::get(PTy->getElementType());
11754 else if (isa<ConstantAggregateZero>(V))
11755 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011756 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011757 return CP->getOperand(EltNo);
11758 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11759 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011760 if (!isa<ConstantInt>(III->getOperand(2)))
11761 return 0;
11762 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011763
11764 // If this is an insert to the element we are looking for, return the
11765 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011766 if (EltNo == IIElt)
11767 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011768
11769 // Otherwise, the insertelement doesn't modify the value, recurse on its
11770 // vector input.
11771 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011772 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000011773 unsigned LHSWidth =
11774 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000011775 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000011776 if (InEl < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000011777 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000011778 else if (InEl < LHSWidth*2)
11779 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000011780 else
11781 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011782 }
11783
11784 // Otherwise, we don't know.
11785 return 0;
11786}
11787
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011788Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000011789 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011790 if (isa<UndefValue>(EI.getOperand(0)))
11791 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11792
Dan Gohman07a96762007-07-16 14:29:03 +000011793 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011794 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11795 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11796
Reid Spencer9d6565a2007-02-15 02:26:10 +000011797 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000011798 // If vector val is constant with all elements the same, replace EI with
11799 // that element. When the elements are not identical, we cannot replace yet
11800 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000011801 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011802 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011803 if (C->getOperand(i) != op0) {
11804 op0 = 0;
11805 break;
11806 }
11807 if (op0)
11808 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011809 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011810
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011811 // If extracting a specified index from the vector, see if we can recursively
11812 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011813 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011814 unsigned IndexVal = IdxC->getZExtValue();
11815 unsigned VectorWidth =
11816 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11817
11818 // If this is extracting an invalid index, turn this into undef, to avoid
11819 // crashing the code below.
11820 if (IndexVal >= VectorWidth)
11821 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11822
Chris Lattner867b99f2006-10-05 06:55:50 +000011823 // This instruction only demands the single element from the input vector.
11824 // If the input vector has a single use, simplify it based on this use
11825 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011826 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011827 uint64_t UndefElts;
11828 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011829 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011830 UndefElts)) {
11831 EI.setOperand(0, V);
11832 return &EI;
11833 }
11834 }
11835
Reid Spencerb83eb642006-10-20 07:07:24 +000011836 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011837 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011838
11839 // If the this extractelement is directly using a bitcast from a vector of
11840 // the same number of elements, see if we can find the source element from
11841 // it. In this case, we will end up needing to bitcast the scalars.
11842 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11843 if (const VectorType *VT =
11844 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11845 if (VT->getNumElements() == VectorWidth)
11846 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11847 return new BitCastInst(Elt, EI.getType());
11848 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011849 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011850
Chris Lattner73fa49d2006-05-25 22:53:38 +000011851 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011852 if (I->hasOneUse()) {
11853 // Push extractelement into predecessor operation if legal and
11854 // profitable to do so
11855 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011856 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11857 if (CheapToScalarize(BO, isConstantElt)) {
11858 ExtractElementInst *newEI0 =
11859 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11860 EI.getName()+".lhs");
11861 ExtractElementInst *newEI1 =
11862 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11863 EI.getName()+".rhs");
11864 InsertNewInstBefore(newEI0, EI);
11865 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011866 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011867 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011868 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011869 unsigned AS =
11870 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011871 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11872 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011873 GetElementPtrInst *GEP =
11874 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011875 InsertNewInstBefore(GEP, EI);
11876 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011877 }
11878 }
11879 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11880 // Extracting the inserted element?
11881 if (IE->getOperand(2) == EI.getOperand(1))
11882 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11883 // If the inserted and extracted elements are constants, they must not
11884 // be the same value, extract from the pre-inserted value instead.
11885 if (isa<Constant>(IE->getOperand(2)) &&
11886 isa<Constant>(EI.getOperand(1))) {
11887 AddUsesToWorkList(EI);
11888 EI.setOperand(0, IE->getOperand(0));
11889 return &EI;
11890 }
11891 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11892 // If this is extracting an element from a shufflevector, figure out where
11893 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011894 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11895 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011896 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000011897 unsigned LHSWidth =
11898 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11899
11900 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000011901 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000011902 else if (SrcIdx < LHSWidth*2) {
11903 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000011904 Src = SVI->getOperand(1);
11905 } else {
11906 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011907 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011908 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011909 }
11910 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011911 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011912 return 0;
11913}
11914
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011915/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11916/// elements from either LHS or RHS, return the shuffle mask and true.
11917/// Otherwise, return false.
11918static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11919 std::vector<Constant*> &Mask) {
11920 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11921 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011922 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011923
11924 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011925 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011926 return true;
11927 } else if (V == LHS) {
11928 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011929 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011930 return true;
11931 } else if (V == RHS) {
11932 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011933 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011934 return true;
11935 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11936 // If this is an insert of an extract from some other vector, include it.
11937 Value *VecOp = IEI->getOperand(0);
11938 Value *ScalarOp = IEI->getOperand(1);
11939 Value *IdxOp = IEI->getOperand(2);
11940
Chris Lattnerd929f062006-04-27 21:14:21 +000011941 if (!isa<ConstantInt>(IdxOp))
11942 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011943 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011944
11945 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11946 // Okay, we can handle this if the vector we are insertinting into is
11947 // transitively ok.
11948 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11949 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011950 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011951 return true;
11952 }
11953 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11954 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011955 EI->getOperand(0)->getType() == V->getType()) {
11956 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011957 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011958
11959 // This must be extracting from either LHS or RHS.
11960 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11961 // Okay, we can handle this if the vector we are insertinting into is
11962 // transitively ok.
11963 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11964 // If so, update the mask to reflect the inserted value.
11965 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011966 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011967 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011968 } else {
11969 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011970 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011971 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011972
11973 }
11974 return true;
11975 }
11976 }
11977 }
11978 }
11979 }
11980 // TODO: Handle shufflevector here!
11981
11982 return false;
11983}
11984
11985/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11986/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11987/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011988static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011989 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011990 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011991 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011992 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011993 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011994
11995 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011996 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011997 return V;
11998 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011999 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012000 return V;
12001 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12002 // If this is an insert of an extract from some other vector, include it.
12003 Value *VecOp = IEI->getOperand(0);
12004 Value *ScalarOp = IEI->getOperand(1);
12005 Value *IdxOp = IEI->getOperand(2);
12006
12007 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12008 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12009 EI->getOperand(0)->getType() == V->getType()) {
12010 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012011 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12012 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012013
12014 // Either the extracted from or inserted into vector must be RHSVec,
12015 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012016 if (EI->getOperand(0) == RHS || RHS == 0) {
12017 RHS = EI->getOperand(0);
12018 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012019 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012020 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012021 return V;
12022 }
12023
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012024 if (VecOp == RHS) {
12025 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000012026 // Everything but the extracted element is replaced with the RHS.
12027 for (unsigned i = 0; i != NumElts; ++i) {
12028 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012029 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012030 }
12031 return V;
12032 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012033
12034 // If this insertelement is a chain that comes from exactly these two
12035 // vectors, return the vector and the effective shuffle.
12036 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12037 return EI->getOperand(0);
12038
Chris Lattnerefb47352006-04-15 01:39:45 +000012039 }
12040 }
12041 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012042 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012043
12044 // Otherwise, can't do anything fancy. Return an identity vector.
12045 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012046 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012047 return V;
12048}
12049
12050Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12051 Value *VecOp = IE.getOperand(0);
12052 Value *ScalarOp = IE.getOperand(1);
12053 Value *IdxOp = IE.getOperand(2);
12054
Chris Lattner599ded12007-04-09 01:11:16 +000012055 // Inserting an undef or into an undefined place, remove this.
12056 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12057 ReplaceInstUsesWith(IE, VecOp);
12058
Chris Lattnerefb47352006-04-15 01:39:45 +000012059 // If the inserted element was extracted from some other vector, and if the
12060 // indexes are constant, try to turn this into a shufflevector operation.
12061 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12062 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12063 EI->getOperand(0)->getType() == IE.getType()) {
12064 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012065 unsigned ExtractedIdx =
12066 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012067 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012068
12069 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12070 return ReplaceInstUsesWith(IE, VecOp);
12071
12072 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12073 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12074
12075 // If we are extracting a value from a vector, then inserting it right
12076 // back into the same place, just use the input vector.
12077 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12078 return ReplaceInstUsesWith(IE, VecOp);
12079
12080 // We could theoretically do this for ANY input. However, doing so could
12081 // turn chains of insertelement instructions into a chain of shufflevector
12082 // instructions, and right now we do not merge shufflevectors. As such,
12083 // only do this in a situation where it is clear that there is benefit.
12084 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12085 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12086 // the values of VecOp, except then one read from EIOp0.
12087 // Build a new shuffle mask.
12088 std::vector<Constant*> Mask;
12089 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000012090 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012091 else {
12092 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000012093 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012094 NumVectorElts));
12095 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000012096 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012097 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000012098 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012099 }
12100
12101 // If this insertelement isn't used by some other insertelement, turn it
12102 // (and any insertelements it points to), into one big shuffle.
12103 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12104 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012105 Value *RHS = 0;
12106 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12107 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12108 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000012109 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012110 }
12111 }
12112 }
12113
12114 return 0;
12115}
12116
12117
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012118Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12119 Value *LHS = SVI.getOperand(0);
12120 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012121 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012122
12123 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012124
Chris Lattner867b99f2006-10-05 06:55:50 +000012125 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012126 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012127 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012128
12129 uint64_t UndefElts;
12130 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012131
12132 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12133 return 0;
12134
Dan Gohman488fbfc2008-09-09 18:11:14 +000012135 uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
12136 if (VWidth <= 64 &&
Dan Gohman3139ff82008-09-11 22:47:57 +000012137 SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12138 LHS = SVI.getOperand(0);
12139 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012140 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012141 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012142
Chris Lattner863bcff2006-05-25 23:48:38 +000012143 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12144 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12145 if (LHS == RHS || isa<UndefValue>(LHS)) {
12146 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012147 // shuffle(undef,undef,mask) -> undef.
12148 return ReplaceInstUsesWith(SVI, LHS);
12149 }
12150
Chris Lattner863bcff2006-05-25 23:48:38 +000012151 // Remap any references to RHS to use LHS.
12152 std::vector<Constant*> Elts;
12153 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012154 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012155 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012156 else {
12157 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012158 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012159 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000012160 Elts.push_back(UndefValue::get(Type::Int32Ty));
12161 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012162 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000012163 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12164 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012165 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012166 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012167 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012168 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000012169 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012170 LHS = SVI.getOperand(0);
12171 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012172 MadeChange = true;
12173 }
12174
Chris Lattner7b2e27922006-05-26 00:29:06 +000012175 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012176 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012177
Chris Lattner863bcff2006-05-25 23:48:38 +000012178 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12179 if (Mask[i] >= e*2) continue; // Ignore undef values.
12180 // Is this an identity shuffle of the LHS value?
12181 isLHSID &= (Mask[i] == i);
12182
12183 // Is this an identity shuffle of the RHS value?
12184 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012185 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012186
Chris Lattner863bcff2006-05-25 23:48:38 +000012187 // Eliminate identity shuffles.
12188 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12189 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012190
Chris Lattner7b2e27922006-05-26 00:29:06 +000012191 // If the LHS is a shufflevector itself, see if we can combine it with this
12192 // one without producing an unusual shuffle. Here we are really conservative:
12193 // we are absolutely afraid of producing a shuffle mask not in the input
12194 // program, because the code gen may not be smart enough to turn a merged
12195 // shuffle into two specific shuffles: it may produce worse code. As such,
12196 // we only merge two shuffles if the result is one of the two input shuffle
12197 // masks. In this case, merging the shuffles just removes one instruction,
12198 // which we know is safe. This is good for things like turning:
12199 // (splat(splat)) -> splat.
12200 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12201 if (isa<UndefValue>(RHS)) {
12202 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12203
12204 std::vector<unsigned> NewMask;
12205 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12206 if (Mask[i] >= 2*e)
12207 NewMask.push_back(2*e);
12208 else
12209 NewMask.push_back(LHSMask[Mask[i]]);
12210
12211 // If the result mask is equal to the src shuffle or this shuffle mask, do
12212 // the replacement.
12213 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012214 unsigned LHSInNElts =
12215 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012216 std::vector<Constant*> Elts;
12217 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012218 if (NewMask[i] >= LHSInNElts*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012219 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012220 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012221 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012222 }
12223 }
12224 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12225 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000012226 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012227 }
12228 }
12229 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012230
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012231 return MadeChange ? &SVI : 0;
12232}
12233
12234
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012235
Chris Lattnerea1c4542004-12-08 23:43:58 +000012236
12237/// TryToSinkInstruction - Try to move the specified instruction from its
12238/// current block into the beginning of DestBlock, which can only happen if it's
12239/// safe to move the instruction past all of the instructions between it and the
12240/// end of its block.
12241static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12242 assert(I->hasOneUse() && "Invariants didn't hold!");
12243
Chris Lattner108e9022005-10-27 17:13:11 +000012244 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012245 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12246 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012247
Chris Lattnerea1c4542004-12-08 23:43:58 +000012248 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012249 if (isa<AllocaInst>(I) && I->getParent() ==
12250 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012251 return false;
12252
Chris Lattner96a52a62004-12-09 07:14:34 +000012253 // We can only sink load instructions if there is nothing between the load and
12254 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012255 if (I->mayReadFromMemory()) {
12256 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012257 Scan != E; ++Scan)
12258 if (Scan->mayWriteToMemory())
12259 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012260 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012261
Dan Gohman02dea8b2008-05-23 21:05:58 +000012262 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012263
Chris Lattner4bc5f802005-08-08 19:11:57 +000012264 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012265 ++NumSunkInst;
12266 return true;
12267}
12268
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012269
12270/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12271/// all reachable code to the worklist.
12272///
12273/// This has a couple of tricks to make the code faster and more powerful. In
12274/// particular, we constant fold and DCE instructions as we go, to avoid adding
12275/// them to the worklist (this significantly speeds up instcombine on code where
12276/// many instructions are dead or constant). Additionally, if we find a branch
12277/// whose condition is a known constant, we only visit the reachable successors.
12278///
12279static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012280 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012281 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012282 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012283 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012284 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012285
Chris Lattner2c7718a2007-03-23 19:17:18 +000012286 while (!Worklist.empty()) {
12287 BB = Worklist.back();
12288 Worklist.pop_back();
12289
12290 // We have now visited this block! If we've already been here, ignore it.
12291 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012292
12293 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012294 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12295 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012296
Chris Lattner2c7718a2007-03-23 19:17:18 +000012297 // DCE instruction if trivially dead.
12298 if (isInstructionTriviallyDead(Inst)) {
12299 ++NumDeadInst;
12300 DOUT << "IC: DCE: " << *Inst;
12301 Inst->eraseFromParent();
12302 continue;
12303 }
12304
12305 // ConstantProp instruction if trivially constant.
12306 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12307 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12308 Inst->replaceAllUsesWith(C);
12309 ++NumConstProp;
12310 Inst->eraseFromParent();
12311 continue;
12312 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012313
Devang Patel7fe1dec2008-11-19 18:56:50 +000012314 // If there are two consecutive llvm.dbg.stoppoint calls then
12315 // it is likely that the optimizer deleted code in between these
12316 // two intrinsics.
12317 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12318 if (DBI_Next) {
12319 if (DBI_Prev
12320 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12321 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12322 IC.RemoveFromWorkList(DBI_Prev);
12323 DBI_Prev->eraseFromParent();
12324 }
12325 DBI_Prev = DBI_Next;
12326 }
12327
Chris Lattner2c7718a2007-03-23 19:17:18 +000012328 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012329 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012330
12331 // Recursively visit successors. If this is a branch or switch on a
12332 // constant, only visit the reachable successor.
12333 TerminatorInst *TI = BB->getTerminator();
12334 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12335 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12336 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012337 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012338 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012339 continue;
12340 }
12341 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12342 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12343 // See if this is an explicit destination.
12344 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12345 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012346 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012347 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012348 continue;
12349 }
12350
12351 // Otherwise it is the default destination.
12352 Worklist.push_back(SI->getSuccessor(0));
12353 continue;
12354 }
12355 }
12356
12357 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12358 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012359 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012360}
12361
Chris Lattnerec9c3582007-03-03 02:04:50 +000012362bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012363 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012364 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012365
12366 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12367 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012368
Chris Lattnerb3d59702005-07-07 20:40:38 +000012369 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012370 // Do a depth-first traversal of the function, populate the worklist with
12371 // the reachable instructions. Ignore blocks that are not reachable. Keep
12372 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012373 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012374 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012375
Chris Lattnerb3d59702005-07-07 20:40:38 +000012376 // Do a quick scan over the function. If we find any blocks that are
12377 // unreachable, remove any instructions inside of them. This prevents
12378 // the instcombine code from having to deal with some bad special cases.
12379 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12380 if (!Visited.count(BB)) {
12381 Instruction *Term = BB->getTerminator();
12382 while (Term != BB->begin()) { // Remove instrs bottom-up
12383 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012384
Bill Wendlingb7427032006-11-26 09:46:52 +000012385 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000012386 ++NumDeadInst;
12387
12388 if (!I->use_empty())
12389 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12390 I->eraseFromParent();
Chris Lattner1e19d602009-01-31 07:04:22 +000012391 Changed = true;
Chris Lattnerb3d59702005-07-07 20:40:38 +000012392 }
12393 }
12394 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012395
Chris Lattnerdbab3862007-03-02 21:28:56 +000012396 while (!Worklist.empty()) {
12397 Instruction *I = RemoveOneFromWorkList();
12398 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012399
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012400 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012401 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012402 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012403 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012404 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012405 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012406
Bill Wendlingb7427032006-11-26 09:46:52 +000012407 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012408
12409 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012410 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012411 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012412 continue;
12413 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012414
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012415 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000012416 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012417 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012418
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012419 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012420 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012421 ReplaceInstUsesWith(*I, C);
12422
Chris Lattner62b14df2002-09-02 04:59:56 +000012423 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012424 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012425 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012426 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012427 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012428 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012429
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012430 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12431 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012432 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12433 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012434 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012435 if (NewC != CE) {
12436 i->set(NewC);
12437 Changed = true;
12438 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012439 }
12440
Chris Lattnerea1c4542004-12-08 23:43:58 +000012441 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012442 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012443 BasicBlock *BB = I->getParent();
12444 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12445 if (UserParent != BB) {
12446 bool UserIsSuccessor = false;
12447 // See if the user is one of our successors.
12448 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12449 if (*SI == UserParent) {
12450 UserIsSuccessor = true;
12451 break;
12452 }
12453
12454 // If the user is one of our immediate successors, and if that successor
12455 // only has us as a predecessors (we'd have to split the critical edge
12456 // otherwise), we can keep going.
12457 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12458 next(pred_begin(UserParent)) == pred_end(UserParent))
12459 // Okay, the CFG is simple enough, try to sink this instruction.
12460 Changed |= TryToSinkInstruction(I, UserParent);
12461 }
12462 }
12463
Chris Lattner8a2a3112001-12-14 16:52:21 +000012464 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012465#ifndef NDEBUG
12466 std::string OrigI;
12467#endif
12468 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012469 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012470 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012471 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012472 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012473 DOUT << "IC: Old = " << *I
12474 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000012475
Chris Lattnerf523d062004-06-09 05:08:07 +000012476 // Everything uses the new instruction now.
12477 I->replaceAllUsesWith(Result);
12478
12479 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012480 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000012481 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012482
Chris Lattner6934a042007-02-11 01:23:03 +000012483 // Move the name to the new instruction first.
12484 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012485
12486 // Insert the new instruction into the basic block...
12487 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012488 BasicBlock::iterator InsertPos = I;
12489
12490 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12491 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12492 ++InsertPos;
12493
12494 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012495
Chris Lattner00d51312004-05-01 23:27:23 +000012496 // Make sure that we reprocess all operands now that we reduced their
12497 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012498 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000012499
Chris Lattnerf523d062004-06-09 05:08:07 +000012500 // Instructions can end up on the worklist more than once. Make sure
12501 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012502 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012503
12504 // Erase the old instruction.
12505 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000012506 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012507#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000012508 DOUT << "IC: Mod = " << OrigI
12509 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000012510#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012511
Chris Lattner90ac28c2002-08-02 19:29:35 +000012512 // If the instruction was modified, it's possible that it is now dead.
12513 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012514 if (isInstructionTriviallyDead(I)) {
12515 // Make sure we process all operands now that we are reducing their
12516 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000012517 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012518
Chris Lattner00d51312004-05-01 23:27:23 +000012519 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012520 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012521 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000012522 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000012523 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000012524 AddToWorkList(I);
12525 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012526 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012527 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012528 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012529 }
12530 }
12531
Chris Lattnerec9c3582007-03-03 02:04:50 +000012532 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000012533
12534 // Do an explicit clear, this shrinks the map if needed.
12535 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012536 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012537}
12538
Chris Lattnerec9c3582007-03-03 02:04:50 +000012539
12540bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012541 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12542
Chris Lattnerec9c3582007-03-03 02:04:50 +000012543 bool EverMadeChange = false;
12544
12545 // Iterate while there is work to do.
12546 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012547 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012548 EverMadeChange = true;
12549 return EverMadeChange;
12550}
12551
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012552FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012553 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012554}