blob: 16e5ce07c349389dd2bcfbb92b71986fff81e8c7 [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);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000170 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000171 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000172 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000173 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000174 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000175 Instruction *visitURem(BinaryOperator &I);
176 Instruction *visitSRem(BinaryOperator &I);
177 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000178 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000179 Instruction *commonRemTransforms(BinaryOperator &I);
180 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000181 Instruction *commonDivTransforms(BinaryOperator &I);
182 Instruction *commonIDivTransforms(BinaryOperator &I);
183 Instruction *visitUDiv(BinaryOperator &I);
184 Instruction *visitSDiv(BinaryOperator &I);
185 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000186 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000187 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000188 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000189 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000190 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000191 Instruction *visitOr (BinaryOperator &I);
192 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000193 Instruction *visitShl(BinaryOperator &I);
194 Instruction *visitAShr(BinaryOperator &I);
195 Instruction *visitLShr(BinaryOperator &I);
196 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000197 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
198 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000199 Instruction *visitFCmpInst(FCmpInst &I);
200 Instruction *visitICmpInst(ICmpInst &I);
201 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000202 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
203 Instruction *LHS,
204 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000205 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
206 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000207
Reid Spencere4d87aa2006-12-23 06:05:41 +0000208 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
209 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000210 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000211 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000212 Instruction *commonCastTransforms(CastInst &CI);
213 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000214 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000215 Instruction *visitTrunc(TruncInst &CI);
216 Instruction *visitZExt(ZExtInst &CI);
217 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000218 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000219 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000220 Instruction *visitFPToUI(FPToUIInst &FI);
221 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000222 Instruction *visitUIToFP(CastInst &CI);
223 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000224 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000225 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000226 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000227 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
228 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000229 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000230 Instruction *visitSelectInst(SelectInst &SI);
231 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000232 Instruction *visitCallInst(CallInst &CI);
233 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000234 Instruction *visitPHINode(PHINode &PN);
235 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000236 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000237 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000238 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000239 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000240 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000241 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000242 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000243 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000244 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000245 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000246
247 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000248 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000249
Chris Lattner9fe38862003-06-19 17:00:31 +0000250 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000251 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000252 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000253 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000254 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
255 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000256 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000257 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
258
Chris Lattner9fe38862003-06-19 17:00:31 +0000259
Chris Lattner28977af2004-04-05 01:30:19 +0000260 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000261 // InsertNewInstBefore - insert an instruction New before instruction Old
262 // in the program. Add the new instruction to the worklist.
263 //
Chris Lattner955f3312004-09-28 21:48:02 +0000264 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000265 assert(New && New->getParent() == 0 &&
266 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000267 BasicBlock *BB = Old.getParent();
268 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000269 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000270 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000271 }
272
Chris Lattner0c967662004-09-24 15:21:34 +0000273 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
274 /// This also adds the cast to the worklist. Finally, this returns the
275 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000276 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
277 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000278 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000279
Chris Lattnere2ed0572006-04-06 19:19:17 +0000280 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000281 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000282
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000283 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000284 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000285 return C;
286 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000287
288 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
289 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
290 }
291
Chris Lattner0c967662004-09-24 15:21:34 +0000292
Chris Lattner8b170942002-08-09 23:47:40 +0000293 // ReplaceInstUsesWith - This method is to be used when an instruction is
294 // found to be dead, replacable with another preexisting expression. Here
295 // we add all uses of I to the worklist, replace all uses of I with the new
296 // value, then return I, so that the inst combiner will know that I was
297 // modified.
298 //
299 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000300 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000301 if (&I != V) {
302 I.replaceAllUsesWith(V);
303 return &I;
304 } else {
305 // If we are replacing the instruction with itself, this must be in a
306 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000307 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000308 return &I;
309 }
Chris Lattner8b170942002-08-09 23:47:40 +0000310 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000311
312 // EraseInstFromFunction - When dealing with an instruction that has side
313 // effects or produces a void value, we can't rely on DCE to delete the
314 // instruction. Instead, visit methods should return the value returned by
315 // this function.
316 Instruction *EraseInstFromFunction(Instruction &I) {
317 assert(I.use_empty() && "Cannot erase instruction that is used!");
318 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000319 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000320 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000321 return 0; // Don't do anything with FI
322 }
Chris Lattner173234a2008-06-02 01:18:21 +0000323
324 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
325 APInt &KnownOne, unsigned Depth = 0) const {
326 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
327 }
328
329 bool MaskedValueIsZero(Value *V, const APInt &Mask,
330 unsigned Depth = 0) const {
331 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
332 }
333 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
334 return llvm::ComputeNumSignBits(Op, TD, Depth);
335 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000336
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000337 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000338
Reid Spencere4d87aa2006-12-23 06:05:41 +0000339 /// SimplifyCommutative - This performs a few simplifications for
340 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000341 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000342
Reid Spencere4d87aa2006-12-23 06:05:41 +0000343 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
344 /// most-complex to least-complex order.
345 bool SimplifyCompare(CmpInst &I);
346
Chris Lattner886ab6c2009-01-31 08:15:18 +0000347 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
348 /// based on the demanded bits.
349 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
350 APInt& KnownZero, APInt& KnownOne,
351 unsigned Depth);
352 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000353 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000354 unsigned Depth=0);
355
356 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
357 /// SimplifyDemandedBits knows about. See if the instruction has any
358 /// properties that allow us to simplify its operands.
359 bool SimplifyDemandedInstructionBits(Instruction &Inst);
360
Evan Cheng388df622009-02-03 10:05:09 +0000361 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
362 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000363
Chris Lattner4e998b22004-09-29 05:07:12 +0000364 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
365 // PHI node as operand #0, see if we can fold the instruction into the PHI
366 // (which is only possible if all operands to the PHI are constants).
367 Instruction *FoldOpIntoPhi(Instruction &I);
368
Chris Lattnerbac32862004-11-14 19:13:23 +0000369 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
370 // operator and they all are only used by the PHI, PHI together their
371 // inputs, and do the operation once, to the result of the PHI.
372 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000373 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000374 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
375
Chris Lattner7da52b22006-11-01 04:51:18 +0000376
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000377 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
378 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000379
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000380 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000381 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000382 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000383 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000384 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000385 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000386 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000387 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000388 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000389
Chris Lattnerafe91a52006-06-15 19:07:26 +0000390
Reid Spencerc55b2432006-12-13 18:21:21 +0000391 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000392
Dan Gohman6de29f82009-06-15 22:12:54 +0000393 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000394 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000395 unsigned GetOrEnforceKnownAlignment(Value *V,
396 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000397
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000398 };
399}
400
Dan Gohman844731a2008-05-13 00:00:25 +0000401char InstCombiner::ID = 0;
402static RegisterPass<InstCombiner>
403X("instcombine", "Combine redundant instructions");
404
Chris Lattner4f98c562003-03-10 21:43:22 +0000405// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000406// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000407static unsigned getComplexity(Value *V) {
408 if (isa<Instruction>(V)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000409 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
410 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000411 return 3;
412 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000413 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000414 if (isa<Argument>(V)) return 3;
415 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000416}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000417
Chris Lattnerc8802d22003-03-11 00:12:48 +0000418// isOnlyUse - Return true if this instruction will be deleted if we stop using
419// it.
420static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000421 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000422}
423
Chris Lattner4cb170c2004-02-23 06:38:22 +0000424// getPromotedType - Return the specified type promoted as it would be to pass
425// though a va_arg area...
426static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000427 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
428 if (ITy->getBitWidth() < 32)
429 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000430 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000431 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000432}
433
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000434/// getBitCastOperand - If the specified operand is a CastInst, a constant
435/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
436/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000437static Value *getBitCastOperand(Value *V) {
438 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000439 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000440 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000441 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
442 // GetElementPtrInst?
443 if (GEP->hasAllZeroIndices())
444 return GEP->getOperand(0);
445 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000446 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000447 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000448 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000449 else if (CE->getOpcode() == Instruction::GetElementPtr) {
450 // GetElementPtr ConstantExp?
451 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
452 I != E; ++I) {
453 ConstantInt *CI = dyn_cast<ConstantInt>(I);
454 if (!CI || !CI->isZero())
455 // Any non-zero indices? Not cast-like.
456 return 0;
457 }
458 // All-zero indices? This is just like casting.
459 return CE->getOperand(0);
460 }
461 }
Chris Lattnereed48272005-09-13 00:40:14 +0000462 return 0;
463}
464
Reid Spencer3da59db2006-11-27 01:05:10 +0000465/// This function is a wrapper around CastInst::isEliminableCastPair. It
466/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000467static Instruction::CastOps
468isEliminableCastPair(
469 const CastInst *CI, ///< The first cast instruction
470 unsigned opcode, ///< The opcode of the second cast instruction
471 const Type *DstTy, ///< The target type for the second cast instruction
472 TargetData *TD ///< The target data for pointer size
473) {
474
475 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
476 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000477
Reid Spencer3da59db2006-11-27 01:05:10 +0000478 // Get the opcodes of the two Cast instructions
479 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
480 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000481
Chris Lattnera0e69692009-03-24 18:35:40 +0000482 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
483 DstTy, TD->getIntPtrType());
484
485 // We don't want to form an inttoptr or ptrtoint that converts to an integer
486 // type that differs from the pointer size.
487 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
488 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
489 Res = 0;
490
491 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000492}
493
494/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
495/// in any code being generated. It does not require codegen if V is simple
496/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000497static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
498 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000499 if (V->getType() == Ty || isa<Constant>(V)) return false;
500
Chris Lattner01575b72006-05-25 23:24:33 +0000501 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000502 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000503 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000504 return false;
505 return true;
506}
507
Chris Lattner4f98c562003-03-10 21:43:22 +0000508// SimplifyCommutative - This performs a few simplifications for commutative
509// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000510//
Chris Lattner4f98c562003-03-10 21:43:22 +0000511// 1. Order operands such that they are listed from right (least complex) to
512// left (most complex). This puts constants before unary operators before
513// binary operators.
514//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000515// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
516// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000517//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000518bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000519 bool Changed = false;
520 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
521 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000522
Chris Lattner4f98c562003-03-10 21:43:22 +0000523 if (!I.isAssociative()) return Changed;
524 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000525 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
526 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
527 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000528 Constant *Folded = ConstantExpr::get(I.getOpcode(),
529 cast<Constant>(I.getOperand(1)),
530 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000531 I.setOperand(0, Op->getOperand(0));
532 I.setOperand(1, Folded);
533 return true;
534 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
535 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
536 isOnlyUse(Op) && isOnlyUse(Op1)) {
537 Constant *C1 = cast<Constant>(Op->getOperand(1));
538 Constant *C2 = cast<Constant>(Op1->getOperand(1));
539
540 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000541 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000542 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000543 Op1->getOperand(0),
544 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000545 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000546 I.setOperand(0, New);
547 I.setOperand(1, Folded);
548 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000549 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000550 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000551 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000552}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000553
Reid Spencere4d87aa2006-12-23 06:05:41 +0000554/// SimplifyCompare - For a CmpInst this function just orders the operands
555/// so that theyare listed from right (least complex) to left (most complex).
556/// This puts constants before unary operators before binary operators.
557bool InstCombiner::SimplifyCompare(CmpInst &I) {
558 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
559 return false;
560 I.swapOperands();
561 // Compare instructions are not associative so there's nothing else we can do.
562 return true;
563}
564
Chris Lattner8d969642003-03-10 23:06:50 +0000565// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
566// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000567//
Chris Lattner8d969642003-03-10 23:06:50 +0000568static inline Value *dyn_castNegVal(Value *V) {
569 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000570 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000571
Chris Lattner0ce85802004-12-14 20:08:06 +0000572 // Constants can be considered to be negated values if they can be folded.
573 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
574 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000575
576 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
577 if (C->getType()->getElementType()->isInteger())
578 return ConstantExpr::getNeg(C);
579
Chris Lattner8d969642003-03-10 23:06:50 +0000580 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000581}
582
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000583// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
584// instruction if the LHS is a constant negative zero (which is the 'negate'
585// form).
586//
587static inline Value *dyn_castFNegVal(Value *V) {
588 if (BinaryOperator::isFNeg(V))
589 return BinaryOperator::getFNegArgument(V);
590
591 // Constants can be considered to be negated values if they can be folded.
592 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
593 return ConstantExpr::getFNeg(C);
594
595 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
596 if (C->getType()->getElementType()->isFloatingPoint())
597 return ConstantExpr::getFNeg(C);
598
599 return 0;
600}
601
Chris Lattner8d969642003-03-10 23:06:50 +0000602static inline Value *dyn_castNotVal(Value *V) {
603 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000604 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000605
606 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000607 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000608 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000609 return 0;
610}
611
Chris Lattnerc8802d22003-03-11 00:12:48 +0000612// dyn_castFoldableMul - If this value is a multiply that can be folded into
613// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000614// non-constant operand of the multiply, and set CST to point to the multiplier.
615// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000616//
Chris Lattner50af16a2004-11-13 19:50:12 +0000617static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000618 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000619 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000620 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000621 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000622 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000623 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000624 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000625 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000626 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000627 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000628 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000629 return I->getOperand(0);
630 }
631 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000632 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000633}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000634
Chris Lattner574da9b2005-01-13 20:14:25 +0000635/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
636/// expression, return it.
637static User *dyn_castGetElementPtr(Value *V) {
638 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
639 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
640 if (CE->getOpcode() == Instruction::GetElementPtr)
641 return cast<User>(V);
642 return false;
643}
644
Dan Gohmaneee962e2008-04-10 18:43:06 +0000645/// getOpcode - If this is an Instruction or a ConstantExpr, return the
646/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000647static unsigned getOpcode(const Value *V) {
648 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000649 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000650 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000651 return CE->getOpcode();
652 // Use UserOp1 to mean there's no opcode.
653 return Instruction::UserOp1;
654}
655
Reid Spencer7177c3a2007-03-25 05:33:51 +0000656/// AddOne - Add one to a ConstantInt
Dan Gohman6de29f82009-06-15 22:12:54 +0000657static Constant *AddOne(Constant *C) {
658 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000659}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000660/// SubOne - Subtract one from a ConstantInt
Dan Gohman6de29f82009-06-15 22:12:54 +0000661static Constant *SubOne(ConstantInt *C) {
662 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000663}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000664/// MultiplyOverflows - True if the multiply can not be expressed in an int
665/// this size.
666static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
667 uint32_t W = C1->getBitWidth();
668 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
669 if (sign) {
670 LHSExt.sext(W * 2);
671 RHSExt.sext(W * 2);
672 } else {
673 LHSExt.zext(W * 2);
674 RHSExt.zext(W * 2);
675 }
676
677 APInt MulExt = LHSExt * RHSExt;
678
679 if (sign) {
680 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
681 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
682 return MulExt.slt(Min) || MulExt.sgt(Max);
683 } else
684 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
685}
Chris Lattner955f3312004-09-28 21:48:02 +0000686
Reid Spencere7816b52007-03-08 01:52:58 +0000687
Chris Lattner255d8912006-02-11 09:31:47 +0000688/// ShrinkDemandedConstant - Check to see if the specified operand of the
689/// specified instruction is a constant integer. If so, check to see if there
690/// are any bits set in the constant that are not demanded. If so, shrink the
691/// constant and return true.
692static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000693 APInt Demanded) {
694 assert(I && "No instruction?");
695 assert(OpNo < I->getNumOperands() && "Operand index too large");
696
697 // If the operand is not a constant integer, nothing to do.
698 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
699 if (!OpC) return false;
700
701 // If there are no bits set that aren't demanded, nothing to do.
702 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
703 if ((~Demanded & OpC->getValue()) == 0)
704 return false;
705
706 // This instruction is producing bits that are not demanded. Shrink the RHS.
707 Demanded &= OpC->getValue();
708 I->setOperand(OpNo, ConstantInt::get(Demanded));
709 return true;
710}
711
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000712// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
713// set of known zero and one bits, compute the maximum and minimum values that
714// could have the specified known zero and known one bits, returning them in
715// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000716static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000717 const APInt& KnownOne,
718 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000719 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
720 KnownZero.getBitWidth() == Min.getBitWidth() &&
721 KnownZero.getBitWidth() == Max.getBitWidth() &&
722 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000723 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000724
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000725 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
726 // bit if it is unknown.
727 Min = KnownOne;
728 Max = KnownOne|UnknownBits;
729
Dan Gohman1c8491e2009-04-25 17:12:48 +0000730 if (UnknownBits.isNegative()) { // Sign bit is unknown
731 Min.set(Min.getBitWidth()-1);
732 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000733 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000734}
735
736// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
737// a set of known zero and one bits, compute the maximum and minimum values that
738// could have the specified known zero and known one bits, returning them in
739// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000740static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000741 const APInt &KnownOne,
742 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000743 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
744 KnownZero.getBitWidth() == Min.getBitWidth() &&
745 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000746 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000747 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000748
749 // The minimum value is when the unknown bits are all zeros.
750 Min = KnownOne;
751 // The maximum value is when the unknown bits are all ones.
752 Max = KnownOne|UnknownBits;
753}
Chris Lattner255d8912006-02-11 09:31:47 +0000754
Chris Lattner886ab6c2009-01-31 08:15:18 +0000755/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
756/// SimplifyDemandedBits knows about. See if the instruction has any
757/// properties that allow us to simplify its operands.
758bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000759 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000760 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
761 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
762
763 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
764 KnownZero, KnownOne, 0);
765 if (V == 0) return false;
766 if (V == &Inst) return true;
767 ReplaceInstUsesWith(Inst, V);
768 return true;
769}
770
771/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
772/// specified instruction operand if possible, updating it in place. It returns
773/// true if it made any change and false otherwise.
774bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
775 APInt &KnownZero, APInt &KnownOne,
776 unsigned Depth) {
777 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
778 KnownZero, KnownOne, Depth);
779 if (NewVal == 0) return false;
780 U.set(NewVal);
781 return true;
782}
783
784
785/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
786/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000787/// that only the bits set in DemandedMask of the result of V are ever used
788/// downstream. Consequently, depending on the mask and V, it may be possible
789/// to replace V with a constant or one of its operands. In such cases, this
790/// function does the replacement and returns true. In all other cases, it
791/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000792/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000793/// to be zero in the expression. These are provided to potentially allow the
794/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
795/// the expression. KnownOne and KnownZero always follow the invariant that
796/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
797/// the bits in KnownOne and KnownZero may only be accurate for those bits set
798/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
799/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000800///
801/// This returns null if it did not change anything and it permits no
802/// simplification. This returns V itself if it did some simplification of V's
803/// operands based on the information about what bits are demanded. This returns
804/// some other non-null value if it found out that V is equal to another value
805/// in the context where the specified bits are demanded, but not for all users.
806Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
807 APInt &KnownZero, APInt &KnownOne,
808 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000809 assert(V != 0 && "Null pointer of Value???");
810 assert(Depth <= 6 && "Limit Search Depth");
811 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000812 const Type *VTy = V->getType();
813 assert((TD || !isa<PointerType>(VTy)) &&
814 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000815 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
816 (!VTy->isIntOrIntVector() ||
817 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000818 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000819 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000820 "Value *V, DemandedMask, KnownZero and KnownOne "
821 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000822 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
823 // We know all of the bits for a constant!
824 KnownOne = CI->getValue() & DemandedMask;
825 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000826 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000827 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000828 if (isa<ConstantPointerNull>(V)) {
829 // We know all of the bits for a constant!
830 KnownOne.clear();
831 KnownZero = DemandedMask;
832 return 0;
833 }
834
Chris Lattner08d2cc72009-01-31 07:26:06 +0000835 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000836 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000837 if (DemandedMask == 0) { // Not demanding any bits from V.
838 if (isa<UndefValue>(V))
839 return 0;
840 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000841 }
842
Chris Lattner4598c942009-01-31 08:24:16 +0000843 if (Depth == 6) // Limit search depth.
844 return 0;
845
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000846 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
847 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
848
Dan Gohman1c8491e2009-04-25 17:12:48 +0000849 Instruction *I = dyn_cast<Instruction>(V);
850 if (!I) {
851 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
852 return 0; // Only analyze instructions.
853 }
854
Chris Lattner4598c942009-01-31 08:24:16 +0000855 // If there are multiple uses of this value and we aren't at the root, then
856 // we can't do any simplifications of the operands, because DemandedMask
857 // only reflects the bits demanded by *one* of the users.
858 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000859 // Despite the fact that we can't simplify this instruction in all User's
860 // context, we can at least compute the knownzero/knownone bits, and we can
861 // do simplifications that apply to *just* the one user if we know that
862 // this instruction has a simpler value in that context.
863 if (I->getOpcode() == Instruction::And) {
864 // If either the LHS or the RHS are Zero, the result is zero.
865 ComputeMaskedBits(I->getOperand(1), DemandedMask,
866 RHSKnownZero, RHSKnownOne, Depth+1);
867 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
868 LHSKnownZero, LHSKnownOne, Depth+1);
869
870 // If all of the demanded bits are known 1 on one side, return the other.
871 // These bits cannot contribute to the result of the 'and' in this
872 // context.
873 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
874 (DemandedMask & ~LHSKnownZero))
875 return I->getOperand(0);
876 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
877 (DemandedMask & ~RHSKnownZero))
878 return I->getOperand(1);
879
880 // If all of the demanded bits in the inputs are known zeros, return zero.
881 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
882 return Constant::getNullValue(VTy);
883
884 } else if (I->getOpcode() == Instruction::Or) {
885 // We can simplify (X|Y) -> X or Y in the user's context if we know that
886 // only bits from X or Y are demanded.
887
888 // If either the LHS or the RHS are One, the result is One.
889 ComputeMaskedBits(I->getOperand(1), DemandedMask,
890 RHSKnownZero, RHSKnownOne, Depth+1);
891 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
892 LHSKnownZero, LHSKnownOne, Depth+1);
893
894 // If all of the demanded bits are known zero on one side, return the
895 // other. These bits cannot contribute to the result of the 'or' in this
896 // context.
897 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
898 (DemandedMask & ~LHSKnownOne))
899 return I->getOperand(0);
900 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
901 (DemandedMask & ~RHSKnownOne))
902 return I->getOperand(1);
903
904 // If all of the potentially set bits on one side are known to be set on
905 // the other side, just use the 'other' side.
906 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
907 (DemandedMask & (~RHSKnownZero)))
908 return I->getOperand(0);
909 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
910 (DemandedMask & (~LHSKnownZero)))
911 return I->getOperand(1);
912 }
913
Chris Lattner4598c942009-01-31 08:24:16 +0000914 // Compute the KnownZero/KnownOne bits to simplify things downstream.
915 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
916 return 0;
917 }
918
919 // If this is the root being simplified, allow it to have multiple uses,
920 // just set the DemandedMask to all bits so that we can try to simplify the
921 // operands. This allows visitTruncInst (for example) to simplify the
922 // operand of a trunc without duplicating all the logic below.
923 if (Depth == 0 && !V->hasOneUse())
924 DemandedMask = APInt::getAllOnesValue(BitWidth);
925
Reid Spencer8cb68342007-03-12 17:25:59 +0000926 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000927 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000928 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000929 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000930 case Instruction::And:
931 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000932 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
933 RHSKnownZero, RHSKnownOne, Depth+1) ||
934 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000935 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000936 return I;
937 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
938 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000939
940 // If all of the demanded bits are known 1 on one side, return the other.
941 // These bits cannot contribute to the result of the 'and'.
942 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
943 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000944 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000945 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
946 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000947 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000948
949 // If all of the demanded bits in the inputs are known zeros, return zero.
950 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000951 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000952
953 // If the RHS is a constant, see if we can simplify it.
954 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000955 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000956
957 // Output known-1 bits are only known if set in both the LHS & RHS.
958 RHSKnownOne &= LHSKnownOne;
959 // Output known-0 are known to be clear if zero in either the LHS | RHS.
960 RHSKnownZero |= LHSKnownZero;
961 break;
962 case Instruction::Or:
963 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000964 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
965 RHSKnownZero, RHSKnownOne, Depth+1) ||
966 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000967 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000968 return I;
969 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
970 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000971
972 // If all of the demanded bits are known zero on one side, return the other.
973 // These bits cannot contribute to the result of the 'or'.
974 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
975 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000977 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
978 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000979 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000980
981 // If all of the potentially set bits on one side are known to be set on
982 // the other side, just use the 'other' side.
983 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
984 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000985 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000986 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
987 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000989
990 // If the RHS is a constant, see if we can simplify it.
991 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000992 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000993
994 // Output known-0 bits are only known if clear in both the LHS & RHS.
995 RHSKnownZero &= LHSKnownZero;
996 // Output known-1 are known to be set if set in either the LHS | RHS.
997 RHSKnownOne |= LHSKnownOne;
998 break;
999 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001000 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1001 RHSKnownZero, RHSKnownOne, Depth+1) ||
1002 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001003 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001004 return I;
1005 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1006 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001007
1008 // If all of the demanded bits are known zero on one side, return the other.
1009 // These bits cannot contribute to the result of the 'xor'.
1010 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001011 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001012 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001013 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001014
1015 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1016 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1017 (RHSKnownOne & LHSKnownOne);
1018 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1019 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1020 (RHSKnownOne & LHSKnownZero);
1021
1022 // If all of the demanded bits are known to be zero on one side or the
1023 // other, turn this into an *inclusive* or.
1024 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1025 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1026 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001027 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001028 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001029 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001030 }
1031
1032 // If all of the demanded bits on one side are known, and all of the set
1033 // bits on that side are also known to be set on the other side, turn this
1034 // into an AND, as we know the bits will be cleared.
1035 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1036 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1037 // all known
1038 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1039 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1040 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001041 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001042 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001043 }
1044 }
1045
1046 // If the RHS is a constant, see if we can simplify it.
1047 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1048 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001049 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001050
1051 RHSKnownZero = KnownZeroOut;
1052 RHSKnownOne = KnownOneOut;
1053 break;
1054 }
1055 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1057 RHSKnownZero, RHSKnownOne, Depth+1) ||
1058 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001059 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 return I;
1061 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1062 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001063
1064 // If the operands are constants, see if we can simplify them.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001065 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1066 ShrinkDemandedConstant(I, 2, DemandedMask))
1067 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001068
1069 // Only known if known in both the LHS and RHS.
1070 RHSKnownOne &= LHSKnownOne;
1071 RHSKnownZero &= LHSKnownZero;
1072 break;
1073 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001074 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001075 DemandedMask.zext(truncBf);
1076 RHSKnownZero.zext(truncBf);
1077 RHSKnownOne.zext(truncBf);
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.trunc(BitWidth);
1082 RHSKnownZero.trunc(BitWidth);
1083 RHSKnownOne.trunc(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 break;
1086 }
1087 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001088 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001089 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001090
1091 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1092 if (const VectorType *SrcVTy =
1093 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1094 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1095 // Don't touch a bitcast between vectors of different element counts.
1096 return false;
1097 } else
1098 // Don't touch a scalar-to-vector bitcast.
1099 return false;
1100 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1101 // Don't touch a vector-to-scalar bitcast.
1102 return false;
1103
Chris Lattner886ab6c2009-01-31 08:15:18 +00001104 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001105 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001106 return I;
1107 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001108 break;
1109 case Instruction::ZExt: {
1110 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001111 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001112
Zhou Shengd48653a2007-03-29 04:45:55 +00001113 DemandedMask.trunc(SrcBitWidth);
1114 RHSKnownZero.trunc(SrcBitWidth);
1115 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001116 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001117 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001118 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 DemandedMask.zext(BitWidth);
1120 RHSKnownZero.zext(BitWidth);
1121 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001122 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001123 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001124 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001125 break;
1126 }
1127 case Instruction::SExt: {
1128 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001129 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001130
Reid Spencer8cb68342007-03-12 17:25:59 +00001131 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001132 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001133
Zhou Sheng01542f32007-03-29 02:26:30 +00001134 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 // If any of the sign extended bits are demanded, we know that the sign
1136 // bit is demanded.
1137 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001138 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001139
Zhou Shengd48653a2007-03-29 04:45:55 +00001140 InputDemandedBits.trunc(SrcBitWidth);
1141 RHSKnownZero.trunc(SrcBitWidth);
1142 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001143 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001144 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001145 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001146 InputDemandedBits.zext(BitWidth);
1147 RHSKnownZero.zext(BitWidth);
1148 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001149 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001150
1151 // If the sign bit of the input is known set or clear, then we know the
1152 // top bits of the result.
1153
1154 // If the input sign bit is known zero, or if the NewBits are not demanded
1155 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001156 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001157 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001158 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1159 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001160 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001161 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001162 }
1163 break;
1164 }
1165 case Instruction::Add: {
1166 // Figure out what the input bits are. If the top bits of the and result
1167 // are not demanded, then the add doesn't demand them from its input
1168 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001169 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001170
1171 // If there is a constant on the RHS, there are a variety of xformations
1172 // we can do.
1173 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1174 // If null, this should be simplified elsewhere. Some of the xforms here
1175 // won't work if the RHS is zero.
1176 if (RHS->isZero())
1177 break;
1178
1179 // If the top bit of the output is demanded, demand everything from the
1180 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001181 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001182
1183 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001184 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001185 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001186 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001187
1188 // If the RHS of the add has bits set that can't affect the input, reduce
1189 // the constant.
1190 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001191 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001192
1193 // Avoid excess work.
1194 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1195 break;
1196
1197 // Turn it into OR if input bits are zero.
1198 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1199 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001200 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001201 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001202 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001203 }
1204
1205 // We can say something about the output known-zero and known-one bits,
1206 // depending on potential carries from the input constant and the
1207 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1208 // bits set and the RHS constant is 0x01001, then we know we have a known
1209 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1210
1211 // To compute this, we first compute the potential carry bits. These are
1212 // the bits which may be modified. I'm not aware of a better way to do
1213 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001214 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001215 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001216
1217 // Now that we know which bits have carries, compute the known-1/0 sets.
1218
1219 // Bits are known one if they are known zero in one operand and one in the
1220 // other, and there is no input carry.
1221 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1222 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1223
1224 // Bits are known zero if they are known zero in both operands and there
1225 // is no input carry.
1226 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1227 } else {
1228 // If the high-bits of this ADD are not demanded, then it does not demand
1229 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001230 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 // Right fill the mask of bits for this ADD to demand the most
1232 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001233 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001234 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1235 LHSKnownZero, LHSKnownOne, Depth+1) ||
1236 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001237 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001238 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001239 }
1240 }
1241 break;
1242 }
1243 case Instruction::Sub:
1244 // If the high-bits of this SUB are not demanded, then it does not demand
1245 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001246 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001247 // Right fill the mask of bits for this SUB to demand the most
1248 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001249 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001250 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001251 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1252 LHSKnownZero, LHSKnownOne, Depth+1) ||
1253 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001254 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001255 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001256 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001257 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1258 // the known zeros and ones.
1259 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001260 break;
1261 case Instruction::Shl:
1262 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001263 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001264 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001265 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001266 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001267 return I;
1268 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001269 RHSKnownZero <<= ShiftAmt;
1270 RHSKnownOne <<= ShiftAmt;
1271 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001272 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001273 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001274 }
1275 break;
1276 case Instruction::LShr:
1277 // For a logical shift right
1278 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001279 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001280
Reid Spencer8cb68342007-03-12 17:25:59 +00001281 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001282 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001283 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001284 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001285 return I;
1286 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001287 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1288 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001289 if (ShiftAmt) {
1290 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001291 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001292 RHSKnownZero |= HighBits; // high bits known zero.
1293 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001294 }
1295 break;
1296 case Instruction::AShr:
1297 // If this is an arithmetic shift right and only the low-bit is set, we can
1298 // always convert this into a logical shr, even if the shift amount is
1299 // variable. The low bit of the shift cannot be an input sign bit unless
1300 // the shift amount is >= the size of the datatype, which is undefined.
1301 if (DemandedMask == 1) {
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), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001305 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001306 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001307
1308 // If the sign bit is the only bit demanded by this ashr, then there is no
1309 // need to do it, the shift doesn't change the high bit.
1310 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001311 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001312
1313 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001314 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001315
Reid Spencer8cb68342007-03-12 17:25:59 +00001316 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001317 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001318 // If any of the "high bits" are demanded, we should set the sign bit as
1319 // demanded.
1320 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1321 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001323 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001324 return I;
1325 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001326 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001327 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001328 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1329 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1330
1331 // Handle the sign bits.
1332 APInt SignBit(APInt::getSignBit(BitWidth));
1333 // Adjust to where it is now in the mask.
1334 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1335
1336 // If the input sign bit is known to be zero, or if none of the top bits
1337 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001338 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001339 (HighBits & ~DemandedMask) == HighBits) {
1340 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001341 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001342 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001343 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001344 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1345 RHSKnownOne |= HighBits;
1346 }
1347 }
1348 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001349 case Instruction::SRem:
1350 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001351 APInt RA = Rem->getValue().abs();
1352 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001353 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001354 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001355
Nick Lewycky8e394322008-11-02 02:41:50 +00001356 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001357 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001358 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001359 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001360 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001361
1362 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1363 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001364
1365 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001366
Chris Lattner886ab6c2009-01-31 08:15:18 +00001367 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001368 }
1369 }
1370 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001371 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001372 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1373 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001374 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1375 KnownZero2, KnownOne2, Depth+1) ||
1376 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001377 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001378 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001379
Chris Lattner455e9ab2009-01-21 18:09:24 +00001380 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001381 Leaders = std::max(Leaders,
1382 KnownZero2.countLeadingOnes());
1383 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001384 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001385 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001386 case Instruction::Call:
1387 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1388 switch (II->getIntrinsicID()) {
1389 default: break;
1390 case Intrinsic::bswap: {
1391 // If the only bits demanded come from one byte of the bswap result,
1392 // just shift the input byte into position to eliminate the bswap.
1393 unsigned NLZ = DemandedMask.countLeadingZeros();
1394 unsigned NTZ = DemandedMask.countTrailingZeros();
1395
1396 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1397 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1398 // have 14 leading zeros, round to 8.
1399 NLZ &= ~7;
1400 NTZ &= ~7;
1401 // If we need exactly one byte, we can do this transformation.
1402 if (BitWidth-NLZ-NTZ == 8) {
1403 unsigned ResultBit = NTZ;
1404 unsigned InputBit = BitWidth-NTZ-8;
1405
1406 // Replace this with either a left or right shift to get the byte into
1407 // the right place.
1408 Instruction *NewVal;
1409 if (InputBit > ResultBit)
1410 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1411 ConstantInt::get(I->getType(), InputBit-ResultBit));
1412 else
1413 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1414 ConstantInt::get(I->getType(), ResultBit-InputBit));
1415 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001416 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001417 }
1418
1419 // TODO: Could compute known zero/one bits based on the input.
1420 break;
1421 }
1422 }
1423 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001424 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001425 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001426 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001427
1428 // If the client is only demanding bits that we know, return the known
1429 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001430 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1431 Constant *C = ConstantInt::get(RHSKnownOne);
1432 if (isa<PointerType>(V->getType()))
1433 C = ConstantExpr::getIntToPtr(C, V->getType());
1434 return C;
1435 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001436 return false;
1437}
1438
Chris Lattner867b99f2006-10-05 06:55:50 +00001439
Mon P Wangaeb06d22008-11-10 04:46:22 +00001440/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001441/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001442/// actually used by the caller. This method analyzes which elements of the
1443/// operand are undef and returns that information in UndefElts.
1444///
1445/// If the information about demanded elements can be used to simplify the
1446/// operation, the operation is simplified, then the resultant value is
1447/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001448Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1449 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001450 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001451 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001452 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001453 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001454
1455 if (isa<UndefValue>(V)) {
1456 // If the entire vector is undefined, just return this info.
1457 UndefElts = EltMask;
1458 return 0;
1459 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1460 UndefElts = EltMask;
1461 return UndefValue::get(V->getType());
1462 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001463
Chris Lattner867b99f2006-10-05 06:55:50 +00001464 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001465 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1466 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001467 Constant *Undef = UndefValue::get(EltTy);
1468
1469 std::vector<Constant*> Elts;
1470 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001471 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001472 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001473 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001474 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1475 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001476 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001477 } else { // Otherwise, defined.
1478 Elts.push_back(CP->getOperand(i));
1479 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001480
Chris Lattner867b99f2006-10-05 06:55:50 +00001481 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001482 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001483 return NewCP != CP ? NewCP : 0;
1484 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001485 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001486 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001487
1488 // Check if this is identity. If so, return 0 since we are not simplifying
1489 // anything.
1490 if (DemandedElts == ((1ULL << VWidth) -1))
1491 return 0;
1492
Reid Spencer9d6565a2007-02-15 02:26:10 +00001493 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001494 Constant *Zero = Constant::getNullValue(EltTy);
1495 Constant *Undef = UndefValue::get(EltTy);
1496 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001497 for (unsigned i = 0; i != VWidth; ++i) {
1498 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1499 Elts.push_back(Elt);
1500 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001501 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001502 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001503 }
1504
Dan Gohman488fbfc2008-09-09 18:11:14 +00001505 // Limit search depth.
1506 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001507 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001508
1509 // If multiple users are using the root value, procede with
1510 // simplification conservatively assuming that all elements
1511 // are needed.
1512 if (!V->hasOneUse()) {
1513 // Quit if we find multiple users of a non-root value though.
1514 // They'll be handled when it's their turn to be visited by
1515 // the main instcombine process.
1516 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001517 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001518 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001519
1520 // Conservatively assume that all elements are needed.
1521 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001522 }
1523
1524 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001525 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001526
1527 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001528 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001529 Value *TmpV;
1530 switch (I->getOpcode()) {
1531 default: break;
1532
1533 case Instruction::InsertElement: {
1534 // If this is a variable index, we don't know which element it overwrites.
1535 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001536 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001537 if (Idx == 0) {
1538 // Note that we can't propagate undef elt info, because we don't know
1539 // which elt is getting updated.
1540 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1541 UndefElts2, Depth+1);
1542 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543 break;
1544 }
1545
1546 // If this is inserting an element that isn't demanded, remove this
1547 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001548 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001549 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001550 return AddSoonDeadInstToWorklist(*I, 0);
1551
1552 // Otherwise, the element inserted overwrites whatever was there, so the
1553 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001554 APInt DemandedElts2 = DemandedElts;
1555 DemandedElts2.clear(IdxNo);
1556 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001557 UndefElts, Depth+1);
1558 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1559
1560 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001561 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001562 break;
1563 }
1564 case Instruction::ShuffleVector: {
1565 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001566 uint64_t LHSVWidth =
1567 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001568 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001569 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001570 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571 unsigned MaskVal = Shuffle->getMaskValue(i);
1572 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001573 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001574 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001575 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001576 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001577 else
Evan Cheng388df622009-02-03 10:05:09 +00001578 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001579 }
1580 }
1581 }
1582
Nate Begeman7b254672009-02-11 22:36:25 +00001583 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001584 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001585 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001586 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1587
Nate Begeman7b254672009-02-11 22:36:25 +00001588 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001589 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1590 UndefElts3, Depth+1);
1591 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1592
1593 bool NewUndefElts = false;
1594 for (unsigned i = 0; i < VWidth; i++) {
1595 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001596 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001597 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001598 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001599 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001600 NewUndefElts = true;
1601 UndefElts.set(i);
1602 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001603 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001604 if (UndefElts3[MaskVal - LHSVWidth]) {
1605 NewUndefElts = true;
1606 UndefElts.set(i);
1607 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001608 }
1609 }
1610
1611 if (NewUndefElts) {
1612 // Add additional discovered undefs.
1613 std::vector<Constant*> Elts;
1614 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001615 if (UndefElts[i])
Dan Gohman488fbfc2008-09-09 18:11:14 +00001616 Elts.push_back(UndefValue::get(Type::Int32Ty));
1617 else
1618 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1619 Shuffle->getMaskValue(i)));
1620 }
1621 I->setOperand(2, ConstantVector::get(Elts));
1622 MadeChange = true;
1623 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001624 break;
1625 }
Chris Lattner69878332007-04-14 22:29:23 +00001626 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001627 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001628 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1629 if (!VTy) break;
1630 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001631 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001632 unsigned Ratio;
1633
1634 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001635 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001636 // elements as are demanded of us.
1637 Ratio = 1;
1638 InputDemandedElts = DemandedElts;
1639 } else if (VWidth > InVWidth) {
1640 // Untested so far.
1641 break;
1642
1643 // If there are more elements in the result than there are in the source,
1644 // then an input element is live if any of the corresponding output
1645 // elements are live.
1646 Ratio = VWidth/InVWidth;
1647 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001648 if (DemandedElts[OutIdx])
1649 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001650 }
1651 } else {
1652 // Untested so far.
1653 break;
1654
1655 // If there are more elements in the source than there are in the result,
1656 // then an input element is live if the corresponding output element is
1657 // live.
1658 Ratio = InVWidth/VWidth;
1659 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001660 if (DemandedElts[InIdx/Ratio])
1661 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001662 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001663
Chris Lattner69878332007-04-14 22:29:23 +00001664 // div/rem demand all inputs, because they don't want divide by zero.
1665 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1666 UndefElts2, Depth+1);
1667 if (TmpV) {
1668 I->setOperand(0, TmpV);
1669 MadeChange = true;
1670 }
1671
1672 UndefElts = UndefElts2;
1673 if (VWidth > InVWidth) {
1674 assert(0 && "Unimp");
1675 // If there are more elements in the result than there are in the source,
1676 // then an output element is undef if the corresponding input element is
1677 // undef.
1678 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001679 if (UndefElts2[OutIdx/Ratio])
1680 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001681 } else if (VWidth < InVWidth) {
1682 assert(0 && "Unimp");
1683 // If there are more elements in the source than there are in the result,
1684 // then a result element is undef if all of the corresponding input
1685 // elements are undef.
1686 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1687 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001688 if (!UndefElts2[InIdx]) // Not undef?
1689 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001690 }
1691 break;
1692 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001693 case Instruction::And:
1694 case Instruction::Or:
1695 case Instruction::Xor:
1696 case Instruction::Add:
1697 case Instruction::Sub:
1698 case Instruction::Mul:
1699 // div/rem demand all inputs, because they don't want divide by zero.
1700 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1701 UndefElts, Depth+1);
1702 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1703 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1704 UndefElts2, Depth+1);
1705 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1706
1707 // Output elements are undefined if both are undefined. Consider things
1708 // like undef&0. The result is known zero, not undef.
1709 UndefElts &= UndefElts2;
1710 break;
1711
1712 case Instruction::Call: {
1713 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1714 if (!II) break;
1715 switch (II->getIntrinsicID()) {
1716 default: break;
1717
1718 // Binary vector operations that work column-wise. A dest element is a
1719 // function of the corresponding input elements from the two inputs.
1720 case Intrinsic::x86_sse_sub_ss:
1721 case Intrinsic::x86_sse_mul_ss:
1722 case Intrinsic::x86_sse_min_ss:
1723 case Intrinsic::x86_sse_max_ss:
1724 case Intrinsic::x86_sse2_sub_sd:
1725 case Intrinsic::x86_sse2_mul_sd:
1726 case Intrinsic::x86_sse2_min_sd:
1727 case Intrinsic::x86_sse2_max_sd:
1728 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1729 UndefElts, Depth+1);
1730 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1731 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1732 UndefElts2, Depth+1);
1733 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1734
1735 // If only the low elt is demanded and this is a scalarizable intrinsic,
1736 // scalarize it now.
1737 if (DemandedElts == 1) {
1738 switch (II->getIntrinsicID()) {
1739 default: break;
1740 case Intrinsic::x86_sse_sub_ss:
1741 case Intrinsic::x86_sse_mul_ss:
1742 case Intrinsic::x86_sse2_sub_sd:
1743 case Intrinsic::x86_sse2_mul_sd:
1744 // TODO: Lower MIN/MAX/ABS/etc
1745 Value *LHS = II->getOperand(1);
1746 Value *RHS = II->getOperand(2);
1747 // Extract the element as scalars.
1748 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1749 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1750
1751 switch (II->getIntrinsicID()) {
1752 default: assert(0 && "Case stmts out of sync!");
1753 case Intrinsic::x86_sse_sub_ss:
1754 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001755 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001756 II->getName()), *II);
1757 break;
1758 case Intrinsic::x86_sse_mul_ss:
1759 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001760 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001761 II->getName()), *II);
1762 break;
1763 }
1764
1765 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001766 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1767 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001768 InsertNewInstBefore(New, *II);
1769 AddSoonDeadInstToWorklist(*II, 0);
1770 return New;
1771 }
1772 }
1773
1774 // Output elements are undefined if both are undefined. Consider things
1775 // like undef&0. The result is known zero, not undef.
1776 UndefElts &= UndefElts2;
1777 break;
1778 }
1779 break;
1780 }
1781 }
1782 return MadeChange ? I : 0;
1783}
1784
Dan Gohman45b4e482008-05-19 22:14:15 +00001785
Chris Lattner564a7272003-08-13 19:01:45 +00001786/// AssociativeOpt - Perform an optimization on an associative operator. This
1787/// function is designed to check a chain of associative operators for a
1788/// potential to apply a certain optimization. Since the optimization may be
1789/// applicable if the expression was reassociated, this checks the chain, then
1790/// reassociates the expression as necessary to expose the optimization
1791/// opportunity. This makes use of a special Functor, which must define
1792/// 'shouldApply' and 'apply' methods.
1793///
1794template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001795static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001796 unsigned Opcode = Root.getOpcode();
1797 Value *LHS = Root.getOperand(0);
1798
1799 // Quick check, see if the immediate LHS matches...
1800 if (F.shouldApply(LHS))
1801 return F.apply(Root);
1802
1803 // Otherwise, if the LHS is not of the same opcode as the root, return.
1804 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001805 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001806 // Should we apply this transform to the RHS?
1807 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1808
1809 // If not to the RHS, check to see if we should apply to the LHS...
1810 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1811 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1812 ShouldApply = true;
1813 }
1814
1815 // If the functor wants to apply the optimization to the RHS of LHSI,
1816 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1817 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001818 // Now all of the instructions are in the current basic block, go ahead
1819 // and perform the reassociation.
1820 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1821
1822 // First move the selected RHS to the LHS of the root...
1823 Root.setOperand(0, LHSI->getOperand(1));
1824
1825 // Make what used to be the LHS of the root be the user of the root...
1826 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001827 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001828 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1829 return 0;
1830 }
Chris Lattner65725312004-04-16 18:08:07 +00001831 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001832 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001833 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001834 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001835 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001836
1837 // Now propagate the ExtraOperand down the chain of instructions until we
1838 // get to LHSI.
1839 while (TmpLHSI != LHSI) {
1840 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001841 // Move the instruction to immediately before the chain we are
1842 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001843 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001844 ARI = NextLHSI;
1845
Chris Lattner564a7272003-08-13 19:01:45 +00001846 Value *NextOp = NextLHSI->getOperand(1);
1847 NextLHSI->setOperand(1, ExtraOperand);
1848 TmpLHSI = NextLHSI;
1849 ExtraOperand = NextOp;
1850 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001851
Chris Lattner564a7272003-08-13 19:01:45 +00001852 // Now that the instructions are reassociated, have the functor perform
1853 // the transformation...
1854 return F.apply(Root);
1855 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001856
Chris Lattner564a7272003-08-13 19:01:45 +00001857 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1858 }
1859 return 0;
1860}
1861
Dan Gohman844731a2008-05-13 00:00:25 +00001862namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001863
Nick Lewycky02d639f2008-05-23 04:34:58 +00001864// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001865struct AddRHS {
1866 Value *RHS;
1867 AddRHS(Value *rhs) : RHS(rhs) {}
1868 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1869 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001870 return BinaryOperator::CreateShl(Add.getOperand(0),
1871 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001872 }
1873};
1874
1875// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1876// iff C1&C2 == 0
1877struct AddMaskingAnd {
1878 Constant *C2;
1879 AddMaskingAnd(Constant *c) : C2(c) {}
1880 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001881 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001882 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001883 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001884 }
1885 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001886 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001887 }
1888};
1889
Dan Gohman844731a2008-05-13 00:00:25 +00001890}
1891
Chris Lattner6e7ba452005-01-01 16:22:27 +00001892static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001893 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001894 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001895 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001896 }
1897
Chris Lattner2eefe512004-04-09 19:05:30 +00001898 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001899 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1900 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001901
Chris Lattner2eefe512004-04-09 19:05:30 +00001902 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1903 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001904 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1905 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001906 }
1907
1908 Value *Op0 = SO, *Op1 = ConstOperand;
1909 if (!ConstIsRHS)
1910 std::swap(Op0, Op1);
1911 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001912 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001913 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001914 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001915 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001916 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001917 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001918 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001919 abort();
1920 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001921 return IC->InsertNewInstBefore(New, I);
1922}
1923
1924// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1925// constant as the other operand, try to fold the binary operator into the
1926// select arguments. This also works for Cast instructions, which obviously do
1927// not have a second operand.
1928static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1929 InstCombiner *IC) {
1930 // Don't modify shared select instructions
1931 if (!SI->hasOneUse()) return 0;
1932 Value *TV = SI->getOperand(1);
1933 Value *FV = SI->getOperand(2);
1934
1935 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001936 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001937 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001938
Chris Lattner6e7ba452005-01-01 16:22:27 +00001939 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1940 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1941
Gabor Greif051a9502008-04-06 20:25:17 +00001942 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1943 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001944 }
1945 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001946}
1947
Chris Lattner4e998b22004-09-29 05:07:12 +00001948
1949/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1950/// node as operand #0, see if we can fold the instruction into the PHI (which
1951/// is only possible if all operands to the PHI are constants).
1952Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1953 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001954 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001955 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001956
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001957 // Check to see if all of the operands of the PHI are constants. If there is
1958 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001959 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001960 BasicBlock *NonConstBB = 0;
1961 for (unsigned i = 0; i != NumPHIValues; ++i)
1962 if (!isa<Constant>(PN->getIncomingValue(i))) {
1963 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001964 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001965 NonConstBB = PN->getIncomingBlock(i);
1966
1967 // If the incoming non-constant value is in I's block, we have an infinite
1968 // loop.
1969 if (NonConstBB == I.getParent())
1970 return 0;
1971 }
1972
1973 // If there is exactly one non-constant value, we can insert a copy of the
1974 // operation in that block. However, if this is a critical edge, we would be
1975 // inserting the computation one some other paths (e.g. inside a loop). Only
1976 // do this if the pred block is unconditionally branching into the phi block.
1977 if (NonConstBB) {
1978 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1979 if (!BI || !BI->isUnconditional()) return 0;
1980 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001981
1982 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001983 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001984 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001985 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001986 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001987
1988 // Next, add all of the operands to the PHI.
1989 if (I.getNumOperands() == 2) {
1990 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001991 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001992 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001993 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001994 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1995 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1996 else
1997 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001998 } else {
1999 assert(PN->getIncomingBlock(i) == NonConstBB);
2000 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002001 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002002 PN->getIncomingValue(i), C, "phitmp",
2003 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002004 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002005 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002006 CI->getPredicate(),
2007 PN->getIncomingValue(i), C, "phitmp",
2008 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002009 else
2010 assert(0 && "Unknown binop!");
2011
Chris Lattnerdbab3862007-03-02 21:28:56 +00002012 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002013 }
2014 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002015 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002016 } else {
2017 CastInst *CI = cast<CastInst>(&I);
2018 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002019 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002020 Value *InV;
2021 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002022 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002023 } else {
2024 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002025 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002026 I.getType(), "phitmp",
2027 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002028 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002029 }
2030 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002031 }
2032 }
2033 return ReplaceInstUsesWith(I, NewPN);
2034}
2035
Chris Lattner2454a2e2008-01-29 06:52:45 +00002036
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002037/// WillNotOverflowSignedAdd - Return true if we can prove that:
2038/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2039/// This basically requires proving that the add in the original type would not
2040/// overflow to change the sign bit or have a carry out.
2041bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2042 // There are different heuristics we can use for this. Here are some simple
2043 // ones.
2044
2045 // Add has the property that adding any two 2's complement numbers can only
2046 // have one carry bit which can change a sign. As such, if LHS and RHS each
2047 // have at least two sign bits, we know that the addition of the two values will
2048 // sign extend fine.
2049 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2050 return true;
2051
2052
2053 // If one of the operands only has one non-zero bit, and if the other operand
2054 // has a known-zero bit in a more significant place than it (not including the
2055 // sign bit) the ripple may go up to and fill the zero, but won't change the
2056 // sign. For example, (X & ~4) + 1.
2057
2058 // TODO: Implement.
2059
2060 return false;
2061}
2062
Chris Lattner2454a2e2008-01-29 06:52:45 +00002063
Chris Lattner7e708292002-06-25 16:13:24 +00002064Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002065 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002066 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002067
Chris Lattner66331a42004-04-10 22:01:55 +00002068 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002069 // X + undef -> undef
2070 if (isa<UndefValue>(RHS))
2071 return ReplaceInstUsesWith(I, RHS);
2072
Chris Lattner66331a42004-04-10 22:01:55 +00002073 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002074 if (RHSC->isNullValue())
2075 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002076
Chris Lattner66331a42004-04-10 22:01:55 +00002077 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002078 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002079 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002080 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002081 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002082 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002083
2084 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2085 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002086 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002087 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002088
2089 // zext(i1) - 1 -> select i1, 0, -1
2090 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2091 if (CI->isAllOnesValue() &&
2092 ZI->getOperand(0)->getType() == Type::Int1Ty)
2093 return SelectInst::Create(ZI->getOperand(0),
2094 Constant::getNullValue(I.getType()),
2095 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00002096 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002097
2098 if (isa<PHINode>(LHS))
2099 if (Instruction *NV = FoldOpIntoPhi(I))
2100 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002101
Chris Lattner4f637d42006-01-06 17:59:59 +00002102 ConstantInt *XorRHS = 0;
2103 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002104 if (isa<ConstantInt>(RHSC) &&
2105 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002106 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002107 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002108
Zhou Sheng4351c642007-04-02 08:20:41 +00002109 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002110 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2111 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002112 do {
2113 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002114 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2115 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002116 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2117 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002118 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002119 if (!MaskedValueIsZero(XorLHS,
2120 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002121 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002122 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002123 }
2124 }
2125 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002126 C0080Val = APIntOps::lshr(C0080Val, Size);
2127 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2128 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002129
Reid Spencer35c38852007-03-28 01:36:16 +00002130 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002131 // with funny bit widths then this switch statement should be removed. It
2132 // is just here to get the size of the "middle" type back up to something
2133 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002134 const Type *MiddleType = 0;
2135 switch (Size) {
2136 default: break;
2137 case 32: MiddleType = Type::Int32Ty; break;
2138 case 16: MiddleType = Type::Int16Ty; break;
2139 case 8: MiddleType = Type::Int8Ty; break;
2140 }
2141 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002142 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002143 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002144 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002145 }
2146 }
Chris Lattner66331a42004-04-10 22:01:55 +00002147 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002148
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002149 if (I.getType() == Type::Int1Ty)
2150 return BinaryOperator::CreateXor(LHS, RHS);
2151
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002152 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002153 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002154 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002155
2156 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2157 if (RHSI->getOpcode() == Instruction::Sub)
2158 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2159 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2160 }
2161 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2162 if (LHSI->getOpcode() == Instruction::Sub)
2163 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2164 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2165 }
Robert Bocchino71698282004-07-27 21:02:21 +00002166 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002167
Chris Lattner5c4afb92002-05-08 22:46:53 +00002168 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002169 // -A + -B --> -(A + B)
2170 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002171 if (LHS->getType()->isIntOrIntVector()) {
2172 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002173 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002174 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002175 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002176 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002177 }
2178
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002179 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002180 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002181
2182 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002183 if (!isa<Constant>(RHS))
2184 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002185 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002186
Misha Brukmanfd939082005-04-21 23:48:37 +00002187
Chris Lattner50af16a2004-11-13 19:50:12 +00002188 ConstantInt *C2;
2189 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2190 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002191 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002192
2193 // X*C1 + X*C2 --> X * (C1+C2)
2194 ConstantInt *C1;
2195 if (X == dyn_castFoldableMul(RHS, C1))
Dan Gohman6de29f82009-06-15 22:12:54 +00002196 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002197 }
2198
2199 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002200 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002201 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002202
Chris Lattnere617c9e2007-01-05 02:17:46 +00002203 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002204 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2205 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002206
Chris Lattnerad3448c2003-02-18 19:57:07 +00002207
Chris Lattner564a7272003-08-13 19:01:45 +00002208 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002209 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002210 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2211 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002212
2213 // A+B --> A|B iff A and B have no bits set in common.
2214 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2215 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2216 APInt LHSKnownOne(IT->getBitWidth(), 0);
2217 APInt LHSKnownZero(IT->getBitWidth(), 0);
2218 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2219 if (LHSKnownZero != 0) {
2220 APInt RHSKnownOne(IT->getBitWidth(), 0);
2221 APInt RHSKnownZero(IT->getBitWidth(), 0);
2222 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2223
2224 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002225 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002226 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002227 }
2228 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002229
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002230 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002231 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002232 Value *W, *X, *Y, *Z;
2233 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2234 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2235 if (W != Y) {
2236 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002237 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002238 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002239 std::swap(W, X);
2240 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002241 std::swap(Y, Z);
2242 std::swap(W, X);
2243 }
2244 }
2245
2246 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002247 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002248 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002249 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002250 }
2251 }
2252 }
2253
Chris Lattner6b032052003-10-02 15:11:26 +00002254 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002255 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002256 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002257 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002258
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002259 // (X & FF00) + xx00 -> (X+xx00) & FF00
2260 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002261 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002262 if (Anded == CRHS) {
2263 // See if all bits from the first bit set in the Add RHS up are included
2264 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002265 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002266
2267 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002268 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002269
2270 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002271 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002272
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002273 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2274 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002275 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002276 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002277 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002278 }
2279 }
2280 }
2281
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002282 // Try to fold constant add into select arguments.
2283 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002284 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002285 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002286 }
2287
Reid Spencer1628cec2006-10-26 06:15:43 +00002288 // add (cast *A to intptrtype) B ->
Dan Gohmana119de82009-06-14 23:30:43 +00002289 // cast (GEP (cast *A to i8*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002290 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002291 CastInst *CI = dyn_cast<CastInst>(LHS);
2292 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002293 if (!CI) {
2294 CI = dyn_cast<CastInst>(RHS);
2295 Other = LHS;
2296 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002297 if (CI && CI->getType()->isSized() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00002298 (CI->getType()->getScalarSizeInBits() ==
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002299 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002300 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002301 unsigned AS =
2302 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002303 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2304 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002305 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002306 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002307 }
2308 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002309
Chris Lattner42790482007-12-20 01:56:58 +00002310 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002311 {
2312 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002313 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002314 if (!SI) {
2315 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002316 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002317 }
Chris Lattner42790482007-12-20 01:56:58 +00002318 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002319 Value *TV = SI->getTrueValue();
2320 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002321 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002322
2323 // Can we fold the add into the argument of the select?
2324 // We check both true and false select arguments for a matching subtract.
Chris Lattner6046fb72008-11-16 04:46:19 +00002325 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2326 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002327 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner6046fb72008-11-16 04:46:19 +00002328 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2329 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002330 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002331 }
2332 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002333
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002334 // Check for (add (sext x), y), see if we can merge this into an
2335 // integer add followed by a sext.
2336 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2337 // (add (sext x), cst) --> (sext (add x, cst'))
2338 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2339 Constant *CI =
2340 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2341 if (LHSConv->hasOneUse() &&
2342 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2343 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2344 // Insert the new, smaller add.
2345 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2346 CI, "addconv");
2347 InsertNewInstBefore(NewAdd, I);
2348 return new SExtInst(NewAdd, I.getType());
2349 }
2350 }
2351
2352 // (add (sext x), (sext y)) --> (sext (add int x, y))
2353 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2354 // Only do this if x/y have the same type, if at last one of them has a
2355 // single use (so we don't increase the number of sexts), and if the
2356 // integer add will not overflow.
2357 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2358 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2359 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2360 RHSConv->getOperand(0))) {
2361 // Insert the new integer add.
2362 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2363 RHSConv->getOperand(0),
2364 "addconv");
2365 InsertNewInstBefore(NewAdd, I);
2366 return new SExtInst(NewAdd, I.getType());
2367 }
2368 }
2369 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002370
2371 return Changed ? &I : 0;
2372}
2373
2374Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2375 bool Changed = SimplifyCommutative(I);
2376 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2377
2378 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2379 // X + 0 --> X
2380 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2381 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2382 (I.getType())->getValueAPF()))
2383 return ReplaceInstUsesWith(I, LHS);
2384 }
2385
2386 if (isa<PHINode>(LHS))
2387 if (Instruction *NV = FoldOpIntoPhi(I))
2388 return NV;
2389 }
2390
2391 // -A + B --> B - A
2392 // -A + -B --> -(A + B)
2393 if (Value *LHSV = dyn_castFNegVal(LHS))
2394 return BinaryOperator::CreateFSub(RHS, LHSV);
2395
2396 // A + -B --> A - B
2397 if (!isa<Constant>(RHS))
2398 if (Value *V = dyn_castFNegVal(RHS))
2399 return BinaryOperator::CreateFSub(LHS, V);
2400
2401 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2402 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2403 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2404 return ReplaceInstUsesWith(I, LHS);
2405
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002406 // Check for (add double (sitofp x), y), see if we can merge this into an
2407 // integer add followed by a promotion.
2408 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2409 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2410 // ... if the constant fits in the integer value. This is useful for things
2411 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2412 // requires a constant pool load, and generally allows the add to be better
2413 // instcombined.
2414 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2415 Constant *CI =
2416 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2417 if (LHSConv->hasOneUse() &&
2418 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2419 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2420 // Insert the new integer add.
2421 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2422 CI, "addconv");
2423 InsertNewInstBefore(NewAdd, I);
2424 return new SIToFPInst(NewAdd, I.getType());
2425 }
2426 }
2427
2428 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2429 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2430 // Only do this if x/y have the same type, if at last one of them has a
2431 // single use (so we don't increase the number of int->fp conversions),
2432 // and if the integer add will not overflow.
2433 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2434 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2435 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2436 RHSConv->getOperand(0))) {
2437 // Insert the new integer add.
2438 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2439 RHSConv->getOperand(0),
2440 "addconv");
2441 InsertNewInstBefore(NewAdd, I);
2442 return new SIToFPInst(NewAdd, I.getType());
2443 }
2444 }
2445 }
2446
Chris Lattner7e708292002-06-25 16:13:24 +00002447 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002448}
2449
Chris Lattner7e708292002-06-25 16:13:24 +00002450Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002451 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002452
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002453 if (Op0 == Op1) // sub X, X -> 0
Chris Lattner233f7dc2002-08-12 21:17:25 +00002454 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002455
Chris Lattner233f7dc2002-08-12 21:17:25 +00002456 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002457 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002458 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002459
Chris Lattnere87597f2004-10-16 18:11:37 +00002460 if (isa<UndefValue>(Op0))
2461 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2462 if (isa<UndefValue>(Op1))
2463 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2464
Chris Lattnerd65460f2003-11-05 01:06:05 +00002465 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2466 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002467 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002468 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002469
Chris Lattnerd65460f2003-11-05 01:06:05 +00002470 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002471 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002472 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002473 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002474
Chris Lattner76b7a062007-01-15 07:02:54 +00002475 // -(X >>u 31) -> (X >>s 31)
2476 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002477 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002478 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002479 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002480 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002481 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002482 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002483 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002484 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002485 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002486 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002487 }
2488 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002489 }
2490 else if (SI->getOpcode() == Instruction::AShr) {
2491 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2492 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002493 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002494 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002495 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002496 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002497 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002498 }
2499 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002500 }
2501 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002502 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002503
2504 // Try to fold constant sub into select arguments.
2505 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002506 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002507 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002508 }
2509
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002510 if (I.getType() == Type::Int1Ty)
2511 return BinaryOperator::CreateXor(Op0, Op1);
2512
Chris Lattner43d84d62005-04-07 16:15:25 +00002513 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002514 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002515 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002516 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002517 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002518 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002519 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2520 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2521 // C1-(X+C2) --> (C1-C2)-X
Dan Gohman6de29f82009-06-15 22:12:54 +00002522 return BinaryOperator::CreateSub(ConstantExpr::getSub(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002523 Op1I->getOperand(0));
2524 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002525 }
2526
Chris Lattnerfd059242003-10-15 16:48:29 +00002527 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002528 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2529 // is not used by anyone else...
2530 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002531 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002532 // Swap the two operands of the subexpr...
2533 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2534 Op1I->setOperand(0, IIOp1);
2535 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002536
Chris Lattnera2881962003-02-18 19:28:33 +00002537 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002538 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002539 }
2540
2541 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2542 //
2543 if (Op1I->getOpcode() == Instruction::And &&
2544 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2545 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2546
Chris Lattnerf523d062004-06-09 05:08:07 +00002547 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002548 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2549 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002550 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002551
Reid Spencerac5209e2006-10-16 23:08:08 +00002552 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002553 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002554 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002555 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002556 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002557 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002558 ConstantExpr::getNeg(DivRHS));
2559
Chris Lattnerad3448c2003-02-18 19:57:07 +00002560 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002561 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002562 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002563 Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2564 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002565 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002566 }
Chris Lattner40371712002-05-09 01:29:19 +00002567 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002568 }
Chris Lattnera2881962003-02-18 19:28:33 +00002569
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002570 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2571 if (Op0I->getOpcode() == Instruction::Add) {
2572 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2573 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2574 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2575 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2576 } else if (Op0I->getOpcode() == Instruction::Sub) {
2577 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2578 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002579 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002580 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002581
Chris Lattner50af16a2004-11-13 19:50:12 +00002582 ConstantInt *C1;
2583 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002584 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002585 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002586
Chris Lattner50af16a2004-11-13 19:50:12 +00002587 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2588 if (X == dyn_castFoldableMul(Op1, C2))
Dan Gohman6de29f82009-06-15 22:12:54 +00002589 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002590 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002591 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002592}
2593
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002594Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2595 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2596
2597 // If this is a 'B = x-(-A)', change to B = x+A...
2598 if (Value *V = dyn_castFNegVal(Op1))
2599 return BinaryOperator::CreateFAdd(Op0, V);
2600
2601 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2602 if (Op1I->getOpcode() == Instruction::FAdd) {
2603 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2604 return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2605 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2606 return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2607 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002608 }
2609
2610 return 0;
2611}
2612
Chris Lattnera0141b92007-07-15 20:42:37 +00002613/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2614/// comparison only checks the sign bit. If it only checks the sign bit, set
2615/// TrueIfSigned if the result of the comparison is true when the input value is
2616/// signed.
2617static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2618 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002619 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002620 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2621 TrueIfSigned = true;
2622 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002623 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2624 TrueIfSigned = true;
2625 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002626 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2627 TrueIfSigned = false;
2628 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002629 case ICmpInst::ICMP_UGT:
2630 // True if LHS u> RHS and RHS == high-bit-mask - 1
2631 TrueIfSigned = true;
2632 return RHS->getValue() ==
2633 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2634 case ICmpInst::ICMP_UGE:
2635 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2636 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002637 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002638 default:
2639 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002640 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002641}
2642
Chris Lattner7e708292002-06-25 16:13:24 +00002643Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002644 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002645 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002646
Dan Gohman77b81fe2009-06-04 17:12:12 +00002647 // TODO: If Op1 is undef and Op0 is finite, return zero.
2648 if (!I.getType()->isFPOrFPVector() &&
2649 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00002650 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2651
Chris Lattner233f7dc2002-08-12 21:17:25 +00002652 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002653 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2654 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002655
2656 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002657 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002658 if (SI->getOpcode() == Instruction::Shl)
2659 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002660 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002661 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002662
Zhou Sheng843f07672007-04-19 05:39:12 +00002663 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002664 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2665 if (CI->equalsInt(1)) // X * 1 == X
2666 return ReplaceInstUsesWith(I, Op0);
2667 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002668 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002669
Zhou Sheng97b52c22007-03-29 01:57:21 +00002670 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002671 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002672 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002673 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002674 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002675 } else if (isa<VectorType>(Op1->getType())) {
Dan Gohman77b81fe2009-06-04 17:12:12 +00002676 // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
Nick Lewycky895f0852008-11-27 20:21:08 +00002677
2678 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2679 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2680 return BinaryOperator::CreateNeg(Op0, I.getName());
2681
2682 // As above, vector X*splat(1.0) -> X in all defined cases.
2683 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002684 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2685 if (CI->equalsInt(1))
2686 return ReplaceInstUsesWith(I, Op0);
2687 }
2688 }
Chris Lattnera2881962003-02-18 19:28:33 +00002689 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002690
2691 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2692 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002693 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002694 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002695 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002696 Op1, "tmp");
2697 InsertNewInstBefore(Add, I);
2698 Value *C1C2 = ConstantExpr::getMul(Op1,
2699 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002700 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002701
2702 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002703
2704 // Try to fold constant mul into select arguments.
2705 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002706 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002707 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002708
2709 if (isa<PHINode>(Op0))
2710 if (Instruction *NV = FoldOpIntoPhi(I))
2711 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002712 }
2713
Chris Lattnera4f445b2003-03-10 23:23:04 +00002714 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2715 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002716 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002717
Nick Lewycky0c730792008-11-21 07:33:58 +00002718 // (X / Y) * Y = X - (X % Y)
2719 // (X / Y) * -Y = (X % Y) - X
2720 {
2721 Value *Op1 = I.getOperand(1);
2722 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2723 if (!BO ||
2724 (BO->getOpcode() != Instruction::UDiv &&
2725 BO->getOpcode() != Instruction::SDiv)) {
2726 Op1 = Op0;
2727 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2728 }
2729 Value *Neg = dyn_castNegVal(Op1);
2730 if (BO && BO->hasOneUse() &&
2731 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2732 (BO->getOpcode() == Instruction::UDiv ||
2733 BO->getOpcode() == Instruction::SDiv)) {
2734 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2735
2736 Instruction *Rem;
2737 if (BO->getOpcode() == Instruction::UDiv)
2738 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2739 else
2740 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2741
2742 InsertNewInstBefore(Rem, I);
2743 Rem->takeName(BO);
2744
2745 if (Op1BO == Op1)
2746 return BinaryOperator::CreateSub(Op0BO, Rem);
2747 else
2748 return BinaryOperator::CreateSub(Rem, Op0BO);
2749 }
2750 }
2751
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002752 if (I.getType() == Type::Int1Ty)
2753 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2754
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002755 // If one of the operands of the multiply is a cast from a boolean value, then
2756 // we know the bool is either zero or one, so this is a 'masking' multiply.
2757 // See if we can simplify things based on how the boolean was originally
2758 // formed.
2759 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002760 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002761 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002762 BoolCast = CI;
2763 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002764 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002765 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002766 BoolCast = CI;
2767 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002768 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002769 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2770 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002771 bool TIS = false;
2772
Reid Spencere4d87aa2006-12-23 06:05:41 +00002773 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002774 // multiply into a shift/and combination.
2775 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002776 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2777 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002778 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002779 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002780 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002781 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002782 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002783 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002784 BoolCast->getOperand(0)->getName()+
2785 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002786
2787 // If the multiply type is not the same as the source type, sign extend
2788 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002789 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002790 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2791 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002792 Instruction::CastOps opcode =
2793 (SrcBits == DstBits ? Instruction::BitCast :
2794 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2795 V = InsertCastBefore(opcode, V, I.getType(), I);
2796 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002797
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002798 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002799 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002800 }
2801 }
2802 }
2803
Chris Lattner7e708292002-06-25 16:13:24 +00002804 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002805}
2806
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002807Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2808 bool Changed = SimplifyCommutative(I);
2809 Value *Op0 = I.getOperand(0);
2810
2811 // Simplify mul instructions with a constant RHS...
2812 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2813 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2814 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2815 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2816 if (Op1F->isExactlyValue(1.0))
2817 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2818 } else if (isa<VectorType>(Op1->getType())) {
2819 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2820 // As above, vector X*splat(1.0) -> X in all defined cases.
2821 if (Constant *Splat = Op1V->getSplatValue()) {
2822 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2823 if (F->isExactlyValue(1.0))
2824 return ReplaceInstUsesWith(I, Op0);
2825 }
2826 }
2827 }
2828
2829 // Try to fold constant mul into select arguments.
2830 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2831 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2832 return R;
2833
2834 if (isa<PHINode>(Op0))
2835 if (Instruction *NV = FoldOpIntoPhi(I))
2836 return NV;
2837 }
2838
2839 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2840 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2841 return BinaryOperator::CreateFMul(Op0v, Op1v);
2842
2843 return Changed ? &I : 0;
2844}
2845
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002846/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2847/// instruction.
2848bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2849 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2850
2851 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2852 int NonNullOperand = -1;
2853 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2854 if (ST->isNullValue())
2855 NonNullOperand = 2;
2856 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2857 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2858 if (ST->isNullValue())
2859 NonNullOperand = 1;
2860
2861 if (NonNullOperand == -1)
2862 return false;
2863
2864 Value *SelectCond = SI->getOperand(0);
2865
2866 // Change the div/rem to use 'Y' instead of the select.
2867 I.setOperand(1, SI->getOperand(NonNullOperand));
2868
2869 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2870 // problem. However, the select, or the condition of the select may have
2871 // multiple uses. Based on our knowledge that the operand must be non-zero,
2872 // propagate the known value for the select into other uses of it, and
2873 // propagate a known value of the condition into its other users.
2874
2875 // If the select and condition only have a single use, don't bother with this,
2876 // early exit.
2877 if (SI->use_empty() && SelectCond->hasOneUse())
2878 return true;
2879
2880 // Scan the current block backward, looking for other uses of SI.
2881 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2882
2883 while (BBI != BBFront) {
2884 --BBI;
2885 // If we found a call to a function, we can't assume it will return, so
2886 // information from below it cannot be propagated above it.
2887 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2888 break;
2889
2890 // Replace uses of the select or its condition with the known values.
2891 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2892 I != E; ++I) {
2893 if (*I == SI) {
2894 *I = SI->getOperand(NonNullOperand);
2895 AddToWorkList(BBI);
2896 } else if (*I == SelectCond) {
2897 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2898 ConstantInt::getFalse();
2899 AddToWorkList(BBI);
2900 }
2901 }
2902
2903 // If we past the instruction, quit looking for it.
2904 if (&*BBI == SI)
2905 SI = 0;
2906 if (&*BBI == SelectCond)
2907 SelectCond = 0;
2908
2909 // If we ran out of things to eliminate, break out of the loop.
2910 if (SelectCond == 0 && SI == 0)
2911 break;
2912
2913 }
2914 return true;
2915}
2916
2917
Reid Spencer1628cec2006-10-26 06:15:43 +00002918/// This function implements the transforms on div instructions that work
2919/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2920/// used by the visitors to those instructions.
2921/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002922Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002923 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002924
Chris Lattner50b2ca42008-02-19 06:12:18 +00002925 // undef / X -> 0 for integer.
2926 // undef / X -> undef for FP (the undef could be a snan).
2927 if (isa<UndefValue>(Op0)) {
2928 if (Op0->getType()->isFPOrFPVector())
2929 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002930 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002931 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002932
2933 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002934 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002935 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002936
Reid Spencer1628cec2006-10-26 06:15:43 +00002937 return 0;
2938}
Misha Brukmanfd939082005-04-21 23:48:37 +00002939
Reid Spencer1628cec2006-10-26 06:15:43 +00002940/// This function implements the transforms common to both integer division
2941/// instructions (udiv and sdiv). It is called by the visitors to those integer
2942/// division instructions.
2943/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002944Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002945 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2946
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002947 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002948 if (Op0 == Op1) {
2949 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002950 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002951 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2952 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2953 }
2954
Dan Gohman6de29f82009-06-15 22:12:54 +00002955 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002956 return ReplaceInstUsesWith(I, CI);
2957 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002958
Reid Spencer1628cec2006-10-26 06:15:43 +00002959 if (Instruction *Common = commonDivTransforms(I))
2960 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002961
2962 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2963 // This does not apply for fdiv.
2964 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2965 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002966
2967 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2968 // div X, 1 == X
2969 if (RHS->equalsInt(1))
2970 return ReplaceInstUsesWith(I, Op0);
2971
2972 // (X / C1) / C2 -> X / (C1*C2)
2973 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2974 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2975 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002976 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2977 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2978 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002979 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Dan Gohman6de29f82009-06-15 22:12:54 +00002980 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002981 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002982
Reid Spencerbca0e382007-03-23 20:05:17 +00002983 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002984 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2985 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2986 return R;
2987 if (isa<PHINode>(Op0))
2988 if (Instruction *NV = FoldOpIntoPhi(I))
2989 return NV;
2990 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002991 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002992
Chris Lattnera2881962003-02-18 19:28:33 +00002993 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002994 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002995 if (LHS->equalsInt(0))
2996 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2997
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002998 // It can't be division by zero, hence it must be division by one.
2999 if (I.getType() == Type::Int1Ty)
3000 return ReplaceInstUsesWith(I, Op0);
3001
Nick Lewycky895f0852008-11-27 20:21:08 +00003002 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3003 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3004 // div X, 1 == X
3005 if (X->isOne())
3006 return ReplaceInstUsesWith(I, Op0);
3007 }
3008
Reid Spencer1628cec2006-10-26 06:15:43 +00003009 return 0;
3010}
3011
3012Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3013 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3014
3015 // Handle the integer div common cases
3016 if (Instruction *Common = commonIDivTransforms(I))
3017 return Common;
3018
Reid Spencer1628cec2006-10-26 06:15:43 +00003019 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003020 // X udiv C^2 -> X >> C
3021 // Check to see if this is an unsigned division with an exact power of 2,
3022 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003023 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003024 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003025 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003026
3027 // X udiv C, where C >= signbit
3028 if (C->getValue().isNegative()) {
3029 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3030 I);
3031 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3032 ConstantInt::get(I.getType(), 1));
3033 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003034 }
3035
3036 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003037 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003038 if (RHSI->getOpcode() == Instruction::Shl &&
3039 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003040 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003041 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003042 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003043 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003044 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003045 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003046 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003047 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003048 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003049 }
3050 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003051 }
3052
Reid Spencer1628cec2006-10-26 06:15:43 +00003053 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3054 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003055 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003056 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003057 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003058 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003059 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003060 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003061 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003062 // Construct the "on true" case of the select
3063 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003064 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003065 Op0, TC, SI->getName()+".t");
3066 TSI = InsertNewInstBefore(TSI, I);
3067
3068 // Construct the "on false" case of the select
3069 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003070 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003071 Op0, FC, SI->getName()+".f");
3072 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003073
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003074 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003075 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003076 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003077 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003078 return 0;
3079}
3080
Reid Spencer1628cec2006-10-26 06:15:43 +00003081Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3082 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3083
3084 // Handle the integer div common cases
3085 if (Instruction *Common = commonIDivTransforms(I))
3086 return Common;
3087
3088 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3089 // sdiv X, -1 == -X
3090 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003091 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003092 }
3093
3094 // If the sign bits of both operands are zero (i.e. we can prove they are
3095 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003096 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003097 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003098 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003099 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003100 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003101 }
3102 }
3103
3104 return 0;
3105}
3106
3107Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3108 return commonDivTransforms(I);
3109}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003110
Reid Spencer0a783f72006-11-02 01:53:59 +00003111/// This function implements the transforms on rem instructions that work
3112/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3113/// is used by the visitors to those instructions.
3114/// @brief Transforms common to all three rem instructions
3115Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003116 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003117
Chris Lattner50b2ca42008-02-19 06:12:18 +00003118 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3119 if (I.getType()->isFPOrFPVector())
3120 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003121 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003122 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003123 if (isa<UndefValue>(Op1))
3124 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003125
3126 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003127 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3128 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003129
Reid Spencer0a783f72006-11-02 01:53:59 +00003130 return 0;
3131}
3132
3133/// This function implements the transforms common to both integer remainder
3134/// instructions (urem and srem). It is called by the visitors to those integer
3135/// remainder instructions.
3136/// @brief Common integer remainder transforms
3137Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3138 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3139
3140 if (Instruction *common = commonRemTransforms(I))
3141 return common;
3142
Dale Johannesened6af242009-01-21 00:35:19 +00003143 // 0 % X == 0 for integer, we don't need to preserve faults!
3144 if (Constant *LHS = dyn_cast<Constant>(Op0))
3145 if (LHS->isNullValue())
3146 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3147
Chris Lattner857e8cd2004-12-12 21:48:58 +00003148 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003149 // X % 0 == undef, we don't need to preserve faults!
3150 if (RHS->equalsInt(0))
3151 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3152
Chris Lattnera2881962003-02-18 19:28:33 +00003153 if (RHS->equalsInt(1)) // X % 1 == 0
3154 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3155
Chris Lattner97943922006-02-28 05:49:21 +00003156 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3157 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3158 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3159 return R;
3160 } else if (isa<PHINode>(Op0I)) {
3161 if (Instruction *NV = FoldOpIntoPhi(I))
3162 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003163 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003164
3165 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003166 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003167 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003168 }
Chris Lattnera2881962003-02-18 19:28:33 +00003169 }
3170
Reid Spencer0a783f72006-11-02 01:53:59 +00003171 return 0;
3172}
3173
3174Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3175 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3176
3177 if (Instruction *common = commonIRemTransforms(I))
3178 return common;
3179
3180 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3181 // X urem C^2 -> X and C
3182 // Check to see if this is an unsigned remainder with an exact power of 2,
3183 // if so, convert to a bitwise and.
3184 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003185 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003186 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003187 }
3188
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003189 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003190 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3191 if (RHSI->getOpcode() == Instruction::Shl &&
3192 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003193 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003194 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003195 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003196 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003197 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003198 }
3199 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003200 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003201
Reid Spencer0a783f72006-11-02 01:53:59 +00003202 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3203 // where C1&C2 are powers of two.
3204 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3205 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3206 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3207 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003208 if ((STO->getValue().isPowerOf2()) &&
3209 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003210 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003211 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003212 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003213 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003214 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003215 }
3216 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003217 }
3218
Chris Lattner3f5b8772002-05-06 16:14:14 +00003219 return 0;
3220}
3221
Reid Spencer0a783f72006-11-02 01:53:59 +00003222Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3223 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3224
Dan Gohmancff55092007-11-05 23:16:33 +00003225 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003226 if (Instruction *common = commonIRemTransforms(I))
3227 return common;
3228
3229 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003230 if (!isa<Constant>(RHSNeg) ||
3231 (isa<ConstantInt>(RHSNeg) &&
3232 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003233 // X % -Y -> X % Y
3234 AddUsesToWorkList(I);
3235 I.setOperand(1, RHSNeg);
3236 return &I;
3237 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003238
Dan Gohmancff55092007-11-05 23:16:33 +00003239 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003240 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003241 if (I.getType()->isInteger()) {
3242 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3243 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3244 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003245 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003246 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003247 }
3248
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003249 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003250 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3251 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003252
Nick Lewycky9dce8732008-12-20 16:48:00 +00003253 bool hasNegative = false;
3254 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3255 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3256 if (RHS->getValue().isNegative())
3257 hasNegative = true;
3258
3259 if (hasNegative) {
3260 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003261 for (unsigned i = 0; i != VWidth; ++i) {
3262 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3263 if (RHS->getValue().isNegative())
3264 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3265 else
3266 Elts[i] = RHS;
3267 }
3268 }
3269
3270 Constant *NewRHSV = ConstantVector::get(Elts);
3271 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003272 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003273 I.setOperand(1, NewRHSV);
3274 return &I;
3275 }
3276 }
3277 }
3278
Reid Spencer0a783f72006-11-02 01:53:59 +00003279 return 0;
3280}
3281
3282Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003283 return commonRemTransforms(I);
3284}
3285
Chris Lattner457dd822004-06-09 07:59:58 +00003286// isOneBitSet - Return true if there is exactly one bit set in the specified
3287// constant.
3288static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003289 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003290}
3291
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003292// isHighOnes - Return true if the constant is of the form 1+0+.
3293// This is the same as lowones(~X).
3294static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003295 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003296}
3297
Reid Spencere4d87aa2006-12-23 06:05:41 +00003298/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003299/// are carefully arranged to allow folding of expressions such as:
3300///
3301/// (A < B) | (A > B) --> (A != B)
3302///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003303/// Note that this is only valid if the first and second predicates have the
3304/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003305///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003306/// Three bits are used to represent the condition, as follows:
3307/// 0 A > B
3308/// 1 A == B
3309/// 2 A < B
3310///
3311/// <=> Value Definition
3312/// 000 0 Always false
3313/// 001 1 A > B
3314/// 010 2 A == B
3315/// 011 3 A >= B
3316/// 100 4 A < B
3317/// 101 5 A != B
3318/// 110 6 A <= B
3319/// 111 7 Always true
3320///
3321static unsigned getICmpCode(const ICmpInst *ICI) {
3322 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003323 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003324 case ICmpInst::ICMP_UGT: return 1; // 001
3325 case ICmpInst::ICMP_SGT: return 1; // 001
3326 case ICmpInst::ICMP_EQ: return 2; // 010
3327 case ICmpInst::ICMP_UGE: return 3; // 011
3328 case ICmpInst::ICMP_SGE: return 3; // 011
3329 case ICmpInst::ICMP_ULT: return 4; // 100
3330 case ICmpInst::ICMP_SLT: return 4; // 100
3331 case ICmpInst::ICMP_NE: return 5; // 101
3332 case ICmpInst::ICMP_ULE: return 6; // 110
3333 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003334 // True -> 7
3335 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003336 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003337 return 0;
3338 }
3339}
3340
Evan Cheng8db90722008-10-14 17:15:11 +00003341/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3342/// predicate into a three bit mask. It also returns whether it is an ordered
3343/// predicate by reference.
3344static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3345 isOrdered = false;
3346 switch (CC) {
3347 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3348 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003349 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3350 case FCmpInst::FCMP_UGT: return 1; // 001
3351 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3352 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003353 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3354 case FCmpInst::FCMP_UGE: return 3; // 011
3355 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3356 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003357 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3358 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003359 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3360 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003361 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003362 default:
3363 // Not expecting FCMP_FALSE and FCMP_TRUE;
3364 assert(0 && "Unexpected FCmp predicate!");
3365 return 0;
3366 }
3367}
3368
Reid Spencere4d87aa2006-12-23 06:05:41 +00003369/// getICmpValue - This is the complement of getICmpCode, which turns an
3370/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003371/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003372/// of predicate to use in the new icmp instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003373static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3374 switch (code) {
3375 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003376 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003377 case 1:
3378 if (sign)
3379 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3380 else
3381 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3382 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3383 case 3:
3384 if (sign)
3385 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3386 else
3387 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3388 case 4:
3389 if (sign)
3390 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3391 else
3392 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3393 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3394 case 6:
3395 if (sign)
3396 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3397 else
3398 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003399 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003400 }
3401}
3402
Evan Cheng8db90722008-10-14 17:15:11 +00003403/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3404/// opcode and two operands into either a FCmp instruction. isordered is passed
3405/// in to determine which kind of predicate to use in the new fcmp instruction.
3406static Value *getFCmpValue(bool isordered, unsigned code,
3407 Value *LHS, Value *RHS) {
3408 switch (code) {
Evan Cheng4990b252008-10-14 18:13:38 +00003409 default: assert(0 && "Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003410 case 0:
3411 if (isordered)
3412 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3413 else
3414 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3415 case 1:
3416 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003417 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3418 else
3419 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003420 case 2:
3421 if (isordered)
3422 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3423 else
3424 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003425 case 3:
3426 if (isordered)
3427 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3428 else
3429 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3430 case 4:
3431 if (isordered)
3432 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3433 else
3434 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3435 case 5:
3436 if (isordered)
Evan Cheng4990b252008-10-14 18:13:38 +00003437 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3438 else
3439 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3440 case 6:
3441 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003442 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3443 else
3444 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng40300622008-10-14 18:44:08 +00003445 case 7: return ConstantInt::getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003446 }
3447}
3448
Chris Lattnerb9553d62008-11-16 04:55:20 +00003449/// PredicatesFoldable - Return true if both predicates match sign or if at
3450/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003451static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3452 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003453 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3454 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003455}
3456
3457namespace {
3458// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3459struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003460 InstCombiner &IC;
3461 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003462 ICmpInst::Predicate pred;
3463 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3464 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3465 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003466 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003467 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3468 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003469 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3470 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003471 return false;
3472 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003473 Instruction *apply(Instruction &Log) const {
3474 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3475 if (ICI->getOperand(0) != LHS) {
3476 assert(ICI->getOperand(1) == LHS);
3477 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003478 }
3479
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003480 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003481 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003482 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003483 unsigned Code;
3484 switch (Log.getOpcode()) {
3485 case Instruction::And: Code = LHSCode & RHSCode; break;
3486 case Instruction::Or: Code = LHSCode | RHSCode; break;
3487 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003488 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003489 }
3490
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003491 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3492 ICmpInst::isSignedPredicate(ICI->getPredicate());
3493
3494 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003495 if (Instruction *I = dyn_cast<Instruction>(RV))
3496 return I;
3497 // Otherwise, it's a constant boolean value...
3498 return IC.ReplaceInstUsesWith(Log, RV);
3499 }
3500};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003501} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003502
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003503// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3504// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003505// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003506Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003507 ConstantInt *OpRHS,
3508 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003509 BinaryOperator &TheAnd) {
3510 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003511 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003512 if (!Op->isShift())
Dan Gohman6de29f82009-06-15 22:12:54 +00003513 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003514
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003515 switch (Op->getOpcode()) {
3516 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003517 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003518 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003519 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003520 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003521 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003522 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003523 }
3524 break;
3525 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003526 if (Together == AndRHS) // (X | C) & C --> C
3527 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003528
Chris Lattner6e7ba452005-01-01 16:22:27 +00003529 if (Op->hasOneUse() && Together != OpRHS) {
3530 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003531 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003532 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003533 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003534 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003535 }
3536 break;
3537 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003538 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003539 // Adding a one to a single bit bit-field should be turned into an XOR
3540 // of the bit. First thing to check is to see if this AND is with a
3541 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003542 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003543
3544 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003545 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 // Ok, at this point, we know that we are masking the result of the
3547 // ADD down to exactly one bit. If the constant we are adding has
3548 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003549 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003550
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003551 // Check to see if any bits below the one bit set in AndRHSV are set.
3552 if ((AddRHS & (AndRHSV-1)) == 0) {
3553 // If not, the only thing that can effect the output of the AND is
3554 // the bit specified by AndRHSV. If that bit is set, the effect of
3555 // the XOR is to toggle the bit. If it is clear, then the ADD has
3556 // no effect.
3557 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3558 TheAnd.setOperand(0, X);
3559 return &TheAnd;
3560 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003561 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003562 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003563 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003564 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003565 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003566 }
3567 }
3568 }
3569 }
3570 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003571
3572 case Instruction::Shl: {
3573 // We know that the AND will not produce any of the bits shifted in, so if
3574 // the anded constant includes them, clear them now!
3575 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003576 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003577 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003578 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3579 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003580
Zhou Sheng290bec52007-03-29 08:15:12 +00003581 if (CI->getValue() == ShlMask) {
3582 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003583 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3584 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003585 TheAnd.setOperand(1, CI);
3586 return &TheAnd;
3587 }
3588 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003589 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003590 case Instruction::LShr:
3591 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003592 // We know that the AND will not produce any of the bits shifted in, so if
3593 // the anded constant includes them, clear them now! This only applies to
3594 // unsigned shifts, because a signed shr may bring in set bits!
3595 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003596 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003597 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003598 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3599 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003600
Zhou Sheng290bec52007-03-29 08:15:12 +00003601 if (CI->getValue() == ShrMask) {
3602 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003603 return ReplaceInstUsesWith(TheAnd, Op);
3604 } else if (CI != AndRHS) {
3605 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3606 return &TheAnd;
3607 }
3608 break;
3609 }
3610 case Instruction::AShr:
3611 // Signed shr.
3612 // See if this is shifting in some sign extension, then masking it out
3613 // with an and.
3614 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003615 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003616 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003617 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3618 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003619 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003620 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003621 // Make the argument unsigned.
3622 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003623 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003624 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003625 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003626 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003627 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003628 }
3629 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003630 }
3631 return 0;
3632}
3633
Chris Lattner8b170942002-08-09 23:47:40 +00003634
Chris Lattnera96879a2004-09-29 17:40:11 +00003635/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3636/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003637/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3638/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003639/// insert new instructions.
3640Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003641 bool isSigned, bool Inside,
3642 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003643 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003644 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003645 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003646
Chris Lattnera96879a2004-09-29 17:40:11 +00003647 if (Inside) {
3648 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003649 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003650
Reid Spencere4d87aa2006-12-23 06:05:41 +00003651 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003652 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003653 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003654 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3655 return new ICmpInst(pred, V, Hi);
3656 }
3657
3658 // Emit V-Lo <u Hi-Lo
3659 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003660 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003661 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003662 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3663 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003664 }
3665
3666 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003667 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003668
Reid Spencere4e40032007-03-21 23:19:50 +00003669 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003670 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003671 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003672 ICmpInst::Predicate pred = (isSigned ?
3673 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3674 return new ICmpInst(pred, V, Hi);
3675 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003676
Reid Spencere4e40032007-03-21 23:19:50 +00003677 // Emit V-Lo >u Hi-1-Lo
3678 // Note that Hi has already had one subtracted from it, above.
3679 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003680 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003681 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003682 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3683 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003684}
3685
Chris Lattner7203e152005-09-18 07:22:02 +00003686// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3687// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3688// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3689// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003690static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003691 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003692 uint32_t BitWidth = Val->getType()->getBitWidth();
3693 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003694
3695 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003696 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003697 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003698 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003699 return true;
3700}
3701
Chris Lattner7203e152005-09-18 07:22:02 +00003702/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3703/// where isSub determines whether the operator is a sub. If we can fold one of
3704/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003705///
3706/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3707/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3708/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3709///
3710/// return (A +/- B).
3711///
3712Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003713 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003714 Instruction &I) {
3715 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3716 if (!LHSI || LHSI->getNumOperands() != 2 ||
3717 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3718
3719 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3720
3721 switch (LHSI->getOpcode()) {
3722 default: return 0;
3723 case Instruction::And:
Dan Gohman6de29f82009-06-15 22:12:54 +00003724 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003725 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003726 if ((Mask->getValue().countLeadingZeros() +
3727 Mask->getValue().countPopulation()) ==
3728 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003729 break;
3730
3731 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3732 // part, we don't need any explicit masks to take them out of A. If that
3733 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003734 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003735 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003736 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003737 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003738 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003739 break;
3740 }
3741 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003742 return 0;
3743 case Instruction::Or:
3744 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003745 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003746 if ((Mask->getValue().countLeadingZeros() +
3747 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Dan Gohman6de29f82009-06-15 22:12:54 +00003748 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003749 break;
3750 return 0;
3751 }
3752
3753 Instruction *New;
3754 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003755 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003756 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003757 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003758 return InsertNewInstBefore(New, I);
3759}
3760
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003761/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3762Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3763 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003764 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003765 ConstantInt *LHSCst, *RHSCst;
3766 ICmpInst::Predicate LHSCC, RHSCC;
3767
Chris Lattnerea065fb2008-11-16 05:10:52 +00003768 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003769 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerea065fb2008-11-16 05:10:52 +00003770 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003771 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003772
3773 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3774 // where C is a power of 2
3775 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3776 LHSCst->getValue().isPowerOf2()) {
3777 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3778 InsertNewInstBefore(NewOr, I);
3779 return new ICmpInst(LHSCC, NewOr, LHSCst);
3780 }
3781
3782 // From here on, we only handle:
3783 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3784 if (Val != Val2) return 0;
3785
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003786 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3787 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3788 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3789 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3790 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3791 return 0;
3792
3793 // We can't fold (ugt x, C) & (sgt x, C2).
3794 if (!PredicatesFoldable(LHSCC, RHSCC))
3795 return 0;
3796
3797 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003798 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003799 if (ICmpInst::isSignedPredicate(LHSCC) ||
3800 (ICmpInst::isEquality(LHSCC) &&
3801 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003802 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003803 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003804 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3805
3806 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003807 std::swap(LHS, RHS);
3808 std::swap(LHSCst, RHSCst);
3809 std::swap(LHSCC, RHSCC);
3810 }
3811
3812 // At this point, we know we have have two icmp instructions
3813 // comparing a value against two constants and and'ing the result
3814 // together. Because of the above check, we know that we only have
3815 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3816 // (from the FoldICmpLogical check above), that the two constants
3817 // are not equal and that the larger constant is on the RHS
3818 assert(LHSCst != RHSCst && "Compares not folded above?");
3819
3820 switch (LHSCC) {
3821 default: assert(0 && "Unknown integer condition code!");
3822 case ICmpInst::ICMP_EQ:
3823 switch (RHSCC) {
3824 default: assert(0 && "Unknown integer condition code!");
3825 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3826 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3827 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3828 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3829 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3830 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3831 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3832 return ReplaceInstUsesWith(I, LHS);
3833 }
3834 case ICmpInst::ICMP_NE:
3835 switch (RHSCC) {
3836 default: assert(0 && "Unknown integer condition code!");
3837 case ICmpInst::ICMP_ULT:
3838 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3839 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3840 break; // (X != 13 & X u< 15) -> no change
3841 case ICmpInst::ICMP_SLT:
3842 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3843 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3844 break; // (X != 13 & X s< 15) -> no change
3845 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3846 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3847 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3848 return ReplaceInstUsesWith(I, RHS);
3849 case ICmpInst::ICMP_NE:
3850 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3851 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3852 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3853 Val->getName()+".off");
3854 InsertNewInstBefore(Add, I);
3855 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3856 ConstantInt::get(Add->getType(), 1));
3857 }
3858 break; // (X != 13 & X != 15) -> no change
3859 }
3860 break;
3861 case ICmpInst::ICMP_ULT:
3862 switch (RHSCC) {
3863 default: assert(0 && "Unknown integer condition code!");
3864 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3865 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3866 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3867 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3868 break;
3869 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3870 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3871 return ReplaceInstUsesWith(I, LHS);
3872 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3873 break;
3874 }
3875 break;
3876 case ICmpInst::ICMP_SLT:
3877 switch (RHSCC) {
3878 default: assert(0 && "Unknown integer condition code!");
3879 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3880 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3881 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3882 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3883 break;
3884 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3885 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3886 return ReplaceInstUsesWith(I, LHS);
3887 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3888 break;
3889 }
3890 break;
3891 case ICmpInst::ICMP_UGT:
3892 switch (RHSCC) {
3893 default: assert(0 && "Unknown integer condition code!");
3894 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3895 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3896 return ReplaceInstUsesWith(I, RHS);
3897 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3898 break;
3899 case ICmpInst::ICMP_NE:
3900 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3901 return new ICmpInst(LHSCC, Val, RHSCst);
3902 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003903 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003904 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3905 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3906 break;
3907 }
3908 break;
3909 case ICmpInst::ICMP_SGT:
3910 switch (RHSCC) {
3911 default: assert(0 && "Unknown integer condition code!");
3912 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3913 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3914 return ReplaceInstUsesWith(I, RHS);
3915 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3916 break;
3917 case ICmpInst::ICMP_NE:
3918 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3919 return new ICmpInst(LHSCC, Val, RHSCst);
3920 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003921 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003922 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3923 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3924 break;
3925 }
3926 break;
3927 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003928
3929 return 0;
3930}
3931
3932
Chris Lattner7e708292002-06-25 16:13:24 +00003933Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003934 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003935 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003936
Chris Lattnere87597f2004-10-16 18:11:37 +00003937 if (isa<UndefValue>(Op1)) // X & undef -> 0
3938 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3939
Chris Lattner6e7ba452005-01-01 16:22:27 +00003940 // and X, X = X
3941 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003942 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003943
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003944 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003945 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003946 if (SimplifyDemandedInstructionBits(I))
3947 return &I;
3948 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003949 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003950 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003951 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003952 } else if (isa<ConstantAggregateZero>(Op1)) {
3953 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003954 }
3955 }
Dan Gohman6de29f82009-06-15 22:12:54 +00003956
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003957 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003958 const APInt& AndRHSMask = AndRHS->getValue();
3959 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003960
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003961 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003962 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003963 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003964 Value *Op0LHS = Op0I->getOperand(0);
3965 Value *Op0RHS = Op0I->getOperand(1);
3966 switch (Op0I->getOpcode()) {
3967 case Instruction::Xor:
3968 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003969 // If the mask is only needed on one incoming arm, push it up.
3970 if (Op0I->hasOneUse()) {
3971 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3972 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003973 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003974 Op0RHS->getName()+".masked");
3975 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003976 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003977 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003978 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003979 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003980 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3981 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003982 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003983 Op0LHS->getName()+".masked");
3984 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003985 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003986 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3987 }
3988 }
3989
Chris Lattner6e7ba452005-01-01 16:22:27 +00003990 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003991 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003992 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3993 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3994 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3995 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003996 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003997 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003998 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003999 break;
4000
4001 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004002 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4003 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4004 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4005 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004006 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004007
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004008 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4009 // has 1's for all bits that the subtraction with A might affect.
4010 if (Op0I->hasOneUse()) {
4011 uint32_t BitWidth = AndRHSMask.getBitWidth();
4012 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4013 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4014
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004015 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004016 if (!(A && A->isZero()) && // avoid infinite recursion.
4017 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004018 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4019 InsertNewInstBefore(NewNeg, I);
4020 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4021 }
4022 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004023 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004024
4025 case Instruction::Shl:
4026 case Instruction::LShr:
4027 // (1 << x) & 1 --> zext(x == 0)
4028 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004029 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004030 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
4031 Constant::getNullValue(I.getType()));
4032 InsertNewInstBefore(NewICmp, I);
4033 return new ZExtInst(NewICmp, I.getType());
4034 }
4035 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004036 }
4037
Chris Lattner58403262003-07-23 19:25:52 +00004038 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004039 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004040 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004041 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004042 // If this is an integer truncation or change from signed-to-unsigned, and
4043 // if the source is an and/or with immediate, transform it. This
4044 // frequently occurs for bitfield accesses.
4045 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004046 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004047 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004048 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004049 if (CastOp->getOpcode() == Instruction::And) {
4050 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004051 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4052 // This will fold the two constants together, which may allow
4053 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004054 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004055 CastOp->getOperand(0), I.getType(),
4056 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004057 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004058 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00004059 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00004060 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004061 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004062 } else if (CastOp->getOpcode() == Instruction::Or) {
4063 // Change: and (cast (or X, C1) to T), C2
4064 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00004065 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00004066 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4067 return ReplaceInstUsesWith(I, AndRHS);
4068 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004069 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004070 }
Chris Lattner06782f82003-07-23 19:36:21 +00004071 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004072
4073 // Try to fold constant and into select arguments.
4074 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004075 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004076 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004077 if (isa<PHINode>(Op0))
4078 if (Instruction *NV = FoldOpIntoPhi(I))
4079 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004080 }
4081
Chris Lattner8d969642003-03-10 23:06:50 +00004082 Value *Op0NotVal = dyn_castNotVal(Op0);
4083 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004084
Chris Lattner5b62aa72004-06-18 06:07:51 +00004085 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4086 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4087
Misha Brukmancb6267b2004-07-30 12:50:08 +00004088 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004089 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004090 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004091 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004092 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004093 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004094 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004095
4096 {
Chris Lattner003b6202007-06-15 05:58:24 +00004097 Value *A = 0, *B = 0, *C = 0, *D = 0;
4098 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004099 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4100 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004101
4102 // (A|B) & ~(A&B) -> A^B
4103 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4104 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004105 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004106 }
4107 }
4108
4109 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004110 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4111 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004112
4113 // ~(A&B) & (A|B) -> A^B
4114 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4115 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004116 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004117 }
4118 }
Chris Lattner64daab52006-04-01 08:03:55 +00004119
4120 if (Op0->hasOneUse() &&
4121 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4122 if (A == Op1) { // (A^B)&A -> A&(A^B)
4123 I.swapOperands(); // Simplify below
4124 std::swap(Op0, Op1);
4125 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4126 cast<BinaryOperator>(Op0)->swapOperands();
4127 I.swapOperands(); // Simplify below
4128 std::swap(Op0, Op1);
4129 }
4130 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004131
Chris Lattner64daab52006-04-01 08:03:55 +00004132 if (Op1->hasOneUse() &&
4133 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4134 if (B == Op0) { // B&(A^B) -> B&(B^A)
4135 cast<BinaryOperator>(Op1)->swapOperands();
4136 std::swap(A, B);
4137 }
4138 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004139 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004140 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004141 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004142 }
4143 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004144
4145 // (A&((~A)|B)) -> A&B
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004146 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4147 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4148 return BinaryOperator::CreateAnd(A, Op1);
4149 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4150 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4151 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004152 }
4153
Reid Spencere4d87aa2006-12-23 06:05:41 +00004154 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4155 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4156 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004157 return R;
4158
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004159 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4160 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4161 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004162 }
4163
Chris Lattner6fc205f2006-05-05 06:39:07 +00004164 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004165 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4166 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4167 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4168 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004169 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004170 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004171 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4172 I.getType(), TD) &&
4173 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4174 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004175 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004176 Op1C->getOperand(0),
4177 I.getName());
4178 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004179 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004180 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004181 }
Chris Lattnere511b742006-11-14 07:46:50 +00004182
4183 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004184 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4185 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4186 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004187 SI0->getOperand(1) == SI1->getOperand(1) &&
4188 (SI0->hasOneUse() || SI1->hasOneUse())) {
4189 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004190 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004191 SI1->getOperand(0),
4192 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004193 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004194 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004195 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004196 }
4197
Evan Cheng8db90722008-10-14 17:15:11 +00004198 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004199 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4200 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4201 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004202 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4203 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004204 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4205 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4206 // If either of the constants are nans, then the whole thing returns
4207 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004208 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004209 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4210 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4211 RHS->getOperand(0));
4212 }
Evan Cheng8db90722008-10-14 17:15:11 +00004213 } else {
4214 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4215 FCmpInst::Predicate Op0CC, Op1CC;
4216 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4217 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Cheng4990b252008-10-14 18:13:38 +00004218 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4219 // Swap RHS operands to match LHS.
4220 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4221 std::swap(Op1LHS, Op1RHS);
4222 }
Evan Cheng8db90722008-10-14 17:15:11 +00004223 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4224 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4225 if (Op0CC == Op1CC)
4226 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4227 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4228 Op1CC == FCmpInst::FCMP_FALSE)
4229 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4230 else if (Op0CC == FCmpInst::FCMP_TRUE)
4231 return ReplaceInstUsesWith(I, Op1);
4232 else if (Op1CC == FCmpInst::FCMP_TRUE)
4233 return ReplaceInstUsesWith(I, Op0);
4234 bool Op0Ordered;
4235 bool Op1Ordered;
4236 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4237 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4238 if (Op1Pred == 0) {
4239 std::swap(Op0, Op1);
4240 std::swap(Op0Pred, Op1Pred);
4241 std::swap(Op0Ordered, Op1Ordered);
4242 }
4243 if (Op0Pred == 0) {
4244 // uno && ueq -> uno && (uno || eq) -> ueq
4245 // ord && olt -> ord && (ord && lt) -> olt
4246 if (Op0Ordered == Op1Ordered)
4247 return ReplaceInstUsesWith(I, Op1);
4248 // uno && oeq -> uno && (ord && eq) -> false
4249 // uno && ord -> false
4250 if (!Op0Ordered)
4251 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4252 // ord && ueq -> ord && (uno || eq) -> oeq
4253 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4254 Op0LHS, Op0RHS));
4255 }
4256 }
4257 }
4258 }
Chris Lattner99c65742007-10-24 05:38:08 +00004259 }
4260 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004261
Chris Lattner7e708292002-06-25 16:13:24 +00004262 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004263}
4264
Chris Lattner8c34cd22008-10-05 02:13:19 +00004265/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4266/// capable of providing pieces of a bswap. The subexpression provides pieces
4267/// of a bswap if it is proven that each of the non-zero bytes in the output of
4268/// the expression came from the corresponding "byte swapped" byte in some other
4269/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4270/// we know that the expression deposits the low byte of %X into the high byte
4271/// of the bswap result and that all other bytes are zero. This expression is
4272/// accepted, the high byte of ByteValues is set to X to indicate a correct
4273/// match.
4274///
4275/// This function returns true if the match was unsuccessful and false if so.
4276/// On entry to the function the "OverallLeftShift" is a signed integer value
4277/// indicating the number of bytes that the subexpression is later shifted. For
4278/// example, if the expression is later right shifted by 16 bits, the
4279/// OverallLeftShift value would be -2 on entry. This is used to specify which
4280/// byte of ByteValues is actually being set.
4281///
4282/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4283/// byte is masked to zero by a user. For example, in (X & 255), X will be
4284/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4285/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4286/// always in the local (OverallLeftShift) coordinate space.
4287///
4288static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4289 SmallVector<Value*, 8> &ByteValues) {
4290 if (Instruction *I = dyn_cast<Instruction>(V)) {
4291 // If this is an or instruction, it may be an inner node of the bswap.
4292 if (I->getOpcode() == Instruction::Or) {
4293 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4294 ByteValues) ||
4295 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4296 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004297 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004298
4299 // If this is a logical shift by a constant multiple of 8, recurse with
4300 // OverallLeftShift and ByteMask adjusted.
4301 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4302 unsigned ShAmt =
4303 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4304 // Ensure the shift amount is defined and of a byte value.
4305 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4306 return true;
4307
4308 unsigned ByteShift = ShAmt >> 3;
4309 if (I->getOpcode() == Instruction::Shl) {
4310 // X << 2 -> collect(X, +2)
4311 OverallLeftShift += ByteShift;
4312 ByteMask >>= ByteShift;
4313 } else {
4314 // X >>u 2 -> collect(X, -2)
4315 OverallLeftShift -= ByteShift;
4316 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004317 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004318 }
4319
4320 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4321 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4322
4323 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4324 ByteValues);
4325 }
4326
4327 // If this is a logical 'and' with a mask that clears bytes, clear the
4328 // corresponding bytes in ByteMask.
4329 if (I->getOpcode() == Instruction::And &&
4330 isa<ConstantInt>(I->getOperand(1))) {
4331 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4332 unsigned NumBytes = ByteValues.size();
4333 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4334 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4335
4336 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4337 // If this byte is masked out by a later operation, we don't care what
4338 // the and mask is.
4339 if ((ByteMask & (1 << i)) == 0)
4340 continue;
4341
4342 // If the AndMask is all zeros for this byte, clear the bit.
4343 APInt MaskB = AndMask & Byte;
4344 if (MaskB == 0) {
4345 ByteMask &= ~(1U << i);
4346 continue;
4347 }
4348
4349 // If the AndMask is not all ones for this byte, it's not a bytezap.
4350 if (MaskB != Byte)
4351 return true;
4352
4353 // Otherwise, this byte is kept.
4354 }
4355
4356 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4357 ByteValues);
4358 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004359 }
4360
Chris Lattner8c34cd22008-10-05 02:13:19 +00004361 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4362 // the input value to the bswap. Some observations: 1) if more than one byte
4363 // is demanded from this input, then it could not be successfully assembled
4364 // into a byteswap. At least one of the two bytes would not be aligned with
4365 // their ultimate destination.
4366 if (!isPowerOf2_32(ByteMask)) return true;
4367 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004368
Chris Lattner8c34cd22008-10-05 02:13:19 +00004369 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4370 // is demanded, it needs to go into byte 0 of the result. This means that the
4371 // byte needs to be shifted until it lands in the right byte bucket. The
4372 // shift amount depends on the position: if the byte is coming from the high
4373 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4374 // low part, it must be shifted left.
4375 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4376 if (InputByteNo < ByteValues.size()/2) {
4377 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4378 return true;
4379 } else {
4380 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4381 return true;
4382 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004383
4384 // If the destination byte value is already defined, the values are or'd
4385 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004386 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004387 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004388 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004389 return false;
4390}
4391
4392/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4393/// If so, insert the new bswap intrinsic and return it.
4394Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004395 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004396 if (!ITy || ITy->getBitWidth() % 16 ||
4397 // ByteMask only allows up to 32-byte values.
4398 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004399 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004400
4401 /// ByteValues - For each byte of the result, we keep track of which value
4402 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004403 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004404 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004405
4406 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004407 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4408 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004409 return 0;
4410
4411 // Check to see if all of the bytes come from the same value.
4412 Value *V = ByteValues[0];
4413 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4414
4415 // Check to make sure that all of the bytes come from the same value.
4416 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4417 if (ByteValues[i] != V)
4418 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004419 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004420 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004421 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004422 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004423}
4424
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004425/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4426/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4427/// we can simplify this expression to "cond ? C : D or B".
4428static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4429 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004430 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004431 Value *Cond = 0;
Chris Lattner159c35b2009-01-05 23:53:12 +00004432 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004433 return 0;
4434
Chris Lattnera6a474d2008-11-16 04:26:55 +00004435 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner159c35b2009-01-05 23:53:12 +00004436 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004437 return SelectInst::Create(Cond, C, B);
Chris Lattner159c35b2009-01-05 23:53:12 +00004438 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004439 return SelectInst::Create(Cond, C, B);
4440 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner159c35b2009-01-05 23:53:12 +00004441 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004442 return SelectInst::Create(Cond, C, D);
Chris Lattner159c35b2009-01-05 23:53:12 +00004443 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004444 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004445 return 0;
4446}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004447
Chris Lattner69d4ced2008-11-16 05:20:07 +00004448/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4449Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4450 ICmpInst *LHS, ICmpInst *RHS) {
4451 Value *Val, *Val2;
4452 ConstantInt *LHSCst, *RHSCst;
4453 ICmpInst::Predicate LHSCC, RHSCC;
4454
4455 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4456 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4457 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4458 return 0;
4459
4460 // From here on, we only handle:
4461 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4462 if (Val != Val2) return 0;
4463
4464 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4465 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4466 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4467 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4468 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4469 return 0;
4470
4471 // We can't fold (ugt x, C) | (sgt x, C2).
4472 if (!PredicatesFoldable(LHSCC, RHSCC))
4473 return 0;
4474
4475 // Ensure that the larger constant is on the RHS.
4476 bool ShouldSwap;
4477 if (ICmpInst::isSignedPredicate(LHSCC) ||
4478 (ICmpInst::isEquality(LHSCC) &&
4479 ICmpInst::isSignedPredicate(RHSCC)))
4480 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4481 else
4482 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4483
4484 if (ShouldSwap) {
4485 std::swap(LHS, RHS);
4486 std::swap(LHSCst, RHSCst);
4487 std::swap(LHSCC, RHSCC);
4488 }
4489
4490 // At this point, we know we have have two icmp instructions
4491 // comparing a value against two constants and or'ing the result
4492 // together. Because of the above check, we know that we only have
4493 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4494 // FoldICmpLogical check above), that the two constants are not
4495 // equal.
4496 assert(LHSCst != RHSCst && "Compares not folded above?");
4497
4498 switch (LHSCC) {
4499 default: assert(0 && "Unknown integer condition code!");
4500 case ICmpInst::ICMP_EQ:
4501 switch (RHSCC) {
4502 default: assert(0 && "Unknown integer condition code!");
4503 case ICmpInst::ICMP_EQ:
4504 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4505 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4506 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4507 Val->getName()+".off");
4508 InsertNewInstBefore(Add, I);
Dan Gohman6de29f82009-06-15 22:12:54 +00004509 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004510 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4511 }
4512 break; // (X == 13 | X == 15) -> no change
4513 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4514 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4515 break;
4516 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4517 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4518 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4519 return ReplaceInstUsesWith(I, RHS);
4520 }
4521 break;
4522 case ICmpInst::ICMP_NE:
4523 switch (RHSCC) {
4524 default: assert(0 && "Unknown integer condition code!");
4525 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4526 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4527 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4528 return ReplaceInstUsesWith(I, LHS);
4529 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4530 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4531 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4532 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4533 }
4534 break;
4535 case ICmpInst::ICMP_ULT:
4536 switch (RHSCC) {
4537 default: assert(0 && "Unknown integer condition code!");
4538 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4539 break;
4540 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4541 // If RHSCst is [us]MAXINT, it is always false. Not handling
4542 // this can cause overflow.
4543 if (RHSCst->isMaxValue(false))
4544 return ReplaceInstUsesWith(I, LHS);
4545 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4546 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4547 break;
4548 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4549 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4550 return ReplaceInstUsesWith(I, RHS);
4551 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4552 break;
4553 }
4554 break;
4555 case ICmpInst::ICMP_SLT:
4556 switch (RHSCC) {
4557 default: assert(0 && "Unknown integer condition code!");
4558 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4559 break;
4560 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4561 // If RHSCst is [us]MAXINT, it is always false. Not handling
4562 // this can cause overflow.
4563 if (RHSCst->isMaxValue(true))
4564 return ReplaceInstUsesWith(I, LHS);
4565 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4566 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4567 break;
4568 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4569 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4570 return ReplaceInstUsesWith(I, RHS);
4571 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4572 break;
4573 }
4574 break;
4575 case ICmpInst::ICMP_UGT:
4576 switch (RHSCC) {
4577 default: assert(0 && "Unknown integer condition code!");
4578 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4579 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4580 return ReplaceInstUsesWith(I, LHS);
4581 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4582 break;
4583 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4584 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4585 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4586 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4587 break;
4588 }
4589 break;
4590 case ICmpInst::ICMP_SGT:
4591 switch (RHSCC) {
4592 default: assert(0 && "Unknown integer condition code!");
4593 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4594 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4595 return ReplaceInstUsesWith(I, LHS);
4596 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4597 break;
4598 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4599 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4600 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4601 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4602 break;
4603 }
4604 break;
4605 }
4606 return 0;
4607}
4608
Bill Wendlinga698a472008-12-01 08:23:25 +00004609/// FoldOrWithConstants - This helper function folds:
4610///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004611/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004612///
4613/// into:
4614///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004615/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004616///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004617/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004618Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004619 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004620 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4621 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004622
Bill Wendling286a0542008-12-02 06:24:20 +00004623 Value *V1 = 0;
4624 ConstantInt *CI2 = 0;
4625 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004626
Bill Wendling29976b92008-12-02 06:18:11 +00004627 APInt Xor = CI1->getValue() ^ CI2->getValue();
4628 if (!Xor.isAllOnesValue()) return 0;
4629
Bill Wendling286a0542008-12-02 06:24:20 +00004630 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004631 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004632 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4633 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004634 }
4635
4636 return 0;
4637}
4638
Chris Lattner7e708292002-06-25 16:13:24 +00004639Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004640 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004641 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004642
Chris Lattner42593e62007-03-24 23:56:43 +00004643 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004644 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004645
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004646 // or X, X = X
4647 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004648 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004649
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004650 // See if we can simplify any instructions used by the instruction whose sole
4651 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004652 if (SimplifyDemandedInstructionBits(I))
4653 return &I;
4654 if (isa<VectorType>(I.getType())) {
4655 if (isa<ConstantAggregateZero>(Op1)) {
4656 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4657 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4658 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4659 return ReplaceInstUsesWith(I, I.getOperand(1));
4660 }
Chris Lattner42593e62007-03-24 23:56:43 +00004661 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004662
Chris Lattner3f5b8772002-05-06 16:14:14 +00004663 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004664 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004665 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004666 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4667 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004668 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004669 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004670 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004671 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004672 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004673 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004674
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004675 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4676 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004677 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004678 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004679 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004680 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004681 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004682 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004683
4684 // Try to fold constant and into select arguments.
4685 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004686 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004687 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004688 if (isa<PHINode>(Op0))
4689 if (Instruction *NV = FoldOpIntoPhi(I))
4690 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004691 }
4692
Chris Lattner4f637d42006-01-06 17:59:59 +00004693 Value *A = 0, *B = 0;
4694 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004695
4696 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4697 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4698 return ReplaceInstUsesWith(I, Op1);
4699 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4700 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4701 return ReplaceInstUsesWith(I, Op0);
4702
Chris Lattner6423d4c2006-07-10 20:25:24 +00004703 // (A | B) | C and A | (B | C) -> bswap if possible.
4704 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004705 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004706 match(Op1, m_Or(m_Value(), m_Value())) ||
4707 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4708 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004709 if (Instruction *BSwap = MatchBSwap(I))
4710 return BSwap;
4711 }
4712
Chris Lattner6e4c6492005-05-09 04:58:36 +00004713 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4714 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004715 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004716 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004717 InsertNewInstBefore(NOr, I);
4718 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004719 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004720 }
4721
4722 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4723 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004724 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004725 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004726 InsertNewInstBefore(NOr, I);
4727 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004728 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004729 }
4730
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004731 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004732 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004733 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4734 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004735 Value *V1 = 0, *V2 = 0, *V3 = 0;
4736 C1 = dyn_cast<ConstantInt>(C);
4737 C2 = dyn_cast<ConstantInt>(D);
4738 if (C1 && C2) { // (A & C1)|(B & C2)
4739 // If we have: ((V + N) & C1) | (V & C2)
4740 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4741 // replace with V+N.
4742 if (C1->getValue() == ~C2->getValue()) {
4743 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4744 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4745 // Add commutes, try both ways.
4746 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4747 return ReplaceInstUsesWith(I, A);
4748 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4749 return ReplaceInstUsesWith(I, A);
4750 }
4751 // Or commutes, try both ways.
4752 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4753 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4754 // Add commutes, try both ways.
4755 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4756 return ReplaceInstUsesWith(I, B);
4757 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4758 return ReplaceInstUsesWith(I, B);
4759 }
4760 }
Chris Lattner044e5332007-04-08 08:01:49 +00004761 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004762 }
4763
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004764 // Check to see if we have any common things being and'ed. If so, find the
4765 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004766 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4767 if (A == B) // (A & C)|(A & D) == A & (C|D)
4768 V1 = A, V2 = C, V3 = D;
4769 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4770 V1 = A, V2 = B, V3 = C;
4771 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4772 V1 = C, V2 = A, V3 = D;
4773 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4774 V1 = C, V2 = A, V3 = B;
4775
4776 if (V1) {
4777 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004778 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4779 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004780 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004781 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004782
Dan Gohman1975d032008-10-30 20:40:10 +00004783 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004784 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4785 return Match;
4786 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4787 return Match;
4788 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4789 return Match;
4790 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4791 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004792
Bill Wendlingb01865c2008-11-30 13:52:49 +00004793 // ((A&~B)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004794 if ((match(C, m_Not(m_Specific(D))) &&
4795 match(B, m_Not(m_Specific(A)))))
4796 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004797 // ((~B&A)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004798 if ((match(A, m_Not(m_Specific(D))) &&
4799 match(B, m_Not(m_Specific(C)))))
4800 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004801 // ((A&~B)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004802 if ((match(C, m_Not(m_Specific(B))) &&
4803 match(D, m_Not(m_Specific(A)))))
4804 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004805 // ((~B&A)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004806 if ((match(A, m_Not(m_Specific(B))) &&
4807 match(D, m_Not(m_Specific(C)))))
4808 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004809 }
Chris Lattnere511b742006-11-14 07:46:50 +00004810
4811 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004812 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4813 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4814 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004815 SI0->getOperand(1) == SI1->getOperand(1) &&
4816 (SI0->hasOneUse() || SI1->hasOneUse())) {
4817 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004818 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004819 SI1->getOperand(0),
4820 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004821 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004822 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004823 }
4824 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004825
Bill Wendlingb3833d12008-12-01 01:07:11 +00004826 // ((A|B)&1)|(B&-2) -> (A&1) | B
4827 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4828 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004829 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004830 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004831 }
4832 // (B&-2)|((A|B)&1) -> (A&1) | B
4833 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4834 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004835 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004836 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004837 }
4838
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004839 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4840 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004841 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004842 } else {
4843 A = 0;
4844 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004845 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004846 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4847 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004848 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004849
Misha Brukmancb6267b2004-07-30 12:50:08 +00004850 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004851 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004852 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004853 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004854 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004855 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004856 }
Chris Lattnera2881962003-02-18 19:28:33 +00004857
Reid Spencere4d87aa2006-12-23 06:05:41 +00004858 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4859 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4860 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004861 return R;
4862
Chris Lattner69d4ced2008-11-16 05:20:07 +00004863 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4864 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4865 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004866 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004867
4868 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004869 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004870 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004871 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004872 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4873 !isa<ICmpInst>(Op1C->getOperand(0))) {
4874 const Type *SrcTy = Op0C->getOperand(0)->getType();
4875 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4876 // Only do this if the casts both really cause code to be
4877 // generated.
4878 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4879 I.getType(), TD) &&
4880 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4881 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004882 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004883 Op1C->getOperand(0),
4884 I.getName());
4885 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004886 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004887 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004888 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004889 }
Chris Lattner99c65742007-10-24 05:38:08 +00004890 }
4891
4892
4893 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4894 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4895 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4896 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004897 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004898 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004899 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4900 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4901 // If either of the constants are nans, then the whole thing returns
4902 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004903 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004904 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4905
4906 // Otherwise, no need to compare the two constants, compare the
4907 // rest.
4908 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4909 RHS->getOperand(0));
4910 }
Evan Cheng40300622008-10-14 18:44:08 +00004911 } else {
4912 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4913 FCmpInst::Predicate Op0CC, Op1CC;
4914 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4915 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4916 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4917 // Swap RHS operands to match LHS.
4918 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4919 std::swap(Op1LHS, Op1RHS);
4920 }
4921 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4922 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4923 if (Op0CC == Op1CC)
4924 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4925 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4926 Op1CC == FCmpInst::FCMP_TRUE)
4927 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4928 else if (Op0CC == FCmpInst::FCMP_FALSE)
4929 return ReplaceInstUsesWith(I, Op1);
4930 else if (Op1CC == FCmpInst::FCMP_FALSE)
4931 return ReplaceInstUsesWith(I, Op0);
4932 bool Op0Ordered;
4933 bool Op1Ordered;
4934 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4935 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4936 if (Op0Ordered == Op1Ordered) {
4937 // If both are ordered or unordered, return a new fcmp with
4938 // or'ed predicates.
4939 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4940 Op0LHS, Op0RHS);
4941 if (Instruction *I = dyn_cast<Instruction>(RV))
4942 return I;
4943 // Otherwise, it's a constant boolean value...
4944 return ReplaceInstUsesWith(I, RV);
4945 }
4946 }
4947 }
4948 }
Chris Lattner99c65742007-10-24 05:38:08 +00004949 }
4950 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004951
Chris Lattner7e708292002-06-25 16:13:24 +00004952 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004953}
4954
Dan Gohman844731a2008-05-13 00:00:25 +00004955namespace {
4956
Chris Lattnerc317d392004-02-16 01:20:27 +00004957// XorSelf - Implements: X ^ X --> 0
4958struct XorSelf {
4959 Value *RHS;
4960 XorSelf(Value *rhs) : RHS(rhs) {}
4961 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4962 Instruction *apply(BinaryOperator &Xor) const {
4963 return &Xor;
4964 }
4965};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004966
Dan Gohman844731a2008-05-13 00:00:25 +00004967}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004968
Chris Lattner7e708292002-06-25 16:13:24 +00004969Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004970 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004972
Evan Chengd34af782008-03-25 20:07:13 +00004973 if (isa<UndefValue>(Op1)) {
4974 if (isa<UndefValue>(Op0))
4975 // Handle undef ^ undef -> 0 special case. This is a common
4976 // idiom (misuse).
4977 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004978 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004979 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004980
Chris Lattnerc317d392004-02-16 01:20:27 +00004981 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4982 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004983 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004984 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004985 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004986
4987 // See if we can simplify any instructions used by the instruction whose sole
4988 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004989 if (SimplifyDemandedInstructionBits(I))
4990 return &I;
4991 if (isa<VectorType>(I.getType()))
4992 if (isa<ConstantAggregateZero>(Op1))
4993 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00004994
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004995 // Is this a ~ operation?
4996 if (Value *NotOp = dyn_castNotVal(&I)) {
4997 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4998 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4999 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5000 if (Op0I->getOpcode() == Instruction::And ||
5001 Op0I->getOpcode() == Instruction::Or) {
5002 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5003 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5004 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005005 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005006 Op0I->getOperand(1)->getName()+".not");
5007 InsertNewInstBefore(NotY, I);
5008 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005009 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005010 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005011 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005012 }
5013 }
5014 }
5015 }
5016
5017
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005018 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005019 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005020 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005021 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005022 return new ICmpInst(ICI->getInversePredicate(),
5023 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005024
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005025 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5026 return new FCmpInst(FCI->getInversePredicate(),
5027 FCI->getOperand(0), FCI->getOperand(1));
5028 }
5029
Nick Lewycky517e1f52008-05-31 19:01:33 +00005030 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5031 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5032 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5033 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5034 Instruction::CastOps Opcode = Op0C->getOpcode();
5035 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5036 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
5037 Op0C->getDestTy())) {
5038 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5039 CI->getOpcode(), CI->getInversePredicate(),
5040 CI->getOperand(0), CI->getOperand(1)), I);
5041 NewCI->takeName(CI);
5042 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5043 }
5044 }
5045 }
5046 }
5047 }
5048
Reid Spencere4d87aa2006-12-23 06:05:41 +00005049 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005050 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005051 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5052 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00005053 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5054 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005055 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005056 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005057 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005058
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005059 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005060 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005061 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005062 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00005063 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005064 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00005065 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005066 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00005067 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005068 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005069 // (X + C) ^ signbit -> (X + C + signbit)
5070 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005071 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005072
Chris Lattner7c4049c2004-01-12 19:35:11 +00005073 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005074 } else if (Op0I->getOpcode() == Instruction::Or) {
5075 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005076 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00005077 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5078 // Anything in both C1 and C2 is known to be zero, remove it from
5079 // NewRHS.
Dan Gohman6de29f82009-06-15 22:12:54 +00005080 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005081 NewRHS = ConstantExpr::getAnd(NewRHS,
5082 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005083 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005084 I.setOperand(0, Op0I->getOperand(0));
5085 I.setOperand(1, NewRHS);
5086 return &I;
5087 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005088 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005089 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005090 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005091
5092 // Try to fold constant and into select arguments.
5093 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005094 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005095 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005096 if (isa<PHINode>(Op0))
5097 if (Instruction *NV = FoldOpIntoPhi(I))
5098 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005099 }
5100
Chris Lattner8d969642003-03-10 23:06:50 +00005101 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005102 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005103 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005104
Chris Lattner8d969642003-03-10 23:06:50 +00005105 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005106 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005107 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005108
Chris Lattner318bf792007-03-18 22:51:34 +00005109
5110 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5111 if (Op1I) {
5112 Value *A, *B;
5113 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5114 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005115 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005116 I.swapOperands();
5117 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005118 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005119 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005120 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005121 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005122 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5123 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5124 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5125 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Chris Lattner318bf792007-03-18 22:51:34 +00005126 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005127 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005128 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005129 std::swap(A, B);
5130 }
Chris Lattner318bf792007-03-18 22:51:34 +00005131 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005132 I.swapOperands(); // Simplified below.
5133 std::swap(Op0, Op1);
5134 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005135 }
Chris Lattner318bf792007-03-18 22:51:34 +00005136 }
5137
5138 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5139 if (Op0I) {
5140 Value *A, *B;
5141 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5142 if (A == Op1) // (B|A)^B == (A|B)^B
5143 std::swap(A, B);
5144 if (B == Op1) { // (A|B)^B == A & ~B
5145 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005146 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5147 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005148 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005149 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5150 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5151 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5152 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Chris Lattner318bf792007-03-18 22:51:34 +00005153 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5154 if (A == Op1) // (A&B)^A -> (B&A)^A
5155 std::swap(A, B);
5156 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005157 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005158 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005159 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5160 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005161 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005162 }
Chris Lattner318bf792007-03-18 22:51:34 +00005163 }
5164
5165 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5166 if (Op0I && Op1I && Op0I->isShift() &&
5167 Op0I->getOpcode() == Op1I->getOpcode() &&
5168 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5169 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5170 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005171 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005172 Op1I->getOperand(0),
5173 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005174 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005175 Op1I->getOperand(1));
5176 }
5177
5178 if (Op0I && Op1I) {
5179 Value *A, *B, *C, *D;
5180 // (A & B)^(A | B) -> A ^ B
5181 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5182 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5183 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005184 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005185 }
5186 // (A | B)^(A & B) -> A ^ B
5187 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5188 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5189 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005190 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005191 }
5192
5193 // (A & B)^(C & D)
5194 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5195 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5196 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5197 // (X & Y)^(X & Y) -> (Y^Z) & X
5198 Value *X = 0, *Y = 0, *Z = 0;
5199 if (A == C)
5200 X = A, Y = B, Z = D;
5201 else if (A == D)
5202 X = A, Y = B, Z = C;
5203 else if (B == C)
5204 X = B, Y = A, Z = D;
5205 else if (B == D)
5206 X = B, Y = A, Z = C;
5207
5208 if (X) {
5209 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005210 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5211 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005212 }
5213 }
5214 }
5215
Reid Spencere4d87aa2006-12-23 06:05:41 +00005216 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5217 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5218 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005219 return R;
5220
Chris Lattner6fc205f2006-05-05 06:39:07 +00005221 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005222 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005223 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005224 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5225 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005226 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005227 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005228 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5229 I.getType(), TD) &&
5230 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5231 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005232 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005233 Op1C->getOperand(0),
5234 I.getName());
5235 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005236 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005237 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005238 }
Chris Lattner99c65742007-10-24 05:38:08 +00005239 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005240
Chris Lattner7e708292002-06-25 16:13:24 +00005241 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005242}
5243
Dan Gohman6de29f82009-06-15 22:12:54 +00005244static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
5245 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5246}
Chris Lattnera96879a2004-09-29 17:40:11 +00005247
Dan Gohman6de29f82009-06-15 22:12:54 +00005248static bool HasAddOverflow(ConstantInt *Result,
5249 ConstantInt *In1, ConstantInt *In2,
5250 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005251 if (IsSigned)
5252 if (In2->getValue().isNegative())
5253 return Result->getValue().sgt(In1->getValue());
5254 else
5255 return Result->getValue().slt(In1->getValue());
5256 else
5257 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005258}
5259
Dan Gohman6de29f82009-06-15 22:12:54 +00005260/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005261/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005262static bool AddWithOverflow(Constant *&Result, Constant *In1,
5263 Constant *In2, bool IsSigned = false) {
5264 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005265
Dan Gohman6de29f82009-06-15 22:12:54 +00005266 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5267 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5268 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5269 if (HasAddOverflow(ExtractElement(Result, Idx),
5270 ExtractElement(In1, Idx),
5271 ExtractElement(In2, Idx),
5272 IsSigned))
5273 return true;
5274 }
5275 return false;
5276 }
5277
5278 return HasAddOverflow(cast<ConstantInt>(Result),
5279 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5280 IsSigned);
5281}
5282
5283static bool HasSubOverflow(ConstantInt *Result,
5284 ConstantInt *In1, ConstantInt *In2,
5285 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005286 if (IsSigned)
5287 if (In2->getValue().isNegative())
5288 return Result->getValue().slt(In1->getValue());
5289 else
5290 return Result->getValue().sgt(In1->getValue());
5291 else
5292 return Result->getValue().ugt(In1->getValue());
5293}
5294
Dan Gohman6de29f82009-06-15 22:12:54 +00005295/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5296/// overflowed for this type.
5297static bool SubWithOverflow(Constant *&Result, Constant *In1,
5298 Constant *In2, bool IsSigned = false) {
5299 Result = ConstantExpr::getSub(In1, In2);
5300
5301 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5302 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5303 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5304 if (HasSubOverflow(ExtractElement(Result, Idx),
5305 ExtractElement(In1, Idx),
5306 ExtractElement(In2, Idx),
5307 IsSigned))
5308 return true;
5309 }
5310 return false;
5311 }
5312
5313 return HasSubOverflow(cast<ConstantInt>(Result),
5314 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5315 IsSigned);
5316}
5317
Chris Lattner574da9b2005-01-13 20:14:25 +00005318/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5319/// code necessary to compute the offset from the base pointer (without adding
5320/// in the base pointer). Return the result as a signed integer of intptr size.
5321static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5322 TargetData &TD = IC.getTargetData();
5323 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005324 const Type *IntPtrTy = TD.getIntPtrType();
5325 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005326
5327 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005328 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005329 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005330
Gabor Greif177dd3f2008-06-12 21:37:33 +00005331 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5332 ++i, ++GTI) {
5333 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005334 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005335 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5336 if (OpC->isZero()) continue;
5337
5338 // Handle a struct index, which adds its field offset to the pointer.
5339 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5340 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5341
5342 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5343 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005344 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005345 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005346 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005347 ConstantInt::get(IntPtrTy, Size),
5348 GEP->getName()+".offs"), I);
5349 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005350 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005351
5352 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5353 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5354 Scale = ConstantExpr::getMul(OC, Scale);
5355 if (Constant *RC = dyn_cast<Constant>(Result))
5356 Result = ConstantExpr::getAdd(RC, Scale);
5357 else {
5358 // Emit an add instruction.
5359 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005360 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005361 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005362 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005363 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005364 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005365 // Convert to correct type.
5366 if (Op->getType() != IntPtrTy) {
5367 if (Constant *OpC = dyn_cast<Constant>(Op))
Chris Lattner62ce3b32009-04-07 05:03:34 +00005368 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005369 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005370 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5371 true,
5372 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005373 }
5374 if (Size != 1) {
5375 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5376 if (Constant *OpC = dyn_cast<Constant>(Op))
5377 Op = ConstantExpr::getMul(OpC, Scale);
5378 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005379 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005380 GEP->getName()+".idx"), I);
5381 }
5382
5383 // Emit an add instruction.
5384 if (isa<Constant>(Op) && isa<Constant>(Result))
5385 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5386 cast<Constant>(Result));
5387 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005388 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005389 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005390 }
5391 return Result;
5392}
5393
Chris Lattner10c0d912008-04-22 02:53:33 +00005394
5395/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5396/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5397/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5398/// complex, and scales are involved. The above expression would also be legal
5399/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5400/// later form is less amenable to optimization though, and we are allowed to
5401/// generate the first by knowing that pointer arithmetic doesn't overflow.
5402///
5403/// If we can't emit an optimized form for this expression, this returns null.
5404///
5405static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5406 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005407 TargetData &TD = IC.getTargetData();
5408 gep_type_iterator GTI = gep_type_begin(GEP);
5409
5410 // Check to see if this gep only has a single variable index. If so, and if
5411 // any constant indices are a multiple of its scale, then we can compute this
5412 // in terms of the scale of the variable index. For example, if the GEP
5413 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5414 // because the expression will cross zero at the same point.
5415 unsigned i, e = GEP->getNumOperands();
5416 int64_t Offset = 0;
5417 for (i = 1; i != e; ++i, ++GTI) {
5418 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5419 // Compute the aggregate offset of constant indices.
5420 if (CI->isZero()) continue;
5421
5422 // Handle a struct index, which adds its field offset to the pointer.
5423 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5424 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5425 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005426 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005427 Offset += Size*CI->getSExtValue();
5428 }
5429 } else {
5430 // Found our variable index.
5431 break;
5432 }
5433 }
5434
5435 // If there are no variable indices, we must have a constant offset, just
5436 // evaluate it the general way.
5437 if (i == e) return 0;
5438
5439 Value *VariableIdx = GEP->getOperand(i);
5440 // Determine the scale factor of the variable element. For example, this is
5441 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005442 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005443
5444 // Verify that there are no other variable indices. If so, emit the hard way.
5445 for (++i, ++GTI; i != e; ++i, ++GTI) {
5446 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5447 if (!CI) return 0;
5448
5449 // Compute the aggregate offset of constant indices.
5450 if (CI->isZero()) continue;
5451
5452 // Handle a struct index, which adds its field offset to the pointer.
5453 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5454 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5455 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005456 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005457 Offset += Size*CI->getSExtValue();
5458 }
5459 }
5460
5461 // Okay, we know we have a single variable index, which must be a
5462 // pointer/array/vector index. If there is no offset, life is simple, return
5463 // the index.
5464 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5465 if (Offset == 0) {
5466 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5467 // we don't need to bother extending: the extension won't affect where the
5468 // computation crosses zero.
5469 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5470 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5471 VariableIdx->getNameStart(), &I);
5472 return VariableIdx;
5473 }
5474
5475 // Otherwise, there is an index. The computation we will do will be modulo
5476 // the pointer size, so get it.
5477 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5478
5479 Offset &= PtrSizeMask;
5480 VariableScale &= PtrSizeMask;
5481
5482 // To do this transformation, any constant index must be a multiple of the
5483 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5484 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5485 // multiple of the variable scale.
5486 int64_t NewOffs = Offset / (int64_t)VariableScale;
5487 if (Offset != NewOffs*(int64_t)VariableScale)
5488 return 0;
5489
5490 // Okay, we can do this evaluation. Start by converting the index to intptr.
5491 const Type *IntPtrTy = TD.getIntPtrType();
5492 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005493 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005494 true /*SExt*/,
5495 VariableIdx->getNameStart(), &I);
5496 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005497 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005498}
5499
5500
Reid Spencere4d87aa2006-12-23 06:05:41 +00005501/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005502/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005503Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5504 ICmpInst::Predicate Cond,
5505 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005506 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005507
Chris Lattner10c0d912008-04-22 02:53:33 +00005508 // Look through bitcasts.
5509 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5510 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005511
Chris Lattner574da9b2005-01-13 20:14:25 +00005512 Value *PtrBase = GEPLHS->getOperand(0);
5513 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005514 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005515 // This transformation (ignoring the base and scales) is valid because we
5516 // know pointers can't overflow. See if we can output an optimized form.
5517 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5518
5519 // If not, synthesize the offset the hard way.
5520 if (Offset == 0)
5521 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005522 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5523 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005524 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005525 // If the base pointers are different, but the indices are the same, just
5526 // compare the base pointer.
5527 if (PtrBase != GEPRHS->getOperand(0)) {
5528 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005529 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005530 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005531 if (IndicesTheSame)
5532 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5533 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5534 IndicesTheSame = false;
5535 break;
5536 }
5537
5538 // If all indices are the same, just compare the base pointers.
5539 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005540 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5541 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005542
5543 // Otherwise, the base pointers are different and the indices are
5544 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005545 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005546 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005547
Chris Lattnere9d782b2005-01-13 22:25:21 +00005548 // If one of the GEPs has all zero indices, recurse.
5549 bool AllZeros = true;
5550 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5551 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5552 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5553 AllZeros = false;
5554 break;
5555 }
5556 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005557 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5558 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005559
5560 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005561 AllZeros = true;
5562 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5563 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5564 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5565 AllZeros = false;
5566 break;
5567 }
5568 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005569 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005570
Chris Lattner4401c9c2005-01-14 00:20:05 +00005571 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5572 // If the GEPs only differ by one index, compare it.
5573 unsigned NumDifferences = 0; // Keep track of # differences.
5574 unsigned DiffOperand = 0; // The operand that differs.
5575 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5576 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005577 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5578 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005579 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005580 NumDifferences = 2;
5581 break;
5582 } else {
5583 if (NumDifferences++) break;
5584 DiffOperand = i;
5585 }
5586 }
5587
5588 if (NumDifferences == 0) // SAME GEP?
5589 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005590 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005591 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005592
Chris Lattner4401c9c2005-01-14 00:20:05 +00005593 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005594 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5595 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005596 // Make sure we do a signed comparison here.
5597 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005598 }
5599 }
5600
Reid Spencere4d87aa2006-12-23 06:05:41 +00005601 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005602 // the result to fold to a constant!
5603 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5604 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5605 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5606 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5607 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005608 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005609 }
5610 }
5611 return 0;
5612}
5613
Chris Lattnera5406232008-05-19 20:18:56 +00005614/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5615///
5616Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5617 Instruction *LHSI,
5618 Constant *RHSC) {
5619 if (!isa<ConstantFP>(RHSC)) return 0;
5620 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5621
5622 // Get the width of the mantissa. We don't want to hack on conversions that
5623 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005624 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005625 if (MantissaWidth == -1) return 0; // Unknown.
5626
5627 // Check to see that the input is converted from an integer type that is small
5628 // enough that preserves all bits. TODO: check here for "known" sign bits.
5629 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00005630 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005631
5632 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005633 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5634 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005635 ++InputSize;
5636
5637 // If the conversion would lose info, don't hack on this.
5638 if ((int)InputSize > MantissaWidth)
5639 return 0;
5640
5641 // Otherwise, we can potentially simplify the comparison. We know that it
5642 // will always come through as an integer value and we know the constant is
5643 // not a NAN (it would have been previously simplified).
5644 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5645
5646 ICmpInst::Predicate Pred;
5647 switch (I.getPredicate()) {
5648 default: assert(0 && "Unexpected predicate!");
5649 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005650 case FCmpInst::FCMP_OEQ:
5651 Pred = ICmpInst::ICMP_EQ;
5652 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005653 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005654 case FCmpInst::FCMP_OGT:
5655 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5656 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005657 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005658 case FCmpInst::FCMP_OGE:
5659 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5660 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005661 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005662 case FCmpInst::FCMP_OLT:
5663 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5664 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005665 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005666 case FCmpInst::FCMP_OLE:
5667 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5668 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005669 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005670 case FCmpInst::FCMP_ONE:
5671 Pred = ICmpInst::ICMP_NE;
5672 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005673 case FCmpInst::FCMP_ORD:
Eli Friedman8b019c82008-11-30 22:48:49 +00005674 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005675 case FCmpInst::FCMP_UNO:
Eli Friedman8b019c82008-11-30 22:48:49 +00005676 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005677 }
5678
5679 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5680
5681 // Now we know that the APFloat is a normal number, zero or inf.
5682
Chris Lattner85162782008-05-20 03:50:52 +00005683 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005684 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005685 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005686
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005687 if (!LHSUnsigned) {
5688 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5689 // and large values.
5690 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5691 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5692 APFloat::rmNearestTiesToEven);
5693 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5694 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5695 Pred == ICmpInst::ICMP_SLE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005696 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5697 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005698 }
5699 } else {
5700 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5701 // +INF and large values.
5702 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5703 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5704 APFloat::rmNearestTiesToEven);
5705 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5706 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5707 Pred == ICmpInst::ICMP_ULE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005708 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5709 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005710 }
Chris Lattnera5406232008-05-19 20:18:56 +00005711 }
5712
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005713 if (!LHSUnsigned) {
5714 // See if the RHS value is < SignedMin.
5715 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5716 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5717 APFloat::rmNearestTiesToEven);
5718 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5719 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5720 Pred == ICmpInst::ICMP_SGE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005721 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5722 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005723 }
Chris Lattnera5406232008-05-19 20:18:56 +00005724 }
5725
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005726 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5727 // [0, UMAX], but it may still be fractional. See if it is fractional by
5728 // casting the FP value to the integer value and back, checking for equality.
5729 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005730 Constant *RHSInt = LHSUnsigned
5731 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5732 : ConstantExpr::getFPToSI(RHSC, IntTy);
5733 if (!RHS.isZero()) {
5734 bool Equal = LHSUnsigned
5735 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5736 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5737 if (!Equal) {
5738 // If we had a comparison against a fractional value, we have to adjust
5739 // the compare predicate and sometimes the value. RHSC is rounded towards
5740 // zero at this point.
5741 switch (Pred) {
5742 default: assert(0 && "Unexpected integer comparison!");
5743 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedman8b019c82008-11-30 22:48:49 +00005744 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005745 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5746 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5747 case ICmpInst::ICMP_ULE:
5748 // (float)int <= 4.4 --> int <= 4
5749 // (float)int <= -4.4 --> false
5750 if (RHS.isNegative())
5751 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5752 break;
5753 case ICmpInst::ICMP_SLE:
5754 // (float)int <= 4.4 --> int <= 4
5755 // (float)int <= -4.4 --> int < -4
5756 if (RHS.isNegative())
5757 Pred = ICmpInst::ICMP_SLT;
5758 break;
5759 case ICmpInst::ICMP_ULT:
5760 // (float)int < -4.4 --> false
5761 // (float)int < 4.4 --> int <= 4
5762 if (RHS.isNegative())
5763 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5764 Pred = ICmpInst::ICMP_ULE;
5765 break;
5766 case ICmpInst::ICMP_SLT:
5767 // (float)int < -4.4 --> int < -4
5768 // (float)int < 4.4 --> int <= 4
5769 if (!RHS.isNegative())
5770 Pred = ICmpInst::ICMP_SLE;
5771 break;
5772 case ICmpInst::ICMP_UGT:
5773 // (float)int > 4.4 --> int > 4
5774 // (float)int > -4.4 --> true
5775 if (RHS.isNegative())
5776 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5777 break;
5778 case ICmpInst::ICMP_SGT:
5779 // (float)int > 4.4 --> int > 4
5780 // (float)int > -4.4 --> int >= -4
5781 if (RHS.isNegative())
5782 Pred = ICmpInst::ICMP_SGE;
5783 break;
5784 case ICmpInst::ICMP_UGE:
5785 // (float)int >= -4.4 --> true
5786 // (float)int >= 4.4 --> int > 4
5787 if (!RHS.isNegative())
5788 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5789 Pred = ICmpInst::ICMP_UGT;
5790 break;
5791 case ICmpInst::ICMP_SGE:
5792 // (float)int >= -4.4 --> int >= -4
5793 // (float)int >= 4.4 --> int > 4
5794 if (!RHS.isNegative())
5795 Pred = ICmpInst::ICMP_SGT;
5796 break;
5797 }
Chris Lattnera5406232008-05-19 20:18:56 +00005798 }
5799 }
5800
5801 // Lower this FP comparison into an appropriate integer version of the
5802 // comparison.
5803 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5804}
5805
Reid Spencere4d87aa2006-12-23 06:05:41 +00005806Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5807 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005808 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005809
Chris Lattner58e97462007-01-14 19:42:17 +00005810 // Fold trivial predicates.
5811 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005812 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005813 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005814 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005815
5816 // Simplify 'fcmp pred X, X'
5817 if (Op0 == Op1) {
5818 switch (I.getPredicate()) {
5819 default: assert(0 && "Unknown predicate!");
5820 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5821 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5822 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedman8b019c82008-11-30 22:48:49 +00005823 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005824 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5825 case FCmpInst::FCMP_OLT: // True if ordered and less than
5826 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedman8b019c82008-11-30 22:48:49 +00005827 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005828
5829 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5830 case FCmpInst::FCMP_ULT: // True if unordered or less than
5831 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5832 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5833 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5834 I.setPredicate(FCmpInst::FCMP_UNO);
5835 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5836 return &I;
5837
5838 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5839 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5840 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5841 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5842 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5843 I.setPredicate(FCmpInst::FCMP_ORD);
5844 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5845 return &I;
5846 }
5847 }
5848
Reid Spencere4d87aa2006-12-23 06:05:41 +00005849 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005850 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005851
Reid Spencere4d87aa2006-12-23 06:05:41 +00005852 // Handle fcmp with constant RHS
5853 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005854 // If the constant is a nan, see if we can fold the comparison based on it.
5855 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5856 if (CFP->getValueAPF().isNaN()) {
5857 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedman8b019c82008-11-30 22:48:49 +00005858 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005859 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5860 "Comparison must be either ordered or unordered!");
5861 // True if unordered.
Eli Friedman8b019c82008-11-30 22:48:49 +00005862 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005863 }
5864 }
5865
Reid Spencere4d87aa2006-12-23 06:05:41 +00005866 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5867 switch (LHSI->getOpcode()) {
5868 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005869 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5870 // block. If in the same block, we're encouraging jump threading. If
5871 // not, we are just pessimizing the code by making an i1 phi.
5872 if (LHSI->getParent() == I.getParent())
5873 if (Instruction *NV = FoldOpIntoPhi(I))
5874 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005875 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005876 case Instruction::SIToFP:
5877 case Instruction::UIToFP:
5878 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5879 return NV;
5880 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005881 case Instruction::Select:
5882 // If either operand of the select is a constant, we can fold the
5883 // comparison into the select arms, which will cause one to be
5884 // constant folded and the select turned into a bitwise or.
5885 Value *Op1 = 0, *Op2 = 0;
5886 if (LHSI->hasOneUse()) {
5887 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5888 // Fold the known value into the constant operand.
5889 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5890 // Insert a new FCmp of the other select operand.
5891 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5892 LHSI->getOperand(2), RHSC,
5893 I.getName()), I);
5894 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5895 // Fold the known value into the constant operand.
5896 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5897 // Insert a new FCmp of the other select operand.
5898 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5899 LHSI->getOperand(1), RHSC,
5900 I.getName()), I);
5901 }
5902 }
5903
5904 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005905 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005906 break;
5907 }
5908 }
5909
5910 return Changed ? &I : 0;
5911}
5912
5913Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5914 bool Changed = SimplifyCompare(I);
5915 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5916 const Type *Ty = Op0->getType();
5917
5918 // icmp X, X
5919 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005920 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005921 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005922
5923 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005924 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005925
Reid Spencere4d87aa2006-12-23 06:05:41 +00005926 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005927 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005928 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5929 isa<ConstantPointerNull>(Op0)) &&
5930 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005931 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005932 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005933 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005934
Reid Spencere4d87aa2006-12-23 06:05:41 +00005935 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005936 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005937 switch (I.getPredicate()) {
5938 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005939 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005940 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005941 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005942 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005943 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005944 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005945 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005946
Reid Spencere4d87aa2006-12-23 06:05:41 +00005947 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005948 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005949 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005950 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005951 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005952 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005953 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005954 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005955 case ICmpInst::ICMP_SGT:
5956 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005957 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005958 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5959 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5960 InsertNewInstBefore(Not, I);
5961 return BinaryOperator::CreateAnd(Not, Op0);
5962 }
5963 case ICmpInst::ICMP_UGE:
5964 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5965 // FALL THROUGH
5966 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005967 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005968 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005969 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005970 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005971 case ICmpInst::ICMP_SGE:
5972 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5973 // FALL THROUGH
5974 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5975 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5976 InsertNewInstBefore(Not, I);
5977 return BinaryOperator::CreateOr(Not, Op0);
5978 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005979 }
Chris Lattner8b170942002-08-09 23:47:40 +00005980 }
5981
Dan Gohman1c8491e2009-04-25 17:12:48 +00005982 unsigned BitWidth = 0;
5983 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00005984 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5985 else if (Ty->isIntOrIntVector())
5986 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00005987
5988 bool isSignBit = false;
5989
Dan Gohman81b28ce2008-09-16 18:46:06 +00005990 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005991 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005992 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005993
Chris Lattnerb6566012008-01-05 01:18:20 +00005994 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5995 if (I.isEquality() && CI->isNullValue() &&
5996 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5997 // (icmp cond A B) if cond is equality
5998 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005999 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006000
Dan Gohman81b28ce2008-09-16 18:46:06 +00006001 // If we have an icmp le or icmp ge instruction, turn it into the
6002 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6003 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006004 switch (I.getPredicate()) {
6005 default: break;
6006 case ICmpInst::ICMP_ULE:
6007 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
6008 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6009 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
6010 case ICmpInst::ICMP_SLE:
6011 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
6012 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6013 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
6014 case ICmpInst::ICMP_UGE:
6015 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
6016 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6017 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
6018 case ICmpInst::ICMP_SGE:
6019 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
6020 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6021 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
6022 }
6023
Chris Lattner183661e2008-07-11 05:40:05 +00006024 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006025 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006026 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006027 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6028 }
6029
6030 // See if we can fold the comparison based on range information we can get
6031 // by checking whether bits are known to be zero or one in the input.
6032 if (BitWidth != 0) {
6033 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6034 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6035
6036 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006037 isSignBit ? APInt::getSignBit(BitWidth)
6038 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006039 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006040 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006041 if (SimplifyDemandedBits(I.getOperandUse(1),
6042 APInt::getAllOnesValue(BitWidth),
6043 Op1KnownZero, Op1KnownOne, 0))
6044 return &I;
6045
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006046 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006047 // in. Compute the Min, Max and RHS values based on the known bits. For the
6048 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006049 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6050 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6051 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6052 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6053 Op0Min, Op0Max);
6054 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6055 Op1Min, Op1Max);
6056 } else {
6057 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6058 Op0Min, Op0Max);
6059 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6060 Op1Min, Op1Max);
6061 }
6062
Chris Lattner183661e2008-07-11 05:40:05 +00006063 // If Min and Max are known to be the same, then SimplifyDemandedBits
6064 // figured out that the LHS is a constant. Just constant fold this now so
6065 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006066 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6067 return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
6068 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6069 return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
6070
Chris Lattner183661e2008-07-11 05:40:05 +00006071 // Based on the range information we know about the LHS, see if we can
6072 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006073 switch (I.getPredicate()) {
Chris Lattner84dff672008-07-11 05:08:55 +00006074 default: assert(0 && "Unknown icmp opcode!");
6075 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006076 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner84dff672008-07-11 05:08:55 +00006077 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6078 break;
6079 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006080 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner84dff672008-07-11 05:08:55 +00006081 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6082 break;
6083 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006084 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006085 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006086 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006087 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006088 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Chris Lattner183661e2008-07-11 05:40:05 +00006089 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006090 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6091 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6092 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6093
6094 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6095 if (CI->isMinValue(true))
6096 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Chris Lattner183661e2008-07-11 05:40:05 +00006097 ConstantInt::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006098 }
Chris Lattner84dff672008-07-11 05:08:55 +00006099 break;
6100 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006101 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006102 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006103 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006104 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006105
6106 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Chris Lattner183661e2008-07-11 05:40:05 +00006107 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006108 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6109 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6110 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6111
6112 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6113 if (CI->isMaxValue(true))
6114 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6115 ConstantInt::getNullValue(Op0->getType()));
6116 }
Chris Lattner84dff672008-07-11 05:08:55 +00006117 break;
6118 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006119 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Chris Lattner84dff672008-07-11 05:08:55 +00006120 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006121 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Chris Lattner84dff672008-07-11 05:08:55 +00006122 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006123 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Chris Lattner183661e2008-07-11 05:40:05 +00006124 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006125 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6126 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6127 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6128 }
Chris Lattner84dff672008-07-11 05:08:55 +00006129 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006130 case ICmpInst::ICMP_SGT:
6131 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006132 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006133 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006134 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006135
6136 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Chris Lattner183661e2008-07-11 05:40:05 +00006137 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006138 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6139 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6140 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6141 }
6142 break;
6143 case ICmpInst::ICMP_SGE:
6144 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6145 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6146 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6147 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6148 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6149 break;
6150 case ICmpInst::ICMP_SLE:
6151 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6152 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6153 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6154 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6155 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6156 break;
6157 case ICmpInst::ICMP_UGE:
6158 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6159 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6160 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6161 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6162 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6163 break;
6164 case ICmpInst::ICMP_ULE:
6165 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6166 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6167 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6168 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6169 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006170 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006171 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006172
6173 // Turn a signed comparison into an unsigned one if both operands
6174 // are known to have the same sign.
6175 if (I.isSignedPredicate() &&
6176 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6177 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6178 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006179 }
6180
6181 // Test if the ICmpInst instruction is used exclusively by a select as
6182 // part of a minimum or maximum operation. If so, refrain from doing
6183 // any other folding. This helps out other analyses which understand
6184 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6185 // and CodeGen. And in this case, at least one of the comparison
6186 // operands has at least one user besides the compare (the select),
6187 // which would often largely negate the benefit of folding anyway.
6188 if (I.hasOneUse())
6189 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6190 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6191 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6192 return 0;
6193
6194 // See if we are doing a comparison between a constant and an instruction that
6195 // can be folded into the comparison.
6196 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006197 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006198 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006199 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006200 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006201 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6202 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006203 }
6204
Chris Lattner01deb9d2007-04-03 17:43:25 +00006205 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006206 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6207 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6208 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006209 case Instruction::GetElementPtr:
6210 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006211 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006212 bool isAllZeros = true;
6213 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6214 if (!isa<Constant>(LHSI->getOperand(i)) ||
6215 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6216 isAllZeros = false;
6217 break;
6218 }
6219 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006220 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00006221 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6222 }
6223 break;
6224
Chris Lattner6970b662005-04-23 15:31:55 +00006225 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006226 // Only fold icmp into the PHI if the phi and fcmp are in the same
6227 // block. If in the same block, we're encouraging jump threading. If
6228 // not, we are just pessimizing the code by making an i1 phi.
6229 if (LHSI->getParent() == I.getParent())
6230 if (Instruction *NV = FoldOpIntoPhi(I))
6231 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006232 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006233 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006234 // If either operand of the select is a constant, we can fold the
6235 // comparison into the select arms, which will cause one to be
6236 // constant folded and the select turned into a bitwise or.
6237 Value *Op1 = 0, *Op2 = 0;
6238 if (LHSI->hasOneUse()) {
6239 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6240 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006241 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6242 // Insert a new ICmp of the other select operand.
6243 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6244 LHSI->getOperand(2), RHSC,
6245 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006246 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6247 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006248 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6249 // Insert a new ICmp of the other select operand.
6250 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6251 LHSI->getOperand(1), RHSC,
6252 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006253 }
6254 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006255
Chris Lattner6970b662005-04-23 15:31:55 +00006256 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006257 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006258 break;
6259 }
Chris Lattner4802d902007-04-06 18:57:34 +00006260 case Instruction::Malloc:
6261 // If we have (malloc != null), and if the malloc has a single use, we
6262 // can assume it is successful and remove the malloc.
6263 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6264 AddToWorkList(LHSI);
6265 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006266 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006267 }
6268 break;
6269 }
Chris Lattner6970b662005-04-23 15:31:55 +00006270 }
6271
Reid Spencere4d87aa2006-12-23 06:05:41 +00006272 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006273 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006274 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006275 return NI;
6276 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006277 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6278 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006279 return NI;
6280
Reid Spencere4d87aa2006-12-23 06:05:41 +00006281 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006282 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6283 // now.
6284 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6285 if (isa<PointerType>(Op0->getType()) &&
6286 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006287 // We keep moving the cast from the left operand over to the right
6288 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006289 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006290
Chris Lattner57d86372007-01-06 01:45:59 +00006291 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6292 // so eliminate it as well.
6293 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6294 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006295
Chris Lattnerde90b762003-11-03 04:25:02 +00006296 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006297 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006298 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006299 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006300 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006301 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006302 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006303 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006304 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006305 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006306 }
Chris Lattner57d86372007-01-06 01:45:59 +00006307 }
6308
6309 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006310 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006311 // This comes up when you have code like
6312 // int X = A < B;
6313 // if (X) ...
6314 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006315 // with a constant or another cast from the same type.
6316 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006317 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006318 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006319 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006320
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006321 // See if it's the same type of instruction on the left and right.
6322 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6323 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006324 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006325 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006326 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006327 default: break;
6328 case Instruction::Add:
6329 case Instruction::Sub:
6330 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006331 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Nick Lewycky4333f492009-01-31 21:30:05 +00006332 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6333 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006334 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6335 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6336 if (CI->getValue().isSignBit()) {
6337 ICmpInst::Predicate Pred = I.isSignedPredicate()
6338 ? I.getUnsignedPredicate()
6339 : I.getSignedPredicate();
6340 return new ICmpInst(Pred, Op0I->getOperand(0),
6341 Op1I->getOperand(0));
6342 }
6343
6344 if (CI->getValue().isMaxSignedValue()) {
6345 ICmpInst::Predicate Pred = I.isSignedPredicate()
6346 ? I.getUnsignedPredicate()
6347 : I.getSignedPredicate();
6348 Pred = I.getSwappedPredicate(Pred);
6349 return new ICmpInst(Pred, Op0I->getOperand(0),
6350 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006351 }
6352 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006353 break;
6354 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006355 if (!I.isEquality())
6356 break;
6357
Nick Lewycky5d52c452008-08-21 05:56:10 +00006358 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6359 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6360 // Mask = -1 >> count-trailing-zeros(Cst).
6361 if (!CI->isZero() && !CI->isOne()) {
6362 const APInt &AP = CI->getValue();
6363 ConstantInt *Mask = ConstantInt::get(
6364 APInt::getLowBitsSet(AP.getBitWidth(),
6365 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006366 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006367 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6368 Mask);
6369 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6370 Mask);
6371 InsertNewInstBefore(And1, I);
6372 InsertNewInstBefore(And2, I);
6373 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006374 }
6375 }
6376 break;
6377 }
6378 }
6379 }
6380 }
6381
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006382 // ~x < ~y --> y < x
6383 { Value *A, *B;
6384 if (match(Op0, m_Not(m_Value(A))) &&
6385 match(Op1, m_Not(m_Value(B))))
6386 return new ICmpInst(I.getPredicate(), B, A);
6387 }
6388
Chris Lattner65b72ba2006-09-18 04:22:48 +00006389 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006390 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006391
6392 // -x == -y --> x == y
6393 if (match(Op0, m_Neg(m_Value(A))) &&
6394 match(Op1, m_Neg(m_Value(B))))
6395 return new ICmpInst(I.getPredicate(), A, B);
6396
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006397 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6398 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6399 Value *OtherVal = A == Op1 ? B : A;
6400 return new ICmpInst(I.getPredicate(), OtherVal,
6401 Constant::getNullValue(A->getType()));
6402 }
6403
6404 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6405 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006406 ConstantInt *C1, *C2;
6407 if (match(B, m_ConstantInt(C1)) &&
6408 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6409 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6410 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6411 return new ICmpInst(I.getPredicate(), A,
6412 InsertNewInstBefore(Xor, I));
6413 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006414
6415 // A^B == A^D -> B == D
6416 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6417 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6418 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6419 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6420 }
6421 }
6422
6423 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6424 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006425 // A == (A^B) -> B == 0
6426 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006427 return new ICmpInst(I.getPredicate(), OtherVal,
6428 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006429 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006430
6431 // (A-B) == A -> B == 0
6432 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6433 return new ICmpInst(I.getPredicate(), B,
6434 Constant::getNullValue(B->getType()));
6435
6436 // A == (A-B) -> B == 0
6437 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006438 return new ICmpInst(I.getPredicate(), B,
6439 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006440
Chris Lattner9c2328e2006-11-14 06:06:06 +00006441 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6442 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6443 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6444 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6445 Value *X = 0, *Y = 0, *Z = 0;
6446
6447 if (A == C) {
6448 X = B; Y = D; Z = A;
6449 } else if (A == D) {
6450 X = B; Y = C; Z = A;
6451 } else if (B == C) {
6452 X = A; Y = D; Z = B;
6453 } else if (B == D) {
6454 X = A; Y = C; Z = B;
6455 }
6456
6457 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006458 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6459 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006460 I.setOperand(0, Op1);
6461 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6462 return &I;
6463 }
6464 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006465 }
Chris Lattner7e708292002-06-25 16:13:24 +00006466 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006467}
6468
Chris Lattner562ef782007-06-20 23:46:26 +00006469
6470/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6471/// and CmpRHS are both known to be integer constants.
6472Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6473 ConstantInt *DivRHS) {
6474 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6475 const APInt &CmpRHSV = CmpRHS->getValue();
6476
6477 // FIXME: If the operand types don't match the type of the divide
6478 // then don't attempt this transform. The code below doesn't have the
6479 // logic to deal with a signed divide and an unsigned compare (and
6480 // vice versa). This is because (x /s C1) <s C2 produces different
6481 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6482 // (x /u C1) <u C2. Simply casting the operands and result won't
6483 // work. :( The if statement below tests that condition and bails
6484 // if it finds it.
6485 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6486 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6487 return 0;
6488 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006489 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006490 if (DivIsSigned && DivRHS->isAllOnesValue())
6491 return 0; // The overflow computation also screws up here
6492 if (DivRHS->isOne())
6493 return 0; // Not worth bothering, and eliminates some funny cases
6494 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006495
6496 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6497 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6498 // C2 (CI). By solving for X we can turn this into a range check
6499 // instead of computing a divide.
Dan Gohman6de29f82009-06-15 22:12:54 +00006500 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006501
6502 // Determine if the product overflows by seeing if the product is
6503 // not equal to the divide. Make sure we do the same kind of divide
6504 // as in the LHS instruction that we're folding.
6505 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6506 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6507
6508 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006509 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006510
Chris Lattner1dbfd482007-06-21 18:11:19 +00006511 // Figure out the interval that is being checked. For example, a comparison
6512 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6513 // Compute this interval based on the constants involved and the signedness of
6514 // the compare/divide. This computes a half-open interval, keeping track of
6515 // whether either value in the interval overflows. After analysis each
6516 // overflow variable is set to 0 if it's corresponding bound variable is valid
6517 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6518 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006519 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006520
Chris Lattner562ef782007-06-20 23:46:26 +00006521 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006522 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006523 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006524 HiOverflow = LoOverflow = ProdOV;
6525 if (!HiOverflow)
6526 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006527 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006528 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006529 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006530 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6531 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006532 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006533 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6534 HiOverflow = LoOverflow = ProdOV;
6535 if (!HiOverflow)
6536 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006537 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006538 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006539 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006540 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6541 if (!LoOverflow) {
6542 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6543 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6544 true) ? -1 : 0;
6545 }
Chris Lattner562ef782007-06-20 23:46:26 +00006546 }
Dan Gohman76491272008-02-13 22:09:18 +00006547 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006548 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006549 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006550 LoBound = AddOne(DivRHS);
6551 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006552 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6553 HiOverflow = 1; // [INTMIN+1, overflow)
6554 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6555 }
Dan Gohman76491272008-02-13 22:09:18 +00006556 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006557 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnera6321b42008-10-11 22:55:00 +00006558 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006559 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006560 if (!LoOverflow)
Chris Lattnera6321b42008-10-11 22:55:00 +00006561 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006562 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006563 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6564 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006565 if (!HiOverflow)
6566 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006567 }
6568
Chris Lattner1dbfd482007-06-21 18:11:19 +00006569 // Dividing by a negative swaps the condition. LT <-> GT
6570 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006571 }
6572
6573 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006574 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006575 default: assert(0 && "Unhandled icmp opcode!");
6576 case ICmpInst::ICMP_EQ:
6577 if (LoOverflow && HiOverflow)
6578 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6579 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006580 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006581 ICmpInst::ICMP_UGE, X, LoBound);
6582 else if (LoOverflow)
6583 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6584 ICmpInst::ICMP_ULT, X, HiBound);
6585 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006586 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006587 case ICmpInst::ICMP_NE:
6588 if (LoOverflow && HiOverflow)
6589 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6590 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006591 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006592 ICmpInst::ICMP_ULT, X, LoBound);
6593 else if (LoOverflow)
6594 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6595 ICmpInst::ICMP_UGE, X, HiBound);
6596 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006597 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006598 case ICmpInst::ICMP_ULT:
6599 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006600 if (LoOverflow == +1) // Low bound is greater than input range.
6601 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6602 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006603 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006604 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006605 case ICmpInst::ICMP_UGT:
6606 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006607 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006608 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006609 else if (HiOverflow == -1) // High bound less than input range.
6610 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6611 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006612 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6613 else
6614 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6615 }
6616}
6617
6618
Chris Lattner01deb9d2007-04-03 17:43:25 +00006619/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6620///
6621Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6622 Instruction *LHSI,
6623 ConstantInt *RHS) {
6624 const APInt &RHSV = RHS->getValue();
6625
6626 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006627 case Instruction::Trunc:
6628 if (ICI.isEquality() && LHSI->hasOneUse()) {
6629 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6630 // of the high bits truncated out of x are known.
6631 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6632 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6633 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6634 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6635 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6636
6637 // If all the high bits are known, we can do this xform.
6638 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6639 // Pull in the high bits from known-ones set.
6640 APInt NewRHS(RHS->getValue());
6641 NewRHS.zext(SrcBits);
6642 NewRHS |= KnownOne;
6643 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6644 ConstantInt::get(NewRHS));
6645 }
6646 }
6647 break;
6648
Duncan Sands0091bf22007-04-04 06:42:45 +00006649 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006650 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6651 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6652 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006653 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6654 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006655 Value *CompareVal = LHSI->getOperand(0);
6656
6657 // If the sign bit of the XorCST is not set, there is no change to
6658 // the operation, just stop using the Xor.
6659 if (!XorCST->getValue().isNegative()) {
6660 ICI.setOperand(0, CompareVal);
6661 AddToWorkList(LHSI);
6662 return &ICI;
6663 }
6664
6665 // Was the old condition true if the operand is positive?
6666 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6667
6668 // If so, the new one isn't.
6669 isTrueIfPositive ^= true;
6670
6671 if (isTrueIfPositive)
6672 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6673 else
6674 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6675 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006676
6677 if (LHSI->hasOneUse()) {
6678 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6679 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6680 const APInt &SignBit = XorCST->getValue();
6681 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6682 ? ICI.getUnsignedPredicate()
6683 : ICI.getSignedPredicate();
6684 return new ICmpInst(Pred, LHSI->getOperand(0),
6685 ConstantInt::get(RHSV ^ SignBit));
6686 }
6687
6688 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006689 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006690 const APInt &NotSignBit = XorCST->getValue();
6691 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6692 ? ICI.getUnsignedPredicate()
6693 : ICI.getSignedPredicate();
6694 Pred = ICI.getSwappedPredicate(Pred);
6695 return new ICmpInst(Pred, LHSI->getOperand(0),
6696 ConstantInt::get(RHSV ^ NotSignBit));
6697 }
6698 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006699 }
6700 break;
6701 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6702 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6703 LHSI->getOperand(0)->hasOneUse()) {
6704 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6705
6706 // If the LHS is an AND of a truncating cast, we can widen the
6707 // and/compare to be the input width without changing the value
6708 // produced, eliminating a cast.
6709 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6710 // We can do this transformation if either the AND constant does not
6711 // have its sign bit set or if it is an equality comparison.
6712 // Extending a relational comparison when we're checking the sign
6713 // bit would not work.
6714 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006715 (ICI.isEquality() ||
6716 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006717 uint32_t BitWidth =
6718 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6719 APInt NewCST = AndCST->getValue();
6720 NewCST.zext(BitWidth);
6721 APInt NewCI = RHSV;
6722 NewCI.zext(BitWidth);
6723 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006724 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006725 ConstantInt::get(NewCST),LHSI->getName());
6726 InsertNewInstBefore(NewAnd, ICI);
6727 return new ICmpInst(ICI.getPredicate(), NewAnd,
6728 ConstantInt::get(NewCI));
6729 }
6730 }
6731
6732 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6733 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6734 // happens a LOT in code produced by the C front-end, for bitfield
6735 // access.
6736 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6737 if (Shift && !Shift->isShift())
6738 Shift = 0;
6739
6740 ConstantInt *ShAmt;
6741 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6742 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6743 const Type *AndTy = AndCST->getType(); // Type of the and.
6744
6745 // We can fold this as long as we can't shift unknown bits
6746 // into the mask. This can only happen with signed shift
6747 // rights, as they sign-extend.
6748 if (ShAmt) {
6749 bool CanFold = Shift->isLogicalShift();
6750 if (!CanFold) {
6751 // To test for the bad case of the signed shr, see if any
6752 // of the bits shifted in could be tested after the mask.
6753 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6754 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6755
6756 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6757 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6758 AndCST->getValue()) == 0)
6759 CanFold = true;
6760 }
6761
6762 if (CanFold) {
6763 Constant *NewCst;
6764 if (Shift->getOpcode() == Instruction::Shl)
6765 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6766 else
6767 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6768
6769 // Check to see if we are shifting out any of the bits being
6770 // compared.
6771 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6772 // If we shifted bits out, the fold is not going to work out.
6773 // As a special case, check to see if this means that the
6774 // result is always true or false now.
6775 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6776 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6777 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6778 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6779 } else {
6780 ICI.setOperand(1, NewCst);
6781 Constant *NewAndCST;
6782 if (Shift->getOpcode() == Instruction::Shl)
6783 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6784 else
6785 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6786 LHSI->setOperand(1, NewAndCST);
6787 LHSI->setOperand(0, Shift->getOperand(0));
6788 AddToWorkList(Shift); // Shift is dead.
6789 AddUsesToWorkList(ICI);
6790 return &ICI;
6791 }
6792 }
6793 }
6794
6795 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6796 // preferable because it allows the C<<Y expression to be hoisted out
6797 // of a loop if Y is invariant and X is not.
6798 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006799 ICI.isEquality() && !Shift->isArithmeticShift() &&
6800 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006801 // Compute C << Y.
6802 Value *NS;
6803 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006804 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006805 Shift->getOperand(1), "tmp");
6806 } else {
6807 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006808 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006809 Shift->getOperand(1), "tmp");
6810 }
6811 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6812
6813 // Compute X & (C << Y).
6814 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006815 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006816 InsertNewInstBefore(NewAnd, ICI);
6817
6818 ICI.setOperand(0, NewAnd);
6819 return &ICI;
6820 }
6821 }
6822 break;
6823
Chris Lattnera0141b92007-07-15 20:42:37 +00006824 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6825 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6826 if (!ShAmt) break;
6827
6828 uint32_t TypeBits = RHSV.getBitWidth();
6829
6830 // Check that the shift amount is in range. If not, don't perform
6831 // undefined shifts. When the shift is visited it will be
6832 // simplified.
6833 if (ShAmt->uge(TypeBits))
6834 break;
6835
6836 if (ICI.isEquality()) {
6837 // If we are comparing against bits always shifted out, the
6838 // comparison cannot succeed.
6839 Constant *Comp =
6840 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6841 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6842 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6843 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6844 return ReplaceInstUsesWith(ICI, Cst);
6845 }
6846
6847 if (LHSI->hasOneUse()) {
6848 // Otherwise strength reduce the shift into an and.
6849 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6850 Constant *Mask =
6851 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006852
Chris Lattnera0141b92007-07-15 20:42:37 +00006853 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006854 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006855 Mask, LHSI->getName()+".mask");
6856 Value *And = InsertNewInstBefore(AndI, ICI);
6857 return new ICmpInst(ICI.getPredicate(), And,
6858 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006859 }
6860 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006861
6862 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6863 bool TrueIfSigned = false;
6864 if (LHSI->hasOneUse() &&
6865 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6866 // (X << 31) <s 0 --> (X&1) != 0
6867 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6868 (TypeBits-ShAmt->getZExtValue()-1));
6869 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006870 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006871 Mask, LHSI->getName()+".mask");
6872 Value *And = InsertNewInstBefore(AndI, ICI);
6873
6874 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6875 And, Constant::getNullValue(And->getType()));
6876 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006877 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006878 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006879
6880 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006881 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006882 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006883 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006884 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006885
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006886 // Check that the shift amount is in range. If not, don't perform
6887 // undefined shifts. When the shift is visited it will be
6888 // simplified.
6889 uint32_t TypeBits = RHSV.getBitWidth();
6890 if (ShAmt->uge(TypeBits))
6891 break;
6892
6893 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006894
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006895 // If we are comparing against bits always shifted out, the
6896 // comparison cannot succeed.
6897 APInt Comp = RHSV << ShAmtVal;
6898 if (LHSI->getOpcode() == Instruction::LShr)
6899 Comp = Comp.lshr(ShAmtVal);
6900 else
6901 Comp = Comp.ashr(ShAmtVal);
6902
6903 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6904 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6905 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6906 return ReplaceInstUsesWith(ICI, Cst);
6907 }
6908
6909 // Otherwise, check to see if the bits shifted out are known to be zero.
6910 // If so, we can compare against the unshifted value:
6911 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006912 if (LHSI->hasOneUse() &&
6913 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006914 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6915 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6916 ConstantExpr::getShl(RHS, ShAmt));
6917 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006918
Evan Chengf30752c2008-04-23 00:38:06 +00006919 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006920 // Otherwise strength reduce the shift into an and.
6921 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6922 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006923
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006924 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006925 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006926 Mask, LHSI->getName()+".mask");
6927 Value *And = InsertNewInstBefore(AndI, ICI);
6928 return new ICmpInst(ICI.getPredicate(), And,
6929 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006930 }
6931 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006932 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006933
6934 case Instruction::SDiv:
6935 case Instruction::UDiv:
6936 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6937 // Fold this div into the comparison, producing a range check.
6938 // Determine, based on the divide type, what the range is being
6939 // checked. If there is an overflow on the low or high side, remember
6940 // it, otherwise compute the range [low, hi) bounding the new value.
6941 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006942 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6943 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6944 DivRHS))
6945 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006946 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006947
6948 case Instruction::Add:
6949 // Fold: icmp pred (add, X, C1), C2
6950
6951 if (!ICI.isEquality()) {
6952 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6953 if (!LHSC) break;
6954 const APInt &LHSV = LHSC->getValue();
6955
6956 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6957 .subtract(LHSV);
6958
6959 if (ICI.isSignedPredicate()) {
6960 if (CR.getLower().isSignBit()) {
6961 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6962 ConstantInt::get(CR.getUpper()));
6963 } else if (CR.getUpper().isSignBit()) {
6964 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6965 ConstantInt::get(CR.getLower()));
6966 }
6967 } else {
6968 if (CR.getLower().isMinValue()) {
6969 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6970 ConstantInt::get(CR.getUpper()));
6971 } else if (CR.getUpper().isMinValue()) {
6972 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6973 ConstantInt::get(CR.getLower()));
6974 }
6975 }
6976 }
6977 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006978 }
6979
6980 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6981 if (ICI.isEquality()) {
6982 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6983
6984 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6985 // the second operand is a constant, simplify a bit.
6986 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6987 switch (BO->getOpcode()) {
6988 case Instruction::SRem:
6989 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6990 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6991 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6992 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6993 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006994 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006995 BO->getName());
6996 InsertNewInstBefore(NewRem, ICI);
6997 return new ICmpInst(ICI.getPredicate(), NewRem,
6998 Constant::getNullValue(BO->getType()));
6999 }
7000 }
7001 break;
7002 case Instruction::Add:
7003 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7004 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7005 if (BO->hasOneUse())
7006 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohman6de29f82009-06-15 22:12:54 +00007007 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007008 } else if (RHSV == 0) {
7009 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7010 // efficiently invertible, or if the add has just this one use.
7011 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7012
7013 if (Value *NegVal = dyn_castNegVal(BOp1))
7014 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7015 else if (Value *NegVal = dyn_castNegVal(BOp0))
7016 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7017 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007018 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007019 InsertNewInstBefore(Neg, ICI);
7020 Neg->takeName(BO);
7021 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7022 }
7023 }
7024 break;
7025 case Instruction::Xor:
7026 // For the xor case, we can xor two constants together, eliminating
7027 // the explicit xor.
7028 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7029 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7030 ConstantExpr::getXor(RHS, BOC));
7031
7032 // FALLTHROUGH
7033 case Instruction::Sub:
7034 // Replace (([sub|xor] A, B) != 0) with (A != B)
7035 if (RHSV == 0)
7036 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7037 BO->getOperand(1));
7038 break;
7039
7040 case Instruction::Or:
7041 // If bits are being or'd in that are not present in the constant we
7042 // are comparing against, then the comparison could never succeed!
7043 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7044 Constant *NotCI = ConstantExpr::getNot(RHS);
7045 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7046 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7047 isICMP_NE));
7048 }
7049 break;
7050
7051 case Instruction::And:
7052 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7053 // If bits are being compared against that are and'd out, then the
7054 // comparison can never succeed!
7055 if ((RHSV & ~BOC->getValue()) != 0)
7056 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7057 isICMP_NE));
7058
7059 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7060 if (RHS == BOC && RHSV.isPowerOf2())
7061 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7062 ICmpInst::ICMP_NE, LHSI,
7063 Constant::getNullValue(RHS->getType()));
7064
7065 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007066 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007067 Value *X = BO->getOperand(0);
7068 Constant *Zero = Constant::getNullValue(X->getType());
7069 ICmpInst::Predicate pred = isICMP_NE ?
7070 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7071 return new ICmpInst(pred, X, Zero);
7072 }
7073
7074 // ((X & ~7) == 0) --> X < 8
7075 if (RHSV == 0 && isHighOnes(BOC)) {
7076 Value *X = BO->getOperand(0);
7077 Constant *NegX = ConstantExpr::getNeg(BOC);
7078 ICmpInst::Predicate pred = isICMP_NE ?
7079 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7080 return new ICmpInst(pred, X, NegX);
7081 }
7082 }
7083 default: break;
7084 }
7085 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7086 // Handle icmp {eq|ne} <intrinsic>, intcst.
7087 if (II->getIntrinsicID() == Intrinsic::bswap) {
7088 AddToWorkList(II);
7089 ICI.setOperand(0, II->getOperand(1));
7090 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
7091 return &ICI;
7092 }
7093 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007094 }
7095 return 0;
7096}
7097
7098/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7099/// We only handle extending casts so far.
7100///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007101Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7102 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007103 Value *LHSCIOp = LHSCI->getOperand(0);
7104 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007105 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007106 Value *RHSCIOp;
7107
Chris Lattner8c756c12007-05-05 22:41:33 +00007108 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7109 // integer type is the same size as the pointer type.
7110 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7111 getTargetData().getPointerSizeInBits() ==
7112 cast<IntegerType>(DestTy)->getBitWidth()) {
7113 Value *RHSOp = 0;
7114 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00007115 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007116 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7117 RHSOp = RHSC->getOperand(0);
7118 // If the pointer types don't match, insert a bitcast.
7119 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007120 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007121 }
7122
7123 if (RHSOp)
7124 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7125 }
7126
7127 // The code below only handles extension cast instructions, so far.
7128 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007129 if (LHSCI->getOpcode() != Instruction::ZExt &&
7130 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007131 return 0;
7132
Reid Spencere4d87aa2006-12-23 06:05:41 +00007133 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7134 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007135
Reid Spencere4d87aa2006-12-23 06:05:41 +00007136 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007137 // Not an extension from the same type?
7138 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007139 if (RHSCIOp->getType() != LHSCIOp->getType())
7140 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007141
Nick Lewycky4189a532008-01-28 03:48:02 +00007142 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007143 // and the other is a zext), then we can't handle this.
7144 if (CI->getOpcode() != LHSCI->getOpcode())
7145 return 0;
7146
Nick Lewycky4189a532008-01-28 03:48:02 +00007147 // Deal with equality cases early.
7148 if (ICI.isEquality())
7149 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7150
7151 // A signed comparison of sign extended values simplifies into a
7152 // signed comparison.
7153 if (isSignedCmp && isSignedExt)
7154 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7155
7156 // The other three cases all fold into an unsigned comparison.
7157 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007158 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007159
Reid Spencere4d87aa2006-12-23 06:05:41 +00007160 // If we aren't dealing with a constant on the RHS, exit early
7161 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7162 if (!CI)
7163 return 0;
7164
7165 // Compute the constant that would happen if we truncated to SrcTy then
7166 // reextended to DestTy.
7167 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7168 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7169
7170 // If the re-extended constant didn't change...
7171 if (Res2 == CI) {
7172 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7173 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007174 // %A = sext i16 %X to i32
7175 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007176 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007177 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007178 // because %A may have negative value.
7179 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007180 // However, we allow this when the compare is EQ/NE, because they are
7181 // signless.
7182 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00007183 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007184 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007185 }
7186
7187 // The re-extended constant changed so the constant cannot be represented
7188 // in the shorter type. Consequently, we cannot emit a simple comparison.
7189
7190 // First, handle some easy cases. We know the result cannot be equal at this
7191 // point so handle the ICI.isEquality() cases
7192 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007193 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007194 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007195 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007196
7197 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7198 // should have been folded away previously and not enter in here.
7199 Value *Result;
7200 if (isSignedCmp) {
7201 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007202 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007203 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007204 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007205 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007206 } else {
7207 // We're performing an unsigned comparison.
7208 if (isSignedExt) {
7209 // We're performing an unsigned comp with a sign extended value.
7210 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007211 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007212 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7213 NegOne, ICI.getName()), ICI);
7214 } else {
7215 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007216 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007217 }
7218 }
7219
7220 // Finally, return the value computed.
7221 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007222 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007223 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007224
7225 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7226 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7227 "ICmp should be folded!");
7228 if (Constant *CI = dyn_cast<Constant>(Result))
7229 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7230 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007231}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007232
Reid Spencer832254e2007-02-02 02:16:23 +00007233Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7234 return commonShiftTransforms(I);
7235}
7236
7237Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7238 return commonShiftTransforms(I);
7239}
7240
7241Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007242 if (Instruction *R = commonShiftTransforms(I))
7243 return R;
7244
7245 Value *Op0 = I.getOperand(0);
7246
7247 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7248 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7249 if (CSI->isAllOnesValue())
7250 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007251
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007252 // See if we can turn a signed shr into an unsigned shr.
7253 if (MaskedValueIsZero(Op0,
7254 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7255 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7256
7257 // Arithmetic shifting an all-sign-bit value is a no-op.
7258 unsigned NumSignBits = ComputeNumSignBits(Op0);
7259 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7260 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007261
Chris Lattner348f6652007-12-06 01:59:46 +00007262 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007263}
7264
7265Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7266 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007267 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007268
7269 // shl X, 0 == X and shr X, 0 == X
7270 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00007271 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00007272 Op0 == Constant::getNullValue(Op0->getType()))
7273 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007274
Reid Spencere4d87aa2006-12-23 06:05:41 +00007275 if (isa<UndefValue>(Op0)) {
7276 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007277 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007278 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007279 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7280 }
7281 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007282 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7283 return ReplaceInstUsesWith(I, Op0);
7284 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007285 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007286 }
7287
Dan Gohman9004c8a2009-05-21 02:28:33 +00007288 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007289 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007290 return &I;
7291
Chris Lattner2eefe512004-04-09 19:05:30 +00007292 // Try to fold constant and into select arguments.
7293 if (isa<Constant>(Op0))
7294 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007295 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007296 return R;
7297
Reid Spencerb83eb642006-10-20 07:07:24 +00007298 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007299 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7300 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007301 return 0;
7302}
7303
Reid Spencerb83eb642006-10-20 07:07:24 +00007304Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007305 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007306 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007307
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007308 // See if we can simplify any instructions used by the instruction whose sole
7309 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007310 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007311
Dan Gohmana119de82009-06-14 23:30:43 +00007312 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7313 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007314 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007315 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007316 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007317 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7318 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007319 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007320 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007321 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007322 }
7323
7324 // ((X*C1) << C2) == (X * (C1 << C2))
7325 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7326 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7327 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007328 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007329 ConstantExpr::getShl(BOOp, Op1));
7330
7331 // Try to fold constant and into select arguments.
7332 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7333 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7334 return R;
7335 if (isa<PHINode>(Op0))
7336 if (Instruction *NV = FoldOpIntoPhi(I))
7337 return NV;
7338
Chris Lattner8999dd32007-12-22 09:07:47 +00007339 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7340 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7341 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7342 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7343 // place. Don't try to do this transformation in this case. Also, we
7344 // require that the input operand is a shift-by-constant so that we have
7345 // confidence that the shifts will get folded together. We could do this
7346 // xform in more cases, but it is unlikely to be profitable.
7347 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7348 isa<ConstantInt>(TrOp->getOperand(1))) {
7349 // Okay, we'll do this xform. Make the shift of shift.
7350 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007351 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007352 I.getName());
7353 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7354
7355 // For logical shifts, the truncation has the effect of making the high
7356 // part of the register be zeros. Emulate this by inserting an AND to
7357 // clear the top bits as needed. This 'and' will usually be zapped by
7358 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007359 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7360 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007361 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7362
7363 // The mask we constructed says what the trunc would do if occurring
7364 // between the shifts. We want to know the effect *after* the second
7365 // shift. We know that it is a logical shift by a constant, so adjust the
7366 // mask as appropriate.
7367 if (I.getOpcode() == Instruction::Shl)
7368 MaskV <<= Op1->getZExtValue();
7369 else {
7370 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7371 MaskV = MaskV.lshr(Op1->getZExtValue());
7372 }
7373
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007374 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007375 TI->getName());
7376 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7377
7378 // Return the value truncated to the interesting size.
7379 return new TruncInst(And, I.getType());
7380 }
7381 }
7382
Chris Lattner4d5542c2006-01-06 07:12:35 +00007383 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007384 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7385 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7386 Value *V1, *V2;
7387 ConstantInt *CC;
7388 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007389 default: break;
7390 case Instruction::Add:
7391 case Instruction::And:
7392 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007393 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007394 // These operators commute.
7395 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007396 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007397 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007398 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007399 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007400 Op0BO->getName());
7401 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007402 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007403 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007404 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007405 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007406 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007407 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007408 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007409 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007410
Chris Lattner150f12a2005-09-18 06:30:59 +00007411 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007412 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007413 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007414 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007415 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7416 m_ConstantInt(CC))) &&
7417 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007418 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007419 Op0BO->getOperand(0), Op1,
7420 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007421 InsertNewInstBefore(YS, I); // (Y << C)
7422 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007423 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007424 V1->getName()+".mask");
7425 InsertNewInstBefore(XM, I); // X & (CC << C)
7426
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007427 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007428 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007429 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007430
Reid Spencera07cb7d2007-02-02 14:41:37 +00007431 // FALL THROUGH.
7432 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007433 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007434 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007435 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007436 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007437 Op0BO->getOperand(1), Op1,
7438 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007439 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007440 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007441 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007442 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007443 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007444 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007445 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007446 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007447 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007448
Chris Lattner13d4ab42006-05-31 21:14:00 +00007449 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007450 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7451 match(Op0BO->getOperand(0),
7452 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007453 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007454 cast<BinaryOperator>(Op0BO->getOperand(0))
7455 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007456 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007457 Op0BO->getOperand(1), Op1,
7458 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007459 InsertNewInstBefore(YS, I); // (Y << C)
7460 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007461 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007462 V1->getName()+".mask");
7463 InsertNewInstBefore(XM, I); // X & (CC << C)
7464
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007465 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007466 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007467
Chris Lattner11021cb2005-09-18 05:12:10 +00007468 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007469 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007470 }
7471
7472
7473 // If the operand is an bitwise operator with a constant RHS, and the
7474 // shift is the only use, we can pull it out of the shift.
7475 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7476 bool isValid = true; // Valid only for And, Or, Xor
7477 bool highBitSet = false; // Transform if high bit of constant set?
7478
7479 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007480 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007481 case Instruction::Add:
7482 isValid = isLeftShift;
7483 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007484 case Instruction::Or:
7485 case Instruction::Xor:
7486 highBitSet = false;
7487 break;
7488 case Instruction::And:
7489 highBitSet = true;
7490 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007491 }
7492
7493 // If this is a signed shift right, and the high bit is modified
7494 // by the logical operation, do not perform the transformation.
7495 // The highBitSet boolean indicates the value of the high bit of
7496 // the constant which would cause it to be modified for this
7497 // operation.
7498 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007499 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007500 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007501
7502 if (isValid) {
7503 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7504
7505 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007506 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007507 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007508 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007509
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007510 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007511 NewRHS);
7512 }
7513 }
7514 }
7515 }
7516
Chris Lattnerad0124c2006-01-06 07:52:12 +00007517 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007518 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7519 if (ShiftOp && !ShiftOp->isShift())
7520 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007521
Reid Spencerb83eb642006-10-20 07:07:24 +00007522 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007523 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007524 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7525 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007526 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7527 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7528 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007529
Zhou Sheng4351c642007-04-02 08:20:41 +00007530 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007531
7532 const IntegerType *Ty = cast<IntegerType>(I.getType());
7533
7534 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007535 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007536 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7537 // saturates.
7538 if (AmtSum >= TypeBits) {
7539 if (I.getOpcode() != Instruction::AShr)
7540 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7541 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7542 }
7543
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007544 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007545 ConstantInt::get(Ty, AmtSum));
7546 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7547 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007548 if (AmtSum >= TypeBits)
7549 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7550
Chris Lattnerb87056f2007-02-05 00:57:54 +00007551 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007552 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007553 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7554 I.getOpcode() == Instruction::LShr) {
7555 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007556 if (AmtSum >= TypeBits)
7557 AmtSum = TypeBits-1;
7558
Chris Lattnerb87056f2007-02-05 00:57:54 +00007559 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007560 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007561 InsertNewInstBefore(Shift, I);
7562
Zhou Shenge9e03f62007-03-28 15:02:20 +00007563 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007564 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007565 }
7566
Chris Lattnerb87056f2007-02-05 00:57:54 +00007567 // Okay, if we get here, one shift must be left, and the other shift must be
7568 // right. See if the amounts are equal.
7569 if (ShiftAmt1 == ShiftAmt2) {
7570 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7571 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007572 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007573 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007574 }
7575 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7576 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007577 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007578 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007579 }
7580 // We can simplify ((X << C) >>s C) into a trunc + sext.
7581 // NOTE: we could do this for any C, but that would make 'unusual' integer
7582 // types. For now, just stick to ones well-supported by the code
7583 // generators.
7584 const Type *SExtType = 0;
7585 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007586 case 1 :
7587 case 8 :
7588 case 16 :
7589 case 32 :
7590 case 64 :
7591 case 128:
7592 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7593 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007594 default: break;
7595 }
7596 if (SExtType) {
7597 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7598 InsertNewInstBefore(NewTrunc, I);
7599 return new SExtInst(NewTrunc, Ty);
7600 }
7601 // Otherwise, we can't handle it yet.
7602 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007603 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007604
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007605 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007606 if (I.getOpcode() == Instruction::Shl) {
7607 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7608 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007609 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007610 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007611 InsertNewInstBefore(Shift, I);
7612
Reid Spencer55702aa2007-03-25 21:11:44 +00007613 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007614 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007615 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007616
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007617 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007618 if (I.getOpcode() == Instruction::LShr) {
7619 assert(ShiftOp->getOpcode() == Instruction::Shl);
7620 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007621 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007622 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007623
Reid Spencerd5e30f02007-03-26 17:18:58 +00007624 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007625 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007626 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007627
7628 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7629 } else {
7630 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007631 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007632
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007633 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007634 if (I.getOpcode() == Instruction::Shl) {
7635 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7636 ShiftOp->getOpcode() == Instruction::AShr);
7637 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007638 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007639 ConstantInt::get(Ty, ShiftDiff));
7640 InsertNewInstBefore(Shift, I);
7641
Reid Spencer55702aa2007-03-25 21:11:44 +00007642 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007643 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007644 }
7645
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007646 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007647 if (I.getOpcode() == Instruction::LShr) {
7648 assert(ShiftOp->getOpcode() == Instruction::Shl);
7649 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007650 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007651 InsertNewInstBefore(Shift, I);
7652
Reid Spencer68d27cf2007-03-26 23:45:51 +00007653 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007654 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007655 }
7656
7657 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007658 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007659 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007660 return 0;
7661}
7662
Chris Lattnera1be5662002-05-02 17:06:02 +00007663
Chris Lattnercfd65102005-10-29 04:36:15 +00007664/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7665/// expression. If so, decompose it, returning some value X, such that Val is
7666/// X*Scale+Offset.
7667///
7668static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007669 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007670 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007671 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007672 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007673 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007674 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007675 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7676 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7677 if (I->getOpcode() == Instruction::Shl) {
7678 // This is a value scaled by '1 << the shift amt'.
7679 Scale = 1U << RHS->getZExtValue();
7680 Offset = 0;
7681 return I->getOperand(0);
7682 } else if (I->getOpcode() == Instruction::Mul) {
7683 // This value is scaled by 'RHS'.
7684 Scale = RHS->getZExtValue();
7685 Offset = 0;
7686 return I->getOperand(0);
7687 } else if (I->getOpcode() == Instruction::Add) {
7688 // We have X+C. Check to see if we really have (X*C2)+C1,
7689 // where C1 is divisible by C2.
7690 unsigned SubScale;
7691 Value *SubVal =
7692 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7693 Offset += RHS->getZExtValue();
7694 Scale = SubScale;
7695 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007696 }
7697 }
7698 }
7699
7700 // Otherwise, we can't look past this.
7701 Scale = 1;
7702 Offset = 0;
7703 return Val;
7704}
7705
7706
Chris Lattnerb3f83972005-10-24 06:03:58 +00007707/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7708/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007709Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007710 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007711 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007712
Chris Lattnerb53c2382005-10-24 06:22:12 +00007713 // Remove any uses of AI that are dead.
7714 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007715
Chris Lattnerb53c2382005-10-24 06:22:12 +00007716 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7717 Instruction *User = cast<Instruction>(*UI++);
7718 if (isInstructionTriviallyDead(User)) {
7719 while (UI != E && *UI == User)
7720 ++UI; // If this instruction uses AI more than once, don't break UI.
7721
Chris Lattnerb53c2382005-10-24 06:22:12 +00007722 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007723 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007724 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007725 }
7726 }
7727
Chris Lattnerb3f83972005-10-24 06:03:58 +00007728 // Get the type really allocated and the type casted to.
7729 const Type *AllocElTy = AI.getAllocatedType();
7730 const Type *CastElTy = PTy->getElementType();
7731 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007732
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007733 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7734 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007735 if (CastElTyAlign < AllocElTyAlign) return 0;
7736
Chris Lattner39387a52005-10-24 06:35:18 +00007737 // If the allocation has multiple uses, only promote it if we are strictly
7738 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007739 // same, we open the door to infinite loops of various kinds. (A reference
7740 // from a dbg.declare doesn't count as a use for this purpose.)
7741 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7742 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007743
Duncan Sands777d2302009-05-09 07:06:46 +00007744 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7745 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007746 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007747
Chris Lattner455fcc82005-10-29 03:19:53 +00007748 // See if we can satisfy the modulus by pulling a scale out of the array
7749 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007750 unsigned ArraySizeScale;
7751 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007752 Value *NumElements = // See if the array size is a decomposable linear expr.
7753 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7754
Chris Lattner455fcc82005-10-29 03:19:53 +00007755 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7756 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007757 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7758 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007759
Chris Lattner455fcc82005-10-29 03:19:53 +00007760 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7761 Value *Amt = 0;
7762 if (Scale == 1) {
7763 Amt = NumElements;
7764 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007765 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007766 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7767 if (isa<ConstantInt>(NumElements))
Dan Gohman6de29f82009-06-15 22:12:54 +00007768 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7769 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007770 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007771 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007772 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007773 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007774 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007775 }
7776
Jeff Cohen86796be2007-04-04 16:58:57 +00007777 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7778 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007779 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007780 Amt = InsertNewInstBefore(Tmp, AI);
7781 }
7782
Chris Lattnerb3f83972005-10-24 06:03:58 +00007783 AllocationInst *New;
7784 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007785 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007786 else
Chris Lattner6934a042007-02-11 01:23:03 +00007787 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007788 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007789 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007790
Dale Johannesena0a66372009-03-05 00:39:02 +00007791 // If the allocation has one real use plus a dbg.declare, just remove the
7792 // declare.
7793 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7794 EraseInstFromFunction(*DI);
7795 }
7796 // If the allocation has multiple real uses, insert a cast and change all
7797 // things that used it to use the new cast. This will also hack on CI, but it
7798 // will die soon.
7799 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007800 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007801 // New is the allocation instruction, pointer typed. AI is the original
7802 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7803 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007804 InsertNewInstBefore(NewCast, AI);
7805 AI.replaceAllUsesWith(NewCast);
7806 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007807 return ReplaceInstUsesWith(CI, New);
7808}
7809
Chris Lattner70074e02006-05-13 02:06:03 +00007810/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007811/// and return it as type Ty without inserting any new casts and without
7812/// changing the computed value. This is used by code that tries to decide
7813/// whether promoting or shrinking integer operations to wider or smaller types
7814/// will allow us to eliminate a truncate or extend.
7815///
7816/// This is a truncation operation if Ty is smaller than V->getType(), or an
7817/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007818///
7819/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7820/// should return true if trunc(V) can be computed by computing V in the smaller
7821/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7822/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7823/// efficiently truncated.
7824///
7825/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7826/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7827/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007828bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007829 unsigned CastOpc,
7830 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007831 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007832 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007833 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007834
7835 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007836 if (!I) return false;
7837
Dan Gohman6de29f82009-06-15 22:12:54 +00007838 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007839
Chris Lattner951626b2007-08-02 06:11:14 +00007840 // If this is an extension or truncate, we can often eliminate it.
7841 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7842 // If this is a cast from the destination type, we can trivially eliminate
7843 // it, and this will remove a cast overall.
7844 if (I->getOperand(0)->getType() == Ty) {
7845 // If the first operand is itself a cast, and is eliminable, do not count
7846 // this as an eliminable cast. We would prefer to eliminate those two
7847 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007848 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007849 ++NumCastsRemoved;
7850 return true;
7851 }
7852 }
7853
7854 // We can't extend or shrink something that has multiple uses: doing so would
7855 // require duplicating the instruction in general, which isn't profitable.
7856 if (!I->hasOneUse()) return false;
7857
Evan Chengf35fd542009-01-15 17:01:23 +00007858 unsigned Opc = I->getOpcode();
7859 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007860 case Instruction::Add:
7861 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007862 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007863 case Instruction::And:
7864 case Instruction::Or:
7865 case Instruction::Xor:
7866 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007867 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007868 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007869 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007870 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007871
Chris Lattner46b96052006-11-29 07:18:39 +00007872 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007873 // If we are truncating the result of this SHL, and if it's a shift of a
7874 // constant amount, we can always perform a SHL in a smaller type.
7875 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007876 uint32_t BitWidth = Ty->getScalarSizeInBits();
7877 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007878 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007879 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007880 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007881 }
7882 break;
7883 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007884 // If this is a truncate of a logical shr, we can truncate it to a smaller
7885 // lshr iff we know that the bits we would otherwise be shifting in are
7886 // already zeros.
7887 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007888 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7889 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007890 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007891 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007892 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7893 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007894 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007895 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007896 }
7897 }
Chris Lattner46b96052006-11-29 07:18:39 +00007898 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007899 case Instruction::ZExt:
7900 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007901 case Instruction::Trunc:
7902 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007903 // can safely replace it. Note that replacing it does not reduce the number
7904 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007905 if (Opc == CastOpc)
7906 return true;
7907
7908 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007909 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007910 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007911 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007912 case Instruction::Select: {
7913 SelectInst *SI = cast<SelectInst>(I);
7914 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007915 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007916 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007917 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007918 }
Chris Lattner8114b712008-06-18 04:00:49 +00007919 case Instruction::PHI: {
7920 // We can change a phi if we can change all operands.
7921 PHINode *PN = cast<PHINode>(I);
7922 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7923 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007924 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007925 return false;
7926 return true;
7927 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007928 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007929 // TODO: Can handle more cases here.
7930 break;
7931 }
7932
7933 return false;
7934}
7935
7936/// EvaluateInDifferentType - Given an expression that
7937/// CanEvaluateInDifferentType returns true for, actually insert the code to
7938/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007939Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007940 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007941 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007942 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007943
7944 // Otherwise, it must be an instruction.
7945 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007946 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007947 unsigned Opc = I->getOpcode();
7948 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007949 case Instruction::Add:
7950 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007951 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007952 case Instruction::And:
7953 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007954 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007955 case Instruction::AShr:
7956 case Instruction::LShr:
7957 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007958 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007959 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007960 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007961 break;
7962 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007963 case Instruction::Trunc:
7964 case Instruction::ZExt:
7965 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007966 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007967 // just return the source. There's no need to insert it because it is not
7968 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007969 if (I->getOperand(0)->getType() == Ty)
7970 return I->getOperand(0);
7971
Chris Lattner8114b712008-06-18 04:00:49 +00007972 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007973 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007974 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007975 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007976 case Instruction::Select: {
7977 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7978 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7979 Res = SelectInst::Create(I->getOperand(0), True, False);
7980 break;
7981 }
Chris Lattner8114b712008-06-18 04:00:49 +00007982 case Instruction::PHI: {
7983 PHINode *OPN = cast<PHINode>(I);
7984 PHINode *NPN = PHINode::Create(Ty);
7985 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7986 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7987 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7988 }
7989 Res = NPN;
7990 break;
7991 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007992 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007993 // TODO: Can handle more cases here.
7994 assert(0 && "Unreachable!");
7995 break;
7996 }
7997
Chris Lattner8114b712008-06-18 04:00:49 +00007998 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007999 return InsertNewInstBefore(Res, *I);
8000}
8001
Reid Spencer3da59db2006-11-27 01:05:10 +00008002/// @brief Implement the transforms common to all CastInst visitors.
8003Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008004 Value *Src = CI.getOperand(0);
8005
Dan Gohman23d9d272007-05-11 21:10:54 +00008006 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008007 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008008 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008009 if (Instruction::CastOps opc =
8010 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8011 // The first cast (CSrc) is eliminable so we need to fix up or replace
8012 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008013 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008014 }
8015 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008016
Reid Spencer3da59db2006-11-27 01:05:10 +00008017 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008018 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8019 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8020 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008021
8022 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008023 if (isa<PHINode>(Src))
8024 if (Instruction *NV = FoldOpIntoPhi(CI))
8025 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008026
Reid Spencer3da59db2006-11-27 01:05:10 +00008027 return 0;
8028}
8029
Chris Lattner46cd5a12009-01-09 05:44:56 +00008030/// FindElementAtOffset - Given a type and a constant offset, determine whether
8031/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008032/// the specified offset. If so, fill them into NewIndices and return the
8033/// resultant element type, otherwise return null.
8034static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8035 SmallVectorImpl<Value*> &NewIndices,
8036 const TargetData *TD) {
8037 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008038
8039 // Start with the index over the outer type. Note that the type size
8040 // might be zero (even if the offset isn't zero) if the indexed type
8041 // is something like [0 x {int, int}]
8042 const Type *IntPtrTy = TD->getIntPtrType();
8043 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008044 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008045 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008046 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008047
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008048 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008049 if (Offset < 0) {
8050 --FirstIdx;
8051 Offset += TySize;
8052 assert(Offset >= 0);
8053 }
8054 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8055 }
8056
8057 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8058
8059 // Index into the types. If we fail, set OrigBase to null.
8060 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008061 // Indexing into tail padding between struct/array elements.
8062 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008063 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008064
Chris Lattner46cd5a12009-01-09 05:44:56 +00008065 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8066 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008067 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8068 "Offset must stay within the indexed type");
8069
Chris Lattner46cd5a12009-01-09 05:44:56 +00008070 unsigned Elt = SL->getElementContainingOffset(Offset);
8071 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
8072
8073 Offset -= SL->getElementOffset(Elt);
8074 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008075 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008076 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008077 assert(EltSize && "Cannot index into a zero-sized array");
8078 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8079 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008080 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008081 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008082 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008083 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008084 }
8085 }
8086
Chris Lattner3914f722009-01-24 01:00:13 +00008087 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008088}
8089
Chris Lattnerd3e28342007-04-27 17:44:50 +00008090/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8091Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8092 Value *Src = CI.getOperand(0);
8093
Chris Lattnerd3e28342007-04-27 17:44:50 +00008094 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008095 // If casting the result of a getelementptr instruction with no offset, turn
8096 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008097 if (GEP->hasAllZeroIndices()) {
8098 // Changing the cast operand is usually not a good idea but it is safe
8099 // here because the pointer operand is being replaced with another
8100 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008101 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008102 CI.setOperand(0, GEP->getOperand(0));
8103 return &CI;
8104 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008105
8106 // If the GEP has a single use, and the base pointer is a bitcast, and the
8107 // GEP computes a constant offset, see if we can convert these three
8108 // instructions into fewer. This typically happens with unions and other
8109 // non-type-safe code.
8110 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8111 if (GEP->hasAllConstantIndices()) {
8112 // We are guaranteed to get a constant from EmitGEPOffset.
8113 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8114 int64_t Offset = OffsetV->getSExtValue();
8115
8116 // Get the base pointer input of the bitcast, and the type it points to.
8117 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8118 const Type *GEPIdxTy =
8119 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008120 SmallVector<Value*, 8> NewIndices;
8121 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
8122 // If we were able to index down into an element, create the GEP
8123 // and bitcast the result. This eliminates one bitcast, potentially
8124 // two.
8125 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8126 NewIndices.begin(),
8127 NewIndices.end(), "");
8128 InsertNewInstBefore(NGEP, CI);
8129 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008130
Chris Lattner46cd5a12009-01-09 05:44:56 +00008131 if (isa<BitCastInst>(CI))
8132 return new BitCastInst(NGEP, CI.getType());
8133 assert(isa<PtrToIntInst>(CI));
8134 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008135 }
8136 }
8137 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008138 }
8139
8140 return commonCastTransforms(CI);
8141}
8142
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008143/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8144/// type like i42. We don't want to introduce operations on random non-legal
8145/// integer types where they don't already exist in the code. In the future,
8146/// we should consider making this based off target-data, so that 32-bit targets
8147/// won't get i64 operations etc.
8148static bool isSafeIntegerType(const Type *Ty) {
8149 switch (Ty->getPrimitiveSizeInBits()) {
8150 case 8:
8151 case 16:
8152 case 32:
8153 case 64:
8154 return true;
8155 default:
8156 return false;
8157 }
8158}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008159
Chris Lattnerc739cd62007-03-03 05:27:34 +00008160/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8161/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00008162/// cases.
8163/// @brief Implement the transforms common to CastInst with integer operands
8164Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8165 if (Instruction *Result = commonCastTransforms(CI))
8166 return Result;
8167
8168 Value *Src = CI.getOperand(0);
8169 const Type *SrcTy = Src->getType();
8170 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008171 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8172 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008173
Reid Spencer3da59db2006-11-27 01:05:10 +00008174 // See if we can simplify any instructions used by the LHS whose sole
8175 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008176 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008177 return &CI;
8178
8179 // If the source isn't an instruction or has more than one use then we
8180 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008181 Instruction *SrcI = dyn_cast<Instruction>(Src);
8182 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008183 return 0;
8184
Chris Lattnerc739cd62007-03-03 05:27:34 +00008185 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008186 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008187 if (!isa<BitCastInst>(CI) &&
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008188 // Only do this if the dest type is a simple type, don't convert the
8189 // expression tree to something weird like i93 unless the source is also
8190 // strange.
Dan Gohman6de29f82009-06-15 22:12:54 +00008191 (isSafeIntegerType(DestTy->getScalarType()) ||
8192 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8193 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008194 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008195 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008196 // eliminates the cast, so it is always a win. If this is a zero-extension,
8197 // we need to do an AND to maintain the clear top-part of the computation,
8198 // so we require that the input have eliminated at least one cast. If this
8199 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008200 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008201 bool DoXForm = false;
8202 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008203 switch (CI.getOpcode()) {
8204 default:
8205 // All the others use floating point so we shouldn't actually
8206 // get here because of the check above.
8207 assert(0 && "Unknown cast type");
8208 case Instruction::Trunc:
8209 DoXForm = true;
8210 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008211 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008212 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008213 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008214 // If it's unnecessary to issue an AND to clear the high bits, it's
8215 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008216 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008217 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8218 if (MaskedValueIsZero(TryRes, Mask))
8219 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008220
8221 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008222 if (TryI->use_empty())
8223 EraseInstFromFunction(*TryI);
8224 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008225 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008226 }
Evan Chengf35fd542009-01-15 17:01:23 +00008227 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008228 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008229 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008230 // If we do not have to emit the truncate + sext pair, then it's always
8231 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008232 //
8233 // It's not safe to eliminate the trunc + sext pair if one of the
8234 // eliminated cast is a truncate. e.g.
8235 // t2 = trunc i32 t1 to i16
8236 // t3 = sext i16 t2 to i32
8237 // !=
8238 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008239 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008240 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8241 if (NumSignBits > (DestBitSize - SrcBitSize))
8242 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008243
8244 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008245 if (TryI->use_empty())
8246 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008247 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008248 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008249 }
Evan Chengf35fd542009-01-15 17:01:23 +00008250 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008251
8252 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008253 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8254 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008255 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8256 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008257 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008258 // Just replace this cast with the result.
8259 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008260
Reid Spencer3da59db2006-11-27 01:05:10 +00008261 assert(Res->getType() == DestTy);
8262 switch (CI.getOpcode()) {
8263 default: assert(0 && "Unknown cast type!");
8264 case Instruction::Trunc:
8265 case Instruction::BitCast:
8266 // Just replace this cast with the result.
8267 return ReplaceInstUsesWith(CI, Res);
8268 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008269 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008270
8271 // If the high bits are already zero, just replace this cast with the
8272 // result.
8273 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8274 if (MaskedValueIsZero(Res, Mask))
8275 return ReplaceInstUsesWith(CI, Res);
8276
8277 // We need to emit an AND to clear the high bits.
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008278 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8279 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008280 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008281 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008282 case Instruction::SExt: {
8283 // If the high bits are already filled with sign bit, just replace this
8284 // cast with the result.
8285 unsigned NumSignBits = ComputeNumSignBits(Res);
8286 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008287 return ReplaceInstUsesWith(CI, Res);
8288
Reid Spencer3da59db2006-11-27 01:05:10 +00008289 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008290 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008291 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8292 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008293 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008294 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008295 }
8296 }
8297
8298 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8299 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8300
8301 switch (SrcI->getOpcode()) {
8302 case Instruction::Add:
8303 case Instruction::Mul:
8304 case Instruction::And:
8305 case Instruction::Or:
8306 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008307 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00008308 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8309 // Don't insert two casts if they cannot be eliminated. We allow
8310 // two casts to be inserted if the sizes are the same. This could
8311 // only be converting signedness, which is a noop.
8312 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008313 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8314 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00008315 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008316 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8317 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008318 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008319 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008320 }
8321 }
8322
8323 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8324 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8325 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008326 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008327 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008328 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008329 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008330 }
8331 break;
8332 case Instruction::SDiv:
8333 case Instruction::UDiv:
8334 case Instruction::SRem:
8335 case Instruction::URem:
8336 // If we are just changing the sign, rewrite.
8337 if (DestBitSize == SrcBitSize) {
8338 // Don't insert two casts if they cannot be eliminated. We allow
8339 // two casts to be inserted if the sizes are the same. This could
8340 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008341 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8342 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008343 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8344 Op0, DestTy, *SrcI);
8345 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8346 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008347 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00008348 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8349 }
8350 }
8351 break;
8352
8353 case Instruction::Shl:
8354 // Allow changing the sign of the source operand. Do not allow
8355 // changing the size of the shift, UNLESS the shift amount is a
8356 // constant. We must not change variable sized shifts to a smaller
8357 // size, because it is undefined to shift more bits out than exist
8358 // in the value.
8359 if (DestBitSize == SrcBitSize ||
8360 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00008361 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8362 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008363 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8364 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008365 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008366 }
8367 break;
8368 case Instruction::AShr:
8369 // If this is a signed shr, and if all bits shifted in are about to be
8370 // truncated off, turn it into an unsigned shr to allow greater
8371 // simplifications.
8372 if (DestBitSize < SrcBitSize &&
8373 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008374 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00008375 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8376 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008377 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008378 }
8379 }
8380 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008381 }
8382 return 0;
8383}
8384
Chris Lattner8a9f5712007-04-11 06:57:46 +00008385Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008386 if (Instruction *Result = commonIntCastTransforms(CI))
8387 return Result;
8388
8389 Value *Src = CI.getOperand(0);
8390 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008391 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8392 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008393
8394 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00008395 if (DestBitWidth == 1 &&
8396 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008397 Constant *One = ConstantInt::get(Src->getType(), 1);
8398 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8399 Value *Zero = Constant::getNullValue(Src->getType());
8400 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8401 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008402
Chris Lattner4f9797d2009-03-24 18:15:30 +00008403 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8404 ConstantInt *ShAmtV = 0;
8405 Value *ShiftOp = 0;
8406 if (Src->hasOneUse() &&
8407 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8408 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8409
8410 // Get a mask for the bits shifting in.
8411 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8412 if (MaskedValueIsZero(ShiftOp, Mask)) {
8413 if (ShAmt >= DestBitWidth) // All zeros.
8414 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8415
8416 // Okay, we can shrink this. Truncate the input, then return a new
8417 // shift.
8418 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8419 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8420 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008421 }
8422 }
8423
8424 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008425}
8426
Evan Chengb98a10e2008-03-24 00:21:34 +00008427/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8428/// in order to eliminate the icmp.
8429Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8430 bool DoXform) {
8431 // If we are just checking for a icmp eq of a single bit and zext'ing it
8432 // to an integer, then shift the bit to the appropriate place and then
8433 // cast to integer to avoid the comparison.
8434 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8435 const APInt &Op1CV = Op1C->getValue();
8436
8437 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8438 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8439 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8440 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8441 if (!DoXform) return ICI;
8442
8443 Value *In = ICI->getOperand(0);
8444 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008445 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008446 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008447 In->getName()+".lobit"),
8448 CI);
8449 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008450 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008451 false/*ZExt*/, "tmp", &CI);
8452
8453 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8454 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008455 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008456 In->getName()+".not"),
8457 CI);
8458 }
8459
8460 return ReplaceInstUsesWith(CI, In);
8461 }
8462
8463
8464
8465 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8466 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8467 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8468 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8469 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8470 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8471 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8472 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8473 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8474 // This only works for EQ and NE
8475 ICI->isEquality()) {
8476 // If Op1C some other power of two, convert:
8477 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8478 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8479 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8480 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8481
8482 APInt KnownZeroMask(~KnownZero);
8483 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8484 if (!DoXform) return ICI;
8485
8486 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8487 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8488 // (X&4) == 2 --> false
8489 // (X&4) != 2 --> true
8490 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8491 Res = ConstantExpr::getZExt(Res, CI.getType());
8492 return ReplaceInstUsesWith(CI, Res);
8493 }
8494
8495 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8496 Value *In = ICI->getOperand(0);
8497 if (ShiftAmt) {
8498 // Perform a logical shr by shiftamt.
8499 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008500 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008501 ConstantInt::get(In->getType(), ShiftAmt),
8502 In->getName()+".lobit"), CI);
8503 }
8504
8505 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8506 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008507 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008508 InsertNewInstBefore(cast<Instruction>(In), CI);
8509 }
8510
8511 if (CI.getType() == In->getType())
8512 return ReplaceInstUsesWith(CI, In);
8513 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008514 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008515 }
8516 }
8517 }
8518
8519 return 0;
8520}
8521
Chris Lattner8a9f5712007-04-11 06:57:46 +00008522Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008523 // If one of the common conversion will work ..
8524 if (Instruction *Result = commonIntCastTransforms(CI))
8525 return Result;
8526
8527 Value *Src = CI.getOperand(0);
8528
Chris Lattnera84f47c2009-02-17 20:47:23 +00008529 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8530 // types and if the sizes are just right we can convert this into a logical
8531 // 'and' which will be much cheaper than the pair of casts.
8532 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8533 // Get the sizes of the types involved. We know that the intermediate type
8534 // will be smaller than A or C, but don't know the relation between A and C.
8535 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008536 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8537 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8538 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008539 // If we're actually extending zero bits, then if
8540 // SrcSize < DstSize: zext(a & mask)
8541 // SrcSize == DstSize: a & mask
8542 // SrcSize > DstSize: trunc(a) & mask
8543 if (SrcSize < DstSize) {
8544 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Dan Gohman6de29f82009-06-15 22:12:54 +00008545 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008546 Instruction *And =
8547 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8548 InsertNewInstBefore(And, CI);
8549 return new ZExtInst(And, CI.getType());
8550 } else if (SrcSize == DstSize) {
8551 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Dan Gohman6de29f82009-06-15 22:12:54 +00008552 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8553 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008554 } else if (SrcSize > DstSize) {
8555 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8556 InsertNewInstBefore(Trunc, CI);
8557 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Dan Gohman6de29f82009-06-15 22:12:54 +00008558 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Trunc->getType(),
8559 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008560 }
8561 }
8562
Evan Chengb98a10e2008-03-24 00:21:34 +00008563 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8564 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008565
Evan Chengb98a10e2008-03-24 00:21:34 +00008566 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8567 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8568 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8569 // of the (zext icmp) will be transformed.
8570 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8571 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8572 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8573 (transformZExtICmp(LHS, CI, false) ||
8574 transformZExtICmp(RHS, CI, false))) {
8575 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8576 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008577 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008578 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008579 }
8580
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008581 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008582 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8583 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8584 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8585 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008586 if (TI0->getType() == CI.getType())
8587 return
8588 BinaryOperator::CreateAnd(TI0,
8589 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008590 }
8591
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008592 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8593 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8594 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8595 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8596 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8597 And->getOperand(1) == C)
8598 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8599 Value *TI0 = TI->getOperand(0);
8600 if (TI0->getType() == CI.getType()) {
8601 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8602 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8603 InsertNewInstBefore(NewAnd, *And);
8604 return BinaryOperator::CreateXor(NewAnd, ZC);
8605 }
8606 }
8607
Reid Spencer3da59db2006-11-27 01:05:10 +00008608 return 0;
8609}
8610
Chris Lattner8a9f5712007-04-11 06:57:46 +00008611Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008612 if (Instruction *I = commonIntCastTransforms(CI))
8613 return I;
8614
Chris Lattner8a9f5712007-04-11 06:57:46 +00008615 Value *Src = CI.getOperand(0);
8616
Dan Gohman1975d032008-10-30 20:40:10 +00008617 // Canonicalize sign-extend from i1 to a select.
8618 if (Src->getType() == Type::Int1Ty)
8619 return SelectInst::Create(Src,
8620 ConstantInt::getAllOnesValue(CI.getType()),
8621 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008622
8623 // See if the value being truncated is already sign extended. If so, just
8624 // eliminate the trunc/sext pair.
8625 if (getOpcode(Src) == Instruction::Trunc) {
8626 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008627 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8628 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8629 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008630 unsigned NumSignBits = ComputeNumSignBits(Op);
8631
8632 if (OpBits == DestBits) {
8633 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8634 // bits, it is already ready.
8635 if (NumSignBits > DestBits-MidBits)
8636 return ReplaceInstUsesWith(CI, Op);
8637 } else if (OpBits < DestBits) {
8638 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8639 // bits, just sext from i32.
8640 if (NumSignBits > OpBits-MidBits)
8641 return new SExtInst(Op, CI.getType(), "tmp");
8642 } else {
8643 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8644 // bits, just truncate to i32.
8645 if (NumSignBits > OpBits-MidBits)
8646 return new TruncInst(Op, CI.getType(), "tmp");
8647 }
8648 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008649
8650 // If the input is a shl/ashr pair of a same constant, then this is a sign
8651 // extension from a smaller value. If we could trust arbitrary bitwidth
8652 // integers, we could turn this into a truncate to the smaller bit and then
8653 // use a sext for the whole extension. Since we don't, look deeper and check
8654 // for a truncate. If the source and dest are the same type, eliminate the
8655 // trunc and extend and just do shifts. For example, turn:
8656 // %a = trunc i32 %i to i8
8657 // %b = shl i8 %a, 6
8658 // %c = ashr i8 %b, 6
8659 // %d = sext i8 %c to i32
8660 // into:
8661 // %a = shl i32 %i, 30
8662 // %d = ashr i32 %a, 30
8663 Value *A = 0;
8664 ConstantInt *BA = 0, *CA = 0;
8665 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8666 m_ConstantInt(CA))) &&
8667 BA == CA && isa<TruncInst>(A)) {
8668 Value *I = cast<TruncInst>(A)->getOperand(0);
8669 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008670 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8671 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008672 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8673 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8674 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8675 CI.getName()), CI);
8676 return BinaryOperator::CreateAShr(I, ShAmtV);
8677 }
8678 }
8679
Chris Lattnerba417832007-04-11 06:12:58 +00008680 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008681}
8682
Chris Lattnerb7530652008-01-27 05:29:54 +00008683/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8684/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008685static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008686 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008687 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008688 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8689 if (!losesInfo)
Chris Lattner02a260a2008-04-20 00:41:09 +00008690 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008691 return 0;
8692}
8693
8694/// LookThroughFPExtensions - If this is an fp extension instruction, look
8695/// through it until we get the source value.
8696static Value *LookThroughFPExtensions(Value *V) {
8697 if (Instruction *I = dyn_cast<Instruction>(V))
8698 if (I->getOpcode() == Instruction::FPExt)
8699 return LookThroughFPExtensions(I->getOperand(0));
8700
8701 // If this value is a constant, return the constant in the smallest FP type
8702 // that can accurately represent it. This allows us to turn
8703 // (float)((double)X+2.0) into x+2.0f.
8704 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8705 if (CFP->getType() == Type::PPC_FP128Ty)
8706 return V; // No constant folding of this.
8707 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008708 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008709 return V;
8710 if (CFP->getType() == Type::DoubleTy)
8711 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008712 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008713 return V;
8714 // Don't try to shrink to various long double types.
8715 }
8716
8717 return V;
8718}
8719
8720Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8721 if (Instruction *I = commonCastTransforms(CI))
8722 return I;
8723
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008724 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008725 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008726 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008727 // many builtins (sqrt, etc).
8728 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8729 if (OpI && OpI->hasOneUse()) {
8730 switch (OpI->getOpcode()) {
8731 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008732 case Instruction::FAdd:
8733 case Instruction::FSub:
8734 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008735 case Instruction::FDiv:
8736 case Instruction::FRem:
8737 const Type *SrcTy = OpI->getType();
8738 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8739 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8740 if (LHSTrunc->getType() != SrcTy &&
8741 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008742 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008743 // If the source types were both smaller than the destination type of
8744 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008745 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8746 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008747 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8748 CI.getType(), CI);
8749 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8750 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008751 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008752 }
8753 }
8754 break;
8755 }
8756 }
8757 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008758}
8759
8760Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8761 return commonCastTransforms(CI);
8762}
8763
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008764Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008765 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8766 if (OpI == 0)
8767 return commonCastTransforms(FI);
8768
8769 // fptoui(uitofp(X)) --> X
8770 // fptoui(sitofp(X)) --> X
8771 // This is safe if the intermediate type has enough bits in its mantissa to
8772 // accurately represent all values of X. For example, do not do this with
8773 // i64->float->i64. This is also safe for sitofp case, because any negative
8774 // 'X' value would cause an undefined result for the fptoui.
8775 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8776 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008777 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008778 OpI->getType()->getFPMantissaWidth())
8779 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008780
8781 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008782}
8783
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008784Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008785 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8786 if (OpI == 0)
8787 return commonCastTransforms(FI);
8788
8789 // fptosi(sitofp(X)) --> X
8790 // fptosi(uitofp(X)) --> X
8791 // This is safe if the intermediate type has enough bits in its mantissa to
8792 // accurately represent all values of X. For example, do not do this with
8793 // i64->float->i64. This is also safe for sitofp case, because any negative
8794 // 'X' value would cause an undefined result for the fptoui.
8795 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8796 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008797 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008798 OpI->getType()->getFPMantissaWidth())
8799 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008800
8801 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008802}
8803
8804Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8805 return commonCastTransforms(CI);
8806}
8807
8808Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8809 return commonCastTransforms(CI);
8810}
8811
Chris Lattnera0e69692009-03-24 18:35:40 +00008812Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8813 // If the destination integer type is smaller than the intptr_t type for
8814 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8815 // trunc to be exposed to other transforms. Don't do this for extending
8816 // ptrtoint's, because we don't know if the target sign or zero extends its
8817 // pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008818 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008819 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8820 TD->getIntPtrType(),
8821 "tmp"), CI);
8822 return new TruncInst(P, CI.getType());
8823 }
8824
Chris Lattnerd3e28342007-04-27 17:44:50 +00008825 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008826}
8827
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008828Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008829 // If the source integer type is larger than the intptr_t type for
8830 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8831 // allows the trunc to be exposed to other transforms. Don't do this for
8832 // extending inttoptr's, because we don't know if the target sign or zero
8833 // extends to pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008834 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008835 TD->getPointerSizeInBits()) {
8836 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8837 TD->getIntPtrType(),
8838 "tmp"), CI);
8839 return new IntToPtrInst(P, CI.getType());
8840 }
8841
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008842 if (Instruction *I = commonCastTransforms(CI))
8843 return I;
8844
8845 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8846 if (!DestPointee->isSized()) return 0;
8847
8848 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8849 ConstantInt *Cst;
8850 Value *X;
8851 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8852 m_ConstantInt(Cst)))) {
8853 // If the source and destination operands have the same type, see if this
8854 // is a single-index GEP.
8855 if (X->getType() == CI.getType()) {
8856 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008857 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008858
8859 // Convert the constant to intptr type.
8860 APInt Offset = Cst->getValue();
8861 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8862
8863 // If Offset is evenly divisible by Size, we can do this xform.
8864 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8865 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008866 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008867 }
8868 }
8869 // TODO: Could handle other cases, e.g. where add is indexing into field of
8870 // struct etc.
8871 } else if (CI.getOperand(0)->hasOneUse() &&
8872 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8873 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8874 // "inttoptr+GEP" instead of "add+intptr".
8875
8876 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008877 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008878
8879 // Convert the constant to intptr type.
8880 APInt Offset = Cst->getValue();
8881 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8882
8883 // If Offset is evenly divisible by Size, we can do this xform.
8884 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8885 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8886
8887 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8888 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008889 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008890 }
8891 }
8892 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008893}
8894
Chris Lattnerd3e28342007-04-27 17:44:50 +00008895Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008896 // If the operands are integer typed then apply the integer transforms,
8897 // otherwise just apply the common ones.
8898 Value *Src = CI.getOperand(0);
8899 const Type *SrcTy = Src->getType();
8900 const Type *DestTy = CI.getType();
8901
Chris Lattner42a75512007-01-15 02:27:26 +00008902 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008903 if (Instruction *Result = commonIntCastTransforms(CI))
8904 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008905 } else if (isa<PointerType>(SrcTy)) {
8906 if (Instruction *I = commonPointerCastTransforms(CI))
8907 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008908 } else {
8909 if (Instruction *Result = commonCastTransforms(CI))
8910 return Result;
8911 }
8912
8913
8914 // Get rid of casts from one type to the same type. These are useless and can
8915 // be replaced by the operand.
8916 if (DestTy == Src->getType())
8917 return ReplaceInstUsesWith(CI, Src);
8918
Reid Spencer3da59db2006-11-27 01:05:10 +00008919 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008920 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8921 const Type *DstElTy = DstPTy->getElementType();
8922 const Type *SrcElTy = SrcPTy->getElementType();
8923
Nate Begeman83ad90a2008-03-31 00:22:16 +00008924 // If the address spaces don't match, don't eliminate the bitcast, which is
8925 // required for changing types.
8926 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8927 return 0;
8928
Chris Lattnerd3e28342007-04-27 17:44:50 +00008929 // If we are casting a malloc or alloca to a pointer to a type of the same
8930 // size, rewrite the allocation instruction to allocate the "right" type.
8931 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8932 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8933 return V;
8934
Chris Lattnerd717c182007-05-05 22:32:24 +00008935 // If the source and destination are pointers, and this cast is equivalent
8936 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008937 // This can enhance SROA and other transforms that want type-safe pointers.
8938 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8939 unsigned NumZeros = 0;
8940 while (SrcElTy != DstElTy &&
8941 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8942 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8943 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8944 ++NumZeros;
8945 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008946
Chris Lattnerd3e28342007-04-27 17:44:50 +00008947 // If we found a path from the src to dest, create the getelementptr now.
8948 if (SrcElTy == DstElTy) {
8949 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008950 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8951 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008952 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008953 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008954
Reid Spencer3da59db2006-11-27 01:05:10 +00008955 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8956 if (SVI->hasOneUse()) {
8957 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8958 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008959 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008960 cast<VectorType>(DestTy)->getNumElements() ==
8961 SVI->getType()->getNumElements() &&
8962 SVI->getType()->getNumElements() ==
8963 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008964 CastInst *Tmp;
8965 // If either of the operands is a cast from CI.getType(), then
8966 // evaluating the shuffle in the casted destination's type will allow
8967 // us to eliminate at least one cast.
8968 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8969 Tmp->getOperand(0)->getType() == DestTy) ||
8970 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8971 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008972 Value *LHS = InsertCastBefore(Instruction::BitCast,
8973 SVI->getOperand(0), DestTy, CI);
8974 Value *RHS = InsertCastBefore(Instruction::BitCast,
8975 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008976 // Return a new shuffle vector. Use the same element ID's, as we
8977 // know the vector types match #elts.
8978 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008979 }
8980 }
8981 }
8982 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008983 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008984}
8985
Chris Lattnere576b912004-04-09 23:46:01 +00008986/// GetSelectFoldableOperands - We want to turn code that looks like this:
8987/// %C = or %A, %B
8988/// %D = select %cond, %C, %A
8989/// into:
8990/// %C = select %cond, %B, 0
8991/// %D = or %A, %C
8992///
8993/// Assuming that the specified instruction is an operand to the select, return
8994/// a bitmask indicating which operands of this instruction are foldable if they
8995/// equal the other incoming value of the select.
8996///
8997static unsigned GetSelectFoldableOperands(Instruction *I) {
8998 switch (I->getOpcode()) {
8999 case Instruction::Add:
9000 case Instruction::Mul:
9001 case Instruction::And:
9002 case Instruction::Or:
9003 case Instruction::Xor:
9004 return 3; // Can fold through either operand.
9005 case Instruction::Sub: // Can only fold on the amount subtracted.
9006 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009007 case Instruction::LShr:
9008 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009009 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009010 default:
9011 return 0; // Cannot fold
9012 }
9013}
9014
9015/// GetSelectFoldableConstant - For the same transformation as the previous
9016/// function, return the identity constant that goes into the select.
9017static Constant *GetSelectFoldableConstant(Instruction *I) {
9018 switch (I->getOpcode()) {
9019 default: assert(0 && "This cannot happen!"); abort();
9020 case Instruction::Add:
9021 case Instruction::Sub:
9022 case Instruction::Or:
9023 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009024 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009025 case Instruction::LShr:
9026 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00009027 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009028 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00009029 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009030 case Instruction::Mul:
9031 return ConstantInt::get(I->getType(), 1);
9032 }
9033}
9034
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009035/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9036/// have the same opcode and only one use each. Try to simplify this.
9037Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9038 Instruction *FI) {
9039 if (TI->getNumOperands() == 1) {
9040 // If this is a non-volatile load or a cast from the same type,
9041 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009042 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009043 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9044 return 0;
9045 } else {
9046 return 0; // unknown unary op.
9047 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009048
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009049 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009050 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9051 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009052 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009053 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009054 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009055 }
9056
Reid Spencer832254e2007-02-02 02:16:23 +00009057 // Only handle binary operators here.
9058 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009059 return 0;
9060
9061 // Figure out if the operations have any operands in common.
9062 Value *MatchOp, *OtherOpT, *OtherOpF;
9063 bool MatchIsOpZero;
9064 if (TI->getOperand(0) == FI->getOperand(0)) {
9065 MatchOp = TI->getOperand(0);
9066 OtherOpT = TI->getOperand(1);
9067 OtherOpF = FI->getOperand(1);
9068 MatchIsOpZero = true;
9069 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9070 MatchOp = TI->getOperand(1);
9071 OtherOpT = TI->getOperand(0);
9072 OtherOpF = FI->getOperand(0);
9073 MatchIsOpZero = false;
9074 } else if (!TI->isCommutative()) {
9075 return 0;
9076 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9077 MatchOp = TI->getOperand(0);
9078 OtherOpT = TI->getOperand(1);
9079 OtherOpF = FI->getOperand(0);
9080 MatchIsOpZero = true;
9081 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9082 MatchOp = TI->getOperand(1);
9083 OtherOpT = TI->getOperand(0);
9084 OtherOpF = FI->getOperand(1);
9085 MatchIsOpZero = true;
9086 } else {
9087 return 0;
9088 }
9089
9090 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009091 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9092 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009093 InsertNewInstBefore(NewSI, SI);
9094
9095 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9096 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009097 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009098 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009099 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009100 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00009101 assert(0 && "Shouldn't get here");
9102 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009103}
9104
Evan Chengde621922009-03-31 20:42:45 +00009105static bool isSelect01(Constant *C1, Constant *C2) {
9106 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9107 if (!C1I)
9108 return false;
9109 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9110 if (!C2I)
9111 return false;
9112 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9113}
9114
9115/// FoldSelectIntoOp - Try fold the select into one of the operands to
9116/// facilitate further optimization.
9117Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9118 Value *FalseVal) {
9119 // See the comment above GetSelectFoldableOperands for a description of the
9120 // transformation we are doing here.
9121 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9122 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9123 !isa<Constant>(FalseVal)) {
9124 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9125 unsigned OpToFold = 0;
9126 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9127 OpToFold = 1;
9128 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9129 OpToFold = 2;
9130 }
9131
9132 if (OpToFold) {
9133 Constant *C = GetSelectFoldableConstant(TVI);
9134 Value *OOp = TVI->getOperand(2-OpToFold);
9135 // Avoid creating select between 2 constants unless it's selecting
9136 // between 0 and 1.
9137 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9138 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9139 InsertNewInstBefore(NewSel, SI);
9140 NewSel->takeName(TVI);
9141 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9142 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9143 assert(0 && "Unknown instruction!!");
9144 }
9145 }
9146 }
9147 }
9148 }
9149
9150 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9151 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9152 !isa<Constant>(TrueVal)) {
9153 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9154 unsigned OpToFold = 0;
9155 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9156 OpToFold = 1;
9157 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9158 OpToFold = 2;
9159 }
9160
9161 if (OpToFold) {
9162 Constant *C = GetSelectFoldableConstant(FVI);
9163 Value *OOp = FVI->getOperand(2-OpToFold);
9164 // Avoid creating select between 2 constants unless it's selecting
9165 // between 0 and 1.
9166 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9167 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9168 InsertNewInstBefore(NewSel, SI);
9169 NewSel->takeName(FVI);
9170 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9171 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9172 assert(0 && "Unknown instruction!!");
9173 }
9174 }
9175 }
9176 }
9177 }
9178
9179 return 0;
9180}
9181
Dan Gohman81b28ce2008-09-16 18:46:06 +00009182/// visitSelectInstWithICmp - Visit a SelectInst that has an
9183/// ICmpInst as its first operand.
9184///
9185Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9186 ICmpInst *ICI) {
9187 bool Changed = false;
9188 ICmpInst::Predicate Pred = ICI->getPredicate();
9189 Value *CmpLHS = ICI->getOperand(0);
9190 Value *CmpRHS = ICI->getOperand(1);
9191 Value *TrueVal = SI.getTrueValue();
9192 Value *FalseVal = SI.getFalseValue();
9193
9194 // Check cases where the comparison is with a constant that
9195 // can be adjusted to fit the min/max idiom. We may edit ICI in
9196 // place here, so make sure the select is the only user.
9197 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009198 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009199 switch (Pred) {
9200 default: break;
9201 case ICmpInst::ICMP_ULT:
9202 case ICmpInst::ICMP_SLT: {
9203 // X < MIN ? T : F --> F
9204 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9205 return ReplaceInstUsesWith(SI, FalseVal);
9206 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9207 Constant *AdjustedRHS = SubOne(CI);
9208 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9209 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9210 Pred = ICmpInst::getSwappedPredicate(Pred);
9211 CmpRHS = AdjustedRHS;
9212 std::swap(FalseVal, TrueVal);
9213 ICI->setPredicate(Pred);
9214 ICI->setOperand(1, CmpRHS);
9215 SI.setOperand(1, TrueVal);
9216 SI.setOperand(2, FalseVal);
9217 Changed = true;
9218 }
9219 break;
9220 }
9221 case ICmpInst::ICMP_UGT:
9222 case ICmpInst::ICMP_SGT: {
9223 // X > MAX ? T : F --> F
9224 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9225 return ReplaceInstUsesWith(SI, FalseVal);
9226 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9227 Constant *AdjustedRHS = AddOne(CI);
9228 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9229 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9230 Pred = ICmpInst::getSwappedPredicate(Pred);
9231 CmpRHS = AdjustedRHS;
9232 std::swap(FalseVal, TrueVal);
9233 ICI->setPredicate(Pred);
9234 ICI->setOperand(1, CmpRHS);
9235 SI.setOperand(1, TrueVal);
9236 SI.setOperand(2, FalseVal);
9237 Changed = true;
9238 }
9239 break;
9240 }
9241 }
9242
Dan Gohman1975d032008-10-30 20:40:10 +00009243 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9244 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009245 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner159c35b2009-01-05 23:53:12 +00009246 if (match(TrueVal, m_ConstantInt<-1>()) &&
9247 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009248 Pred = ICI->getPredicate();
Chris Lattner159c35b2009-01-05 23:53:12 +00009249 else if (match(TrueVal, m_ConstantInt<0>()) &&
9250 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009251 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9252
Dan Gohman1975d032008-10-30 20:40:10 +00009253 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9254 // If we are just checking for a icmp eq of a single bit and zext'ing it
9255 // to an integer, then shift the bit to the appropriate place and then
9256 // cast to integer to avoid the comparison.
9257 const APInt &Op1CV = CI->getValue();
9258
9259 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9260 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9261 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009262 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009263 Value *In = ICI->getOperand(0);
9264 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009265 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009266 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9267 In->getName()+".lobit"),
9268 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009269 if (In->getType() != SI.getType())
9270 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009271 true/*SExt*/, "tmp", ICI);
9272
9273 if (Pred == ICmpInst::ICMP_SGT)
9274 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9275 In->getName()+".not"), *ICI);
9276
9277 return ReplaceInstUsesWith(SI, In);
9278 }
9279 }
9280 }
9281
Dan Gohman81b28ce2008-09-16 18:46:06 +00009282 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9283 // Transform (X == Y) ? X : Y -> Y
9284 if (Pred == ICmpInst::ICMP_EQ)
9285 return ReplaceInstUsesWith(SI, FalseVal);
9286 // Transform (X != Y) ? X : Y -> X
9287 if (Pred == ICmpInst::ICMP_NE)
9288 return ReplaceInstUsesWith(SI, TrueVal);
9289 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9290
9291 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9292 // Transform (X == Y) ? Y : X -> X
9293 if (Pred == ICmpInst::ICMP_EQ)
9294 return ReplaceInstUsesWith(SI, FalseVal);
9295 // Transform (X != Y) ? Y : X -> Y
9296 if (Pred == ICmpInst::ICMP_NE)
9297 return ReplaceInstUsesWith(SI, TrueVal);
9298 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9299 }
9300
9301 /// NOTE: if we wanted to, this is where to detect integer ABS
9302
9303 return Changed ? &SI : 0;
9304}
9305
Chris Lattner3d69f462004-03-12 05:52:32 +00009306Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009307 Value *CondVal = SI.getCondition();
9308 Value *TrueVal = SI.getTrueValue();
9309 Value *FalseVal = SI.getFalseValue();
9310
9311 // select true, X, Y -> X
9312 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009313 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009314 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009315
9316 // select C, X, X -> X
9317 if (TrueVal == FalseVal)
9318 return ReplaceInstUsesWith(SI, TrueVal);
9319
Chris Lattnere87597f2004-10-16 18:11:37 +00009320 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9321 return ReplaceInstUsesWith(SI, FalseVal);
9322 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9323 return ReplaceInstUsesWith(SI, TrueVal);
9324 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9325 if (isa<Constant>(TrueVal))
9326 return ReplaceInstUsesWith(SI, TrueVal);
9327 else
9328 return ReplaceInstUsesWith(SI, FalseVal);
9329 }
9330
Reid Spencer4fe16d62007-01-11 18:21:29 +00009331 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009332 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009333 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009334 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009335 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009336 } else {
9337 // Change: A = select B, false, C --> A = and !B, C
9338 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009339 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009340 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009341 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009342 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009343 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009344 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009345 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009346 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009347 } else {
9348 // Change: A = select B, C, true --> A = or !B, C
9349 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009350 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009351 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009352 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009353 }
9354 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009355
9356 // select a, b, a -> a&b
9357 // select a, a, b -> a|b
9358 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009359 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009360 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009361 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009362 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009363
Chris Lattner2eefe512004-04-09 19:05:30 +00009364 // Selecting between two integer constants?
9365 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9366 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009367 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009368 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009369 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009370 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009371 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009372 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009373 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009374 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009375 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009376 }
Chris Lattner457dd822004-06-09 07:59:58 +00009377
Reid Spencere4d87aa2006-12-23 06:05:41 +00009378 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009379
Reid Spencere4d87aa2006-12-23 06:05:41 +00009380 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00009381 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00009382 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00009383 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009384 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00009385 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00009386 Value *X = IC->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00009387 uint32_t Bits = X->getType()->getScalarSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00009388 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009389 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00009390 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00009391 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009392
9393 // Then cast to the appropriate width.
9394 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00009395 }
9396 }
9397
9398
9399 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009400 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009401 // non-constant value, eliminate this whole mess. This corresponds to
9402 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009403 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009404 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009405 cast<Constant>(IC->getOperand(1))->isNullValue())
9406 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9407 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009408 isa<ConstantInt>(ICA->getOperand(1)) &&
9409 (ICA->getOperand(1) == TrueValC ||
9410 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009411 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9412 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009413 // know whether we have a icmp_ne or icmp_eq and whether the
9414 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009415 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009416 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009417 Value *V = ICA;
9418 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009419 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009420 Instruction::Xor, V, ICA->getOperand(1)), SI);
9421 return ReplaceInstUsesWith(SI, V);
9422 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009423 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009424 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009425
9426 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009427 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9428 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009429 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009430 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9431 // This is not safe in general for floating point:
9432 // consider X== -0, Y== +0.
9433 // It becomes safe if either operand is a nonzero constant.
9434 ConstantFP *CFPt, *CFPf;
9435 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9436 !CFPt->getValueAPF().isZero()) ||
9437 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9438 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009439 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009440 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009441 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009442 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009443 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009444 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009445
Reid Spencere4d87aa2006-12-23 06:05:41 +00009446 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009447 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009448 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9449 // This is not safe in general for floating point:
9450 // consider X== -0, Y== +0.
9451 // It becomes safe if either operand is a nonzero constant.
9452 ConstantFP *CFPt, *CFPf;
9453 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9454 !CFPt->getValueAPF().isZero()) ||
9455 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9456 !CFPf->getValueAPF().isZero()))
9457 return ReplaceInstUsesWith(SI, FalseVal);
9458 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009459 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009460 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9461 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009462 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009463 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009464 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009465 }
9466
9467 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009468 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9469 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9470 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009471
Chris Lattner87875da2005-01-13 22:52:24 +00009472 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9473 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9474 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009475 Instruction *AddOp = 0, *SubOp = 0;
9476
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009477 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9478 if (TI->getOpcode() == FI->getOpcode())
9479 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9480 return IV;
9481
9482 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9483 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009484 if ((TI->getOpcode() == Instruction::Sub &&
9485 FI->getOpcode() == Instruction::Add) ||
9486 (TI->getOpcode() == Instruction::FSub &&
9487 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009488 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009489 } else if ((FI->getOpcode() == Instruction::Sub &&
9490 TI->getOpcode() == Instruction::Add) ||
9491 (FI->getOpcode() == Instruction::FSub &&
9492 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009493 AddOp = TI; SubOp = FI;
9494 }
9495
9496 if (AddOp) {
9497 Value *OtherAddOp = 0;
9498 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9499 OtherAddOp = AddOp->getOperand(1);
9500 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9501 OtherAddOp = AddOp->getOperand(0);
9502 }
9503
9504 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009505 // So at this point we know we have (Y -> OtherAddOp):
9506 // select C, (add X, Y), (sub X, Z)
9507 Value *NegVal; // Compute -Z
9508 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9509 NegVal = ConstantExpr::getNeg(C);
9510 } else {
9511 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009512 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009513 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009514
9515 Value *NewTrueOp = OtherAddOp;
9516 Value *NewFalseOp = NegVal;
9517 if (AddOp != TI)
9518 std::swap(NewTrueOp, NewFalseOp);
9519 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009520 SelectInst::Create(CondVal, NewTrueOp,
9521 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009522
9523 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009524 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009525 }
9526 }
9527 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009528
Chris Lattnere576b912004-04-09 23:46:01 +00009529 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009530 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009531 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9532 if (FoldI)
9533 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009534 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009535
9536 if (BinaryOperator::isNot(CondVal)) {
9537 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9538 SI.setOperand(1, FalseVal);
9539 SI.setOperand(2, TrueVal);
9540 return &SI;
9541 }
9542
Chris Lattner3d69f462004-03-12 05:52:32 +00009543 return 0;
9544}
9545
Dan Gohmaneee962e2008-04-10 18:43:06 +00009546/// EnforceKnownAlignment - If the specified pointer points to an object that
9547/// we control, modify the object's alignment to PrefAlign. This isn't
9548/// often possible though. If alignment is important, a more reliable approach
9549/// is to simply align all global variables and allocation instructions to
9550/// their preferred alignment from the beginning.
9551///
9552static unsigned EnforceKnownAlignment(Value *V,
9553 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009554
Dan Gohmaneee962e2008-04-10 18:43:06 +00009555 User *U = dyn_cast<User>(V);
9556 if (!U) return Align;
9557
9558 switch (getOpcode(U)) {
9559 default: break;
9560 case Instruction::BitCast:
9561 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9562 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009563 // If all indexes are zero, it is just the alignment of the base pointer.
9564 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009565 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009566 if (!isa<Constant>(*i) ||
9567 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009568 AllZeroOperands = false;
9569 break;
9570 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009571
9572 if (AllZeroOperands) {
9573 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009574 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009575 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009576 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009577 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009578 }
9579
9580 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9581 // If there is a large requested alignment and we can, bump up the alignment
9582 // of the global.
9583 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009584 if (GV->getAlignment() >= PrefAlign)
9585 Align = GV->getAlignment();
9586 else {
9587 GV->setAlignment(PrefAlign);
9588 Align = PrefAlign;
9589 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009590 }
9591 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9592 // If there is a requested alignment and if this is an alloca, round up. We
9593 // don't do this for malloc, because some systems can't respect the request.
9594 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009595 if (AI->getAlignment() >= PrefAlign)
9596 Align = AI->getAlignment();
9597 else {
9598 AI->setAlignment(PrefAlign);
9599 Align = PrefAlign;
9600 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009601 }
9602 }
9603
9604 return Align;
9605}
9606
9607/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9608/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9609/// and it is more than the alignment of the ultimate object, see if we can
9610/// increase the alignment of the ultimate object, making this check succeed.
9611unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9612 unsigned PrefAlign) {
9613 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9614 sizeof(PrefAlign) * CHAR_BIT;
9615 APInt Mask = APInt::getAllOnesValue(BitWidth);
9616 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9617 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9618 unsigned TrailZ = KnownZero.countTrailingOnes();
9619 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9620
9621 if (PrefAlign > Align)
9622 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9623
9624 // We don't need to make any adjustment.
9625 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009626}
9627
Chris Lattnerf497b022008-01-13 23:50:23 +00009628Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009629 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009630 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009631 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009632 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009633
9634 if (CopyAlign < MinAlign) {
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009635 MI->setAlignment(MinAlign);
Chris Lattnerf497b022008-01-13 23:50:23 +00009636 return MI;
9637 }
9638
9639 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9640 // load/store.
9641 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9642 if (MemOpLength == 0) return 0;
9643
Chris Lattner37ac6082008-01-14 00:28:35 +00009644 // Source and destination pointer types are always "i8*" for intrinsic. See
9645 // if the size is something we can handle with a single primitive load/store.
9646 // A single load+store correctly handles overlapping memory in the memmove
9647 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009648 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009649 if (Size == 0) return MI; // Delete this mem transfer.
9650
9651 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009652 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009653
Chris Lattner37ac6082008-01-14 00:28:35 +00009654 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009655 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009656
9657 // Memcpy forces the use of i8* for the source and destination. That means
9658 // that if you're using memcpy to move one double around, you'll get a cast
9659 // from double* to i8*. We'd much rather use a double load+store rather than
9660 // an i64 load+store, here because this improves the odds that the source or
9661 // dest address will be promotable. See if we can find a better type than the
9662 // integer datatype.
9663 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9664 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9665 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9666 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9667 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009668 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009669 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9670 if (STy->getNumElements() == 1)
9671 SrcETy = STy->getElementType(0);
9672 else
9673 break;
9674 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9675 if (ATy->getNumElements() == 1)
9676 SrcETy = ATy->getElementType();
9677 else
9678 break;
9679 } else
9680 break;
9681 }
9682
Dan Gohman8f8e2692008-05-23 01:52:21 +00009683 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009684 NewPtrTy = PointerType::getUnqual(SrcETy);
9685 }
9686 }
9687
9688
Chris Lattnerf497b022008-01-13 23:50:23 +00009689 // If the memcpy/memmove provides better alignment info than we can
9690 // infer, use it.
9691 SrcAlign = std::max(SrcAlign, CopyAlign);
9692 DstAlign = std::max(DstAlign, CopyAlign);
9693
9694 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9695 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009696 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9697 InsertNewInstBefore(L, *MI);
9698 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9699
9700 // Set the size of the copy to 0, it will be deleted on the next iteration.
9701 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9702 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009703}
Chris Lattner3d69f462004-03-12 05:52:32 +00009704
Chris Lattner69ea9d22008-04-30 06:39:11 +00009705Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9706 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009707 if (MI->getAlignment() < Alignment) {
9708 MI->setAlignment(Alignment);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009709 return MI;
9710 }
9711
9712 // Extract the length and alignment and fill if they are constant.
9713 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9714 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9715 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9716 return 0;
9717 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009718 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009719
9720 // If the length is zero, this is a no-op
9721 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9722
9723 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9724 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9725 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9726
9727 Value *Dest = MI->getDest();
9728 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9729
9730 // Alignment 0 is identity for alignment 1 for memset, but not store.
9731 if (Alignment == 0) Alignment = 1;
9732
9733 // Extract the fill value and store.
9734 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9735 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9736 Alignment), *MI);
9737
9738 // Set the size of the copy to 0, it will be deleted on the next iteration.
9739 MI->setLength(Constant::getNullValue(LenC->getType()));
9740 return MI;
9741 }
9742
9743 return 0;
9744}
9745
9746
Chris Lattner8b0ea312006-01-13 20:11:04 +00009747/// visitCallInst - CallInst simplification. This mostly only handles folding
9748/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9749/// the heavy lifting.
9750///
Chris Lattner9fe38862003-06-19 17:00:31 +00009751Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009752 // If the caller function is nounwind, mark the call as nounwind, even if the
9753 // callee isn't.
9754 if (CI.getParent()->getParent()->doesNotThrow() &&
9755 !CI.doesNotThrow()) {
9756 CI.setDoesNotThrow();
9757 return &CI;
9758 }
9759
9760
9761
Chris Lattner8b0ea312006-01-13 20:11:04 +00009762 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9763 if (!II) return visitCallSite(&CI);
9764
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009765 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9766 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009767 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009768 bool Changed = false;
9769
9770 // memmove/cpy/set of zero bytes is a noop.
9771 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9772 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9773
Chris Lattner35b9e482004-10-12 04:52:52 +00009774 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009775 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009776 // Replace the instruction with just byte operations. We would
9777 // transform other cases to loads/stores, but we don't know if
9778 // alignment is sufficient.
9779 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009780 }
9781
Chris Lattner35b9e482004-10-12 04:52:52 +00009782 // If we have a memmove and the source operation is a constant global,
9783 // then the source and dest pointers can't alias, so we can change this
9784 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009785 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009786 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9787 if (GVSrc->isConstant()) {
9788 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009789 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9790 const Type *Tys[1];
9791 Tys[0] = CI.getOperand(3)->getType();
9792 CI.setOperand(0,
9793 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009794 Changed = true;
9795 }
Chris Lattnera935db82008-05-28 05:30:41 +00009796
9797 // memmove(x,x,size) -> noop.
9798 if (MMI->getSource() == MMI->getDest())
9799 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009800 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009801
Chris Lattner95a959d2006-03-06 20:18:44 +00009802 // If we can determine a pointer alignment that is bigger than currently
9803 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009804 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009805 if (Instruction *I = SimplifyMemTransfer(MI))
9806 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009807 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9808 if (Instruction *I = SimplifyMemSet(MSI))
9809 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009810 }
9811
Chris Lattner8b0ea312006-01-13 20:11:04 +00009812 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009813 }
9814
9815 switch (II->getIntrinsicID()) {
9816 default: break;
9817 case Intrinsic::bswap:
9818 // bswap(bswap(x)) -> x
9819 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9820 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9821 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9822 break;
9823 case Intrinsic::ppc_altivec_lvx:
9824 case Intrinsic::ppc_altivec_lvxl:
9825 case Intrinsic::x86_sse_loadu_ps:
9826 case Intrinsic::x86_sse2_loadu_pd:
9827 case Intrinsic::x86_sse2_loadu_dq:
9828 // Turn PPC lvx -> load if the pointer is known aligned.
9829 // Turn X86 loadups -> load if the pointer is known aligned.
9830 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9831 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9832 PointerType::getUnqual(II->getType()),
9833 CI);
9834 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009835 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009836 break;
9837 case Intrinsic::ppc_altivec_stvx:
9838 case Intrinsic::ppc_altivec_stvxl:
9839 // Turn stvx -> store if the pointer is known aligned.
9840 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9841 const Type *OpPtrTy =
9842 PointerType::getUnqual(II->getOperand(1)->getType());
9843 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9844 return new StoreInst(II->getOperand(1), Ptr);
9845 }
9846 break;
9847 case Intrinsic::x86_sse_storeu_ps:
9848 case Intrinsic::x86_sse2_storeu_pd:
9849 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009850 // Turn X86 storeu -> store if the pointer is known aligned.
9851 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9852 const Type *OpPtrTy =
9853 PointerType::getUnqual(II->getOperand(2)->getType());
9854 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9855 return new StoreInst(II->getOperand(2), Ptr);
9856 }
9857 break;
9858
9859 case Intrinsic::x86_sse_cvttss2si: {
9860 // These intrinsics only demands the 0th element of its input vector. If
9861 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009862 unsigned VWidth =
9863 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9864 APInt DemandedElts(VWidth, 1);
9865 APInt UndefElts(VWidth, 0);
9866 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009867 UndefElts)) {
9868 II->setOperand(1, V);
9869 return II;
9870 }
9871 break;
9872 }
9873
9874 case Intrinsic::ppc_altivec_vperm:
9875 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9876 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9877 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009878
Chris Lattner0521e3c2008-06-18 04:33:20 +00009879 // Check that all of the elements are integer constants or undefs.
9880 bool AllEltsOk = true;
9881 for (unsigned i = 0; i != 16; ++i) {
9882 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9883 !isa<UndefValue>(Mask->getOperand(i))) {
9884 AllEltsOk = false;
9885 break;
9886 }
9887 }
9888
9889 if (AllEltsOk) {
9890 // Cast the input vectors to byte vectors.
9891 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9892 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9893 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009894
Chris Lattner0521e3c2008-06-18 04:33:20 +00009895 // Only extract each element once.
9896 Value *ExtractedElts[32];
9897 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9898
Chris Lattnere2ed0572006-04-06 19:19:17 +00009899 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009900 if (isa<UndefValue>(Mask->getOperand(i)))
9901 continue;
9902 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9903 Idx &= 31; // Match the hardware behavior.
9904
9905 if (ExtractedElts[Idx] == 0) {
9906 Instruction *Elt =
9907 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9908 InsertNewInstBefore(Elt, CI);
9909 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009910 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009911
Chris Lattner0521e3c2008-06-18 04:33:20 +00009912 // Insert this value into the result vector.
9913 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9914 i, "tmp");
9915 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009916 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009917 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009918 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009919 }
9920 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009921
Chris Lattner0521e3c2008-06-18 04:33:20 +00009922 case Intrinsic::stackrestore: {
9923 // If the save is right next to the restore, remove the restore. This can
9924 // happen when variable allocas are DCE'd.
9925 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9926 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9927 BasicBlock::iterator BI = SS;
9928 if (&*++BI == II)
9929 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009930 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009931 }
9932
9933 // Scan down this block to see if there is another stack restore in the
9934 // same block without an intervening call/alloca.
9935 BasicBlock::iterator BI = II;
9936 TerminatorInst *TI = II->getParent()->getTerminator();
9937 bool CannotRemove = false;
9938 for (++BI; &*BI != TI; ++BI) {
9939 if (isa<AllocaInst>(BI)) {
9940 CannotRemove = true;
9941 break;
9942 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009943 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9944 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9945 // If there is a stackrestore below this one, remove this one.
9946 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9947 return EraseInstFromFunction(CI);
9948 // Otherwise, ignore the intrinsic.
9949 } else {
9950 // If we found a non-intrinsic call, we can't remove the stack
9951 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009952 CannotRemove = true;
9953 break;
9954 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009955 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009956 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009957
9958 // If the stack restore is in a return/unwind block and if there are no
9959 // allocas or calls between the restore and the return, nuke the restore.
9960 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9961 return EraseInstFromFunction(CI);
9962 break;
9963 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009964 }
9965
Chris Lattner8b0ea312006-01-13 20:11:04 +00009966 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009967}
9968
9969// InvokeInst simplification
9970//
9971Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009972 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009973}
9974
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009975/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9976/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009977static bool isSafeToEliminateVarargsCast(const CallSite CS,
9978 const CastInst * const CI,
9979 const TargetData * const TD,
9980 const int ix) {
9981 if (!CI->isLosslessCast())
9982 return false;
9983
9984 // The size of ByVal arguments is derived from the type, so we
9985 // can't change to a type with a different size. If the size were
9986 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009987 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009988 return true;
9989
9990 const Type* SrcTy =
9991 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9992 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9993 if (!SrcTy->isSized() || !DstTy->isSized())
9994 return false;
Duncan Sands777d2302009-05-09 07:06:46 +00009995 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009996 return false;
9997 return true;
9998}
9999
Chris Lattnera44d8a22003-10-07 22:32:43 +000010000// visitCallSite - Improvements for call and invoke instructions.
10001//
10002Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010003 bool Changed = false;
10004
10005 // If the callee is a constexpr cast of a function, attempt to move the cast
10006 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010007 if (transformConstExprCastCall(CS)) return 0;
10008
Chris Lattner6c266db2003-10-07 22:54:13 +000010009 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010010
Chris Lattner08b22ec2005-05-13 07:09:09 +000010011 if (Function *CalleeF = dyn_cast<Function>(Callee))
10012 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10013 Instruction *OldCall = CS.getInstruction();
10014 // If the call and callee calling conventions don't match, this call must
10015 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010016 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010017 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
10018 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010019 if (!OldCall->use_empty())
10020 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10021 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10022 return EraseInstFromFunction(*OldCall);
10023 return 0;
10024 }
10025
Chris Lattner17be6352004-10-18 02:59:09 +000010026 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10027 // This instruction is not reachable, just remove it. We insert a store to
10028 // undef so that we know that this code is not reachable, despite the fact
10029 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010030 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010031 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010032 CS.getInstruction());
10033
10034 if (!CS.getInstruction()->use_empty())
10035 CS.getInstruction()->
10036 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10037
10038 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10039 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010040 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10041 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010042 }
Chris Lattner17be6352004-10-18 02:59:09 +000010043 return EraseInstFromFunction(*CS.getInstruction());
10044 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010045
Duncan Sandscdb6d922007-09-17 10:26:40 +000010046 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10047 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10048 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10049 return transformCallThroughTrampoline(CS);
10050
Chris Lattner6c266db2003-10-07 22:54:13 +000010051 const PointerType *PTy = cast<PointerType>(Callee->getType());
10052 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10053 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010054 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010055 // See if we can optimize any arguments passed through the varargs area of
10056 // the call.
10057 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010058 E = CS.arg_end(); I != E; ++I, ++ix) {
10059 CastInst *CI = dyn_cast<CastInst>(*I);
10060 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10061 *I = CI->getOperand(0);
10062 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010063 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010064 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010065 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010066
Duncan Sandsf0c33542007-12-19 21:13:37 +000010067 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010068 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010069 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010070 Changed = true;
10071 }
10072
Chris Lattner6c266db2003-10-07 22:54:13 +000010073 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010074}
10075
Chris Lattner9fe38862003-06-19 17:00:31 +000010076// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10077// attempt to move the cast to the arguments of the call/invoke.
10078//
10079bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10080 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10081 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010082 if (CE->getOpcode() != Instruction::BitCast ||
10083 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010084 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010085 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010086 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010087 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010088
10089 // Okay, this is a cast from a function to a different type. Unless doing so
10090 // would cause a type conversion of one of our arguments, change this call to
10091 // be a direct call with arguments casted to the appropriate types.
10092 //
10093 const FunctionType *FT = Callee->getFunctionType();
10094 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010095 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010096
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010097 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010098 return false; // TODO: Handle multiple return values.
10099
Chris Lattnerf78616b2004-01-14 06:06:08 +000010100 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010101 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010102 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010103 // Conversion is ok if changing from one pointer type to another or from
10104 // a pointer to an integer of the same size.
10105 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +000010106 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010107 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010108
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010109 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010110 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010111 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010112 return false; // Cannot transform this return value.
10113
Chris Lattner58d74912008-03-12 17:45:29 +000010114 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010115 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010116 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010117 return false; // Attribute not compatible with transformed value.
10118 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010119
Chris Lattnerf78616b2004-01-14 06:06:08 +000010120 // If the callsite is an invoke instruction, and the return value is used by
10121 // a PHI node in a successor, we cannot change the return type of the call
10122 // because there is no place to put the cast instruction (without breaking
10123 // the critical edge). Bail out in this case.
10124 if (!Caller->use_empty())
10125 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10126 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10127 UI != E; ++UI)
10128 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10129 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010130 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010131 return false;
10132 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010133
10134 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10135 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010136
Chris Lattner9fe38862003-06-19 17:00:31 +000010137 CallSite::arg_iterator AI = CS.arg_begin();
10138 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10139 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010140 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010141
10142 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010143 return false; // Cannot transform this parameter value.
10144
Devang Patel19c87462008-09-26 22:53:05 +000010145 if (CallerPAL.getParamAttributes(i + 1)
10146 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010147 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010148
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010149 // Converting from one pointer type to another or between a pointer and an
10150 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010151 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010152 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10153 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010154 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010155 }
10156
10157 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010158 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010159 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010160
Chris Lattner58d74912008-03-12 17:45:29 +000010161 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10162 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010163 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010164 // won't be dropping them. Check that these extra arguments have attributes
10165 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010166 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10167 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010168 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010169 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010170 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010171 return false;
10172 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010173
Chris Lattner9fe38862003-06-19 17:00:31 +000010174 // Okay, we decided that this is a safe thing to do: go ahead and start
10175 // inserting cast instructions as necessary...
10176 std::vector<Value*> Args;
10177 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010178 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010179 attrVec.reserve(NumCommonArgs);
10180
10181 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010182 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010183
10184 // If the return value is not being used, the type may not be compatible
10185 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010186 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010187
10188 // Add the new return attributes.
10189 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010190 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010191
10192 AI = CS.arg_begin();
10193 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10194 const Type *ParamTy = FT->getParamType(i);
10195 if ((*AI)->getType() == ParamTy) {
10196 Args.push_back(*AI);
10197 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010198 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010199 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010200 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010201 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010202 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010203
10204 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010205 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010206 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010207 }
10208
10209 // If the function takes more arguments than the call was taking, add them
10210 // now...
10211 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10212 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10213
10214 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010215 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010216 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010217 cerr << "WARNING: While resolving call to function '"
10218 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010219 } else {
10220 // Add all of the arguments in their promoted form to the arg list...
10221 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10222 const Type *PTy = getPromotedType((*AI)->getType());
10223 if (PTy != (*AI)->getType()) {
10224 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010225 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10226 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010227 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010228 InsertNewInstBefore(Cast, *Caller);
10229 Args.push_back(Cast);
10230 } else {
10231 Args.push_back(*AI);
10232 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010233
Duncan Sandse1e520f2008-01-13 08:02:44 +000010234 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010235 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010236 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010237 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010238 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010239 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010240
Devang Patel19c87462008-09-26 22:53:05 +000010241 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10242 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10243
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010244 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010245 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010246
Devang Patel05988662008-09-25 21:00:45 +000010247 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010248
Chris Lattner9fe38862003-06-19 17:00:31 +000010249 Instruction *NC;
10250 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010251 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010252 Args.begin(), Args.end(),
10253 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010254 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010255 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010256 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010257 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10258 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010259 CallInst *CI = cast<CallInst>(Caller);
10260 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010261 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010262 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010263 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010264 }
10265
Chris Lattner6934a042007-02-11 01:23:03 +000010266 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010267 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010268 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010269 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010270 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010271 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010272 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010273
10274 // If this is an invoke instruction, we should insert it after the first
10275 // non-phi, instruction in the normal successor block.
10276 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010277 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010278 InsertNewInstBefore(NC, *I);
10279 } else {
10280 // Otherwise, it's a call, just insert cast right after the call instr
10281 InsertNewInstBefore(NC, *Caller);
10282 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010283 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010284 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +000010285 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010286 }
10287 }
10288
10289 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10290 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010291 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010292 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010293 return true;
10294}
10295
Duncan Sandscdb6d922007-09-17 10:26:40 +000010296// transformCallThroughTrampoline - Turn a call to a function created by the
10297// init_trampoline intrinsic into a direct call to the underlying function.
10298//
10299Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10300 Value *Callee = CS.getCalledValue();
10301 const PointerType *PTy = cast<PointerType>(Callee->getType());
10302 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010303 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010304
10305 // If the call already has the 'nest' attribute somewhere then give up -
10306 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010307 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010308 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010309
10310 IntrinsicInst *Tramp =
10311 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10312
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010313 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010314 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10315 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10316
Devang Patel05988662008-09-25 21:00:45 +000010317 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010318 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010319 unsigned NestIdx = 1;
10320 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010321 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010322
10323 // Look for a parameter marked with the 'nest' attribute.
10324 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10325 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010326 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010327 // Record the parameter type and any other attributes.
10328 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010329 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010330 break;
10331 }
10332
10333 if (NestTy) {
10334 Instruction *Caller = CS.getInstruction();
10335 std::vector<Value*> NewArgs;
10336 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10337
Devang Patel05988662008-09-25 21:00:45 +000010338 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010339 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010340
Duncan Sandscdb6d922007-09-17 10:26:40 +000010341 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010342 // mean appending it. Likewise for attributes.
10343
Devang Patel19c87462008-09-26 22:53:05 +000010344 // Add any result attributes.
10345 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010346 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010347
Duncan Sandscdb6d922007-09-17 10:26:40 +000010348 {
10349 unsigned Idx = 1;
10350 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10351 do {
10352 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010353 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010354 Value *NestVal = Tramp->getOperand(3);
10355 if (NestVal->getType() != NestTy)
10356 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10357 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010358 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010359 }
10360
10361 if (I == E)
10362 break;
10363
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010364 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010365 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010366 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010367 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010368 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010369
10370 ++Idx, ++I;
10371 } while (1);
10372 }
10373
Devang Patel19c87462008-09-26 22:53:05 +000010374 // Add any function attributes.
10375 if (Attributes Attr = Attrs.getFnAttributes())
10376 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10377
Duncan Sandscdb6d922007-09-17 10:26:40 +000010378 // The trampoline may have been bitcast to a bogus type (FTy).
10379 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010380 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010381
Duncan Sandscdb6d922007-09-17 10:26:40 +000010382 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010383 NewTypes.reserve(FTy->getNumParams()+1);
10384
Duncan Sandscdb6d922007-09-17 10:26:40 +000010385 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010386 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010387 {
10388 unsigned Idx = 1;
10389 FunctionType::param_iterator I = FTy->param_begin(),
10390 E = FTy->param_end();
10391
10392 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010393 if (Idx == NestIdx)
10394 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010395 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010396
10397 if (I == E)
10398 break;
10399
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010400 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010401 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010402
10403 ++Idx, ++I;
10404 } while (1);
10405 }
10406
10407 // Replace the trampoline call with a direct call. Let the generic
10408 // code sort out any function type mismatches.
10409 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +000010410 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010411 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10412 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010413 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010414
10415 Instruction *NewCaller;
10416 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010417 NewCaller = InvokeInst::Create(NewCallee,
10418 II->getNormalDest(), II->getUnwindDest(),
10419 NewArgs.begin(), NewArgs.end(),
10420 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010421 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010422 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010423 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010424 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10425 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010426 if (cast<CallInst>(Caller)->isTailCall())
10427 cast<CallInst>(NewCaller)->setTailCall();
10428 cast<CallInst>(NewCaller)->
10429 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010430 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010431 }
10432 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10433 Caller->replaceAllUsesWith(NewCaller);
10434 Caller->eraseFromParent();
10435 RemoveFromWorkList(Caller);
10436 return 0;
10437 }
10438 }
10439
10440 // Replace the trampoline call with a direct call. Since there is no 'nest'
10441 // parameter, there is no need to adjust the argument list. Let the generic
10442 // code sort out any function type mismatches.
10443 Constant *NewCallee =
10444 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10445 CS.setCalledFunction(NewCallee);
10446 return CS.getInstruction();
10447}
10448
Chris Lattner7da52b22006-11-01 04:51:18 +000010449/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10450/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10451/// and a single binop.
10452Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10453 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010454 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010455 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010456 Value *LHSVal = FirstInst->getOperand(0);
10457 Value *RHSVal = FirstInst->getOperand(1);
10458
10459 const Type *LHSType = LHSVal->getType();
10460 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010461
10462 // Scan to see if all operands are the same opcode, all have one use, and all
10463 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010464 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010465 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010466 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010467 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010468 // types or GEP's with different index types.
10469 I->getOperand(0)->getType() != LHSType ||
10470 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010471 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010472
10473 // If they are CmpInst instructions, check their predicates
10474 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10475 if (cast<CmpInst>(I)->getPredicate() !=
10476 cast<CmpInst>(FirstInst)->getPredicate())
10477 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010478
10479 // Keep track of which operand needs a phi node.
10480 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10481 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010482 }
10483
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010484 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010485
Chris Lattner7da52b22006-11-01 04:51:18 +000010486 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010487 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010488 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010489 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010490 NewLHS = PHINode::Create(LHSType,
10491 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010492 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10493 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010494 InsertNewInstBefore(NewLHS, PN);
10495 LHSVal = NewLHS;
10496 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010497
10498 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010499 NewRHS = PHINode::Create(RHSType,
10500 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010501 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10502 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010503 InsertNewInstBefore(NewRHS, PN);
10504 RHSVal = NewRHS;
10505 }
10506
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010507 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010508 if (NewLHS || NewRHS) {
10509 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10510 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10511 if (NewLHS) {
10512 Value *NewInLHS = InInst->getOperand(0);
10513 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10514 }
10515 if (NewRHS) {
10516 Value *NewInRHS = InInst->getOperand(1);
10517 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10518 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010519 }
10520 }
10521
Chris Lattner7da52b22006-11-01 04:51:18 +000010522 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010523 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010524 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10525 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10526 RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010527}
10528
Chris Lattner05f18922008-12-01 02:34:36 +000010529Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10530 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10531
10532 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10533 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010534 // This is true if all GEP bases are allocas and if all indices into them are
10535 // constants.
10536 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010537
10538 // Scan to see if all operands are the same opcode, all have one use, and all
10539 // kill their operands (i.e. the operands have one use).
10540 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10541 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10542 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10543 GEP->getNumOperands() != FirstInst->getNumOperands())
10544 return 0;
10545
Chris Lattner36d3e322009-02-21 00:46:50 +000010546 // Keep track of whether or not all GEPs are of alloca pointers.
10547 if (AllBasePointersAreAllocas &&
10548 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10549 !GEP->hasAllConstantIndices()))
10550 AllBasePointersAreAllocas = false;
10551
Chris Lattner05f18922008-12-01 02:34:36 +000010552 // Compare the operand lists.
10553 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10554 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10555 continue;
10556
10557 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10558 // if one of the PHIs has a constant for the index. The index may be
10559 // substantially cheaper to compute for the constants, so making it a
10560 // variable index could pessimize the path. This also handles the case
10561 // for struct indices, which must always be constant.
10562 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10563 isa<ConstantInt>(GEP->getOperand(op)))
10564 return 0;
10565
10566 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10567 return 0;
10568 FixedOperands[op] = 0; // Needs a PHI.
10569 }
10570 }
10571
Chris Lattner36d3e322009-02-21 00:46:50 +000010572 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010573 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010574 // offset calculation, but all the predecessors will have to materialize the
10575 // stack address into a register anyway. We'd actually rather *clone* the
10576 // load up into the predecessors so that we have a load of a gep of an alloca,
10577 // which can usually all be folded into the load.
10578 if (AllBasePointersAreAllocas)
10579 return 0;
10580
Chris Lattner05f18922008-12-01 02:34:36 +000010581 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10582 // that is variable.
10583 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10584
10585 bool HasAnyPHIs = false;
10586 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10587 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10588 Value *FirstOp = FirstInst->getOperand(i);
10589 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10590 FirstOp->getName()+".pn");
10591 InsertNewInstBefore(NewPN, PN);
10592
10593 NewPN->reserveOperandSpace(e);
10594 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10595 OperandPhis[i] = NewPN;
10596 FixedOperands[i] = NewPN;
10597 HasAnyPHIs = true;
10598 }
10599
10600
10601 // Add all operands to the new PHIs.
10602 if (HasAnyPHIs) {
10603 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10604 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10605 BasicBlock *InBB = PN.getIncomingBlock(i);
10606
10607 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10608 if (PHINode *OpPhi = OperandPhis[op])
10609 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10610 }
10611 }
10612
10613 Value *Base = FixedOperands[0];
10614 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10615 FixedOperands.end());
10616}
10617
10618
Chris Lattner21550882009-02-23 05:56:17 +000010619/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10620/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010621/// obvious the value of the load is not changed from the point of the load to
10622/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010623///
10624/// Finally, it is safe, but not profitable, to sink a load targetting a
10625/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10626/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010627static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010628 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10629
10630 for (++BBI; BBI != E; ++BBI)
10631 if (BBI->mayWriteToMemory())
10632 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010633
10634 // Check for non-address taken alloca. If not address-taken already, it isn't
10635 // profitable to do this xform.
10636 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10637 bool isAddressTaken = false;
10638 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10639 UI != E; ++UI) {
10640 if (isa<LoadInst>(UI)) continue;
10641 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10642 // If storing TO the alloca, then the address isn't taken.
10643 if (SI->getOperand(1) == AI) continue;
10644 }
10645 isAddressTaken = true;
10646 break;
10647 }
10648
Chris Lattner36d3e322009-02-21 00:46:50 +000010649 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010650 return false;
10651 }
10652
Chris Lattner36d3e322009-02-21 00:46:50 +000010653 // If this load is a load from a GEP with a constant offset from an alloca,
10654 // then we don't want to sink it. In its present form, it will be
10655 // load [constant stack offset]. Sinking it will cause us to have to
10656 // materialize the stack addresses in each predecessor in a register only to
10657 // do a shared load from register in the successor.
10658 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10659 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10660 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10661 return false;
10662
Chris Lattner76c73142006-11-01 07:13:54 +000010663 return true;
10664}
10665
Chris Lattner9fe38862003-06-19 17:00:31 +000010666
Chris Lattnerbac32862004-11-14 19:13:23 +000010667// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10668// operator and they all are only used by the PHI, PHI together their
10669// inputs, and do the operation once, to the result of the PHI.
10670Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10671 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10672
10673 // Scan the instruction, looking for input operations that can be folded away.
10674 // If all input operands to the phi are the same instruction (e.g. a cast from
10675 // the same type or "+42") we can pull the operation through the PHI, reducing
10676 // code size and simplifying code.
10677 Constant *ConstantOp = 0;
10678 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010679 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010680 if (isa<CastInst>(FirstInst)) {
10681 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010682 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010683 // Can fold binop, compare or shift here if the RHS is a constant,
10684 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010685 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010686 if (ConstantOp == 0)
10687 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010688 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10689 isVolatile = LI->isVolatile();
10690 // We can't sink the load if the loaded value could be modified between the
10691 // load and the PHI.
10692 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010693 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010694 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010695
10696 // If the PHI is of volatile loads and the load block has multiple
10697 // successors, sinking it would remove a load of the volatile value from
10698 // the path through the other successor.
10699 if (isVolatile &&
10700 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10701 return 0;
10702
Chris Lattner9c080502006-11-01 07:43:41 +000010703 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010704 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010705 } else {
10706 return 0; // Cannot fold this operation.
10707 }
10708
10709 // Check to see if all arguments are the same operation.
10710 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10711 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10712 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010713 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010714 return 0;
10715 if (CastSrcTy) {
10716 if (I->getOperand(0)->getType() != CastSrcTy)
10717 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010718 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010719 // We can't sink the load if the loaded value could be modified between
10720 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010721 if (LI->isVolatile() != isVolatile ||
10722 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010723 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010724 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010725
Chris Lattner71042962008-07-08 17:18:32 +000010726 // If the PHI is of volatile loads and the load block has multiple
10727 // successors, sinking it would remove a load of the volatile value from
10728 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010729 if (isVolatile &&
10730 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10731 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010732
Chris Lattnerbac32862004-11-14 19:13:23 +000010733 } else if (I->getOperand(1) != ConstantOp) {
10734 return 0;
10735 }
10736 }
10737
10738 // Okay, they are all the same operation. Create a new PHI node of the
10739 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010740 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10741 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010742 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010743
10744 Value *InVal = FirstInst->getOperand(0);
10745 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010746
10747 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010748 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10749 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10750 if (NewInVal != InVal)
10751 InVal = 0;
10752 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10753 }
10754
10755 Value *PhiVal;
10756 if (InVal) {
10757 // The new PHI unions all of the same values together. This is really
10758 // common, so we handle it intelligently here for compile-time speed.
10759 PhiVal = InVal;
10760 delete NewPN;
10761 } else {
10762 InsertNewInstBefore(NewPN, PN);
10763 PhiVal = NewPN;
10764 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010765
Chris Lattnerbac32862004-11-14 19:13:23 +000010766 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010767 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010768 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010769 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010770 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010771 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010772 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010773 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010774 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10775
10776 // If this was a volatile load that we are merging, make sure to loop through
10777 // and mark all the input loads as non-volatile. If we don't do this, we will
10778 // insert a new volatile load and the old ones will not be deletable.
10779 if (isVolatile)
10780 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10781 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10782
10783 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010784}
Chris Lattnera1be5662002-05-02 17:06:02 +000010785
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010786/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10787/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010788static bool DeadPHICycle(PHINode *PN,
10789 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010790 if (PN->use_empty()) return true;
10791 if (!PN->hasOneUse()) return false;
10792
10793 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010794 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010795 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010796
10797 // Don't scan crazily complex things.
10798 if (PotentiallyDeadPHIs.size() == 16)
10799 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010800
10801 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10802 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010803
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010804 return false;
10805}
10806
Chris Lattnercf5008a2007-11-06 21:52:06 +000010807/// PHIsEqualValue - Return true if this phi node is always equal to
10808/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10809/// z = some value; x = phi (y, z); y = phi (x, z)
10810static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10811 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10812 // See if we already saw this PHI node.
10813 if (!ValueEqualPHIs.insert(PN))
10814 return true;
10815
10816 // Don't scan crazily complex things.
10817 if (ValueEqualPHIs.size() == 16)
10818 return false;
10819
10820 // Scan the operands to see if they are either phi nodes or are equal to
10821 // the value.
10822 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10823 Value *Op = PN->getIncomingValue(i);
10824 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10825 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10826 return false;
10827 } else if (Op != NonPhiInVal)
10828 return false;
10829 }
10830
10831 return true;
10832}
10833
10834
Chris Lattner473945d2002-05-06 18:06:38 +000010835// PHINode simplification
10836//
Chris Lattner7e708292002-06-25 16:13:24 +000010837Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010838 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010839 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010840
Owen Anderson7e057142006-07-10 22:03:18 +000010841 if (Value *V = PN.hasConstantValue())
10842 return ReplaceInstUsesWith(PN, V);
10843
Owen Anderson7e057142006-07-10 22:03:18 +000010844 // If all PHI operands are the same operation, pull them through the PHI,
10845 // reducing code size.
10846 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010847 isa<Instruction>(PN.getIncomingValue(1)) &&
10848 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10849 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10850 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10851 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010852 PN.getIncomingValue(0)->hasOneUse())
10853 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10854 return Result;
10855
10856 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10857 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10858 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010859 if (PN.hasOneUse()) {
10860 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10861 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010862 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010863 PotentiallyDeadPHIs.insert(&PN);
10864 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10865 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10866 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010867
10868 // If this phi has a single use, and if that use just computes a value for
10869 // the next iteration of a loop, delete the phi. This occurs with unused
10870 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10871 // common case here is good because the only other things that catch this
10872 // are induction variable analysis (sometimes) and ADCE, which is only run
10873 // late.
10874 if (PHIUser->hasOneUse() &&
10875 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10876 PHIUser->use_back() == &PN) {
10877 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10878 }
10879 }
Owen Anderson7e057142006-07-10 22:03:18 +000010880
Chris Lattnercf5008a2007-11-06 21:52:06 +000010881 // We sometimes end up with phi cycles that non-obviously end up being the
10882 // same value, for example:
10883 // z = some value; x = phi (y, z); y = phi (x, z)
10884 // where the phi nodes don't necessarily need to be in the same block. Do a
10885 // quick check to see if the PHI node only contains a single non-phi value, if
10886 // so, scan to see if the phi cycle is actually equal to that value.
10887 {
10888 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10889 // Scan for the first non-phi operand.
10890 while (InValNo != NumOperandVals &&
10891 isa<PHINode>(PN.getIncomingValue(InValNo)))
10892 ++InValNo;
10893
10894 if (InValNo != NumOperandVals) {
10895 Value *NonPhiInVal = PN.getOperand(InValNo);
10896
10897 // Scan the rest of the operands to see if there are any conflicts, if so
10898 // there is no need to recursively scan other phis.
10899 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10900 Value *OpVal = PN.getIncomingValue(InValNo);
10901 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10902 break;
10903 }
10904
10905 // If we scanned over all operands, then we have one unique value plus
10906 // phi values. Scan PHI nodes to see if they all merge in each other or
10907 // the value.
10908 if (InValNo == NumOperandVals) {
10909 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10910 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10911 return ReplaceInstUsesWith(PN, NonPhiInVal);
10912 }
10913 }
10914 }
Chris Lattner60921c92003-12-19 05:58:40 +000010915 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010916}
10917
Reid Spencer17212df2006-12-12 09:18:51 +000010918static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10919 Instruction *InsertPoint,
10920 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010921 unsigned PtrSize = DTy->getScalarSizeInBits();
10922 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010923 // We must cast correctly to the pointer type. Ensure that we
10924 // sign extend the integer value if it is smaller as this is
10925 // used for address computation.
10926 Instruction::CastOps opcode =
10927 (VTySize < PtrSize ? Instruction::SExt :
10928 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10929 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010930}
10931
Chris Lattnera1be5662002-05-02 17:06:02 +000010932
Chris Lattner7e708292002-06-25 16:13:24 +000010933Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010934 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010935 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010936 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010937 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010938 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010939
Chris Lattnere87597f2004-10-16 18:11:37 +000010940 if (isa<UndefValue>(GEP.getOperand(0)))
10941 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10942
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010943 bool HasZeroPointerIndex = false;
10944 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10945 HasZeroPointerIndex = C->isNullValue();
10946
10947 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010948 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010949
Chris Lattner28977af2004-04-05 01:30:19 +000010950 // Eliminate unneeded casts for indices.
10951 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010952
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010953 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010954 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10955 i != e; ++i, ++GTI) {
Sanjiv Gupta7787d4a2009-04-24 02:37:54 +000010956 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010957 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010958 if (CI->getOpcode() == Instruction::ZExt ||
10959 CI->getOpcode() == Instruction::SExt) {
10960 const Type *SrcTy = CI->getOperand(0)->getType();
10961 // We can eliminate a cast from i32 to i64 iff the target
10962 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000010963 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010964 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010965 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010966 }
10967 }
10968 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010969 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010970 // to what we need. If narrower, sign-extend it to what we need.
10971 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010972 // insert it. This explicit cast can make subsequent optimizations more
10973 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010974 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010975 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010976 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010977 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010978 MadeChange = true;
10979 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010980 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10981 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010982 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010983 MadeChange = true;
10984 }
Dan Gohman4f833d42008-09-11 23:06:38 +000010985 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10986 if (Constant *C = dyn_cast<Constant>(Op)) {
10987 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10988 MadeChange = true;
10989 } else {
10990 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10991 GEP);
10992 *i = Op;
10993 MadeChange = true;
10994 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010995 }
Chris Lattner28977af2004-04-05 01:30:19 +000010996 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010997 }
Chris Lattner28977af2004-04-05 01:30:19 +000010998 if (MadeChange) return &GEP;
10999
Chris Lattner90ac28c2002-08-02 19:29:35 +000011000 // Combine Indices - If the source pointer to this getelementptr instruction
11001 // is a getelementptr instruction, combine the indices of the two
11002 // getelementptr instructions into a single instruction.
11003 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011004 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000011005 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000011006 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000011007
11008 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011009 // Note that if our source is a gep chain itself that we wait for that
11010 // chain to be resolved before we perform this transformation. This
11011 // avoids us creating a TON of code in some cases.
11012 //
11013 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11014 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11015 return 0; // Wait until our source is folded to completion.
11016
Chris Lattner72588fc2007-02-15 22:48:32 +000011017 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011018
11019 // Find out whether the last index in the source GEP is a sequential idx.
11020 bool EndsWithSequential = false;
11021 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11022 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011023 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011024
Chris Lattner90ac28c2002-08-02 19:29:35 +000011025 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011026 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011027 // Replace: gep (gep %P, long B), long A, ...
11028 // With: T = long A+B; gep %P, T, ...
11029 //
Chris Lattner620ce142004-05-07 22:09:22 +000011030 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000011031 if (SO1 == Constant::getNullValue(SO1->getType())) {
11032 Sum = GO1;
11033 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11034 Sum = SO1;
11035 } else {
11036 // If they aren't the same type, convert both to an integer of the
11037 // target's pointer size.
11038 if (SO1->getType() != GO1->getType()) {
11039 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000011040 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011041 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000011042 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011043 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000011044 unsigned PS = TD->getPointerSizeInBits();
11045 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011046 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011047 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011048
Duncan Sands514ab342007-11-01 20:53:16 +000011049 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011050 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011051 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011052 } else {
11053 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011054 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11055 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011056 }
11057 }
11058 }
Chris Lattner620ce142004-05-07 22:09:22 +000011059 if (isa<Constant>(SO1) && isa<Constant>(GO1))
11060 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
11061 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011062 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011063 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011064 }
Chris Lattner28977af2004-04-05 01:30:19 +000011065 }
Chris Lattner620ce142004-05-07 22:09:22 +000011066
11067 // Recycle the GEP we already have if possible.
11068 if (SrcGEPOperands.size() == 2) {
11069 GEP.setOperand(0, SrcGEPOperands[0]);
11070 GEP.setOperand(1, Sum);
11071 return &GEP;
11072 } else {
11073 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11074 SrcGEPOperands.end()-1);
11075 Indices.push_back(Sum);
11076 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11077 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011078 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011079 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011080 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011081 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011082 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11083 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011084 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11085 }
11086
11087 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011088 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11089 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011090
Chris Lattner620ce142004-05-07 22:09:22 +000011091 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011092 // GEP of global variable. If all of the indices for this GEP are
11093 // constants, we can promote this to a constexpr instead of an instruction.
11094
11095 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011096 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011097 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11098 for (; I != E && isa<Constant>(*I); ++I)
11099 Indices.push_back(cast<Constant>(*I));
11100
11101 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011102 Constant *CE = ConstantExpr::getGetElementPtr(GV,
11103 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011104
11105 // Replace all uses of the GEP with the new constexpr...
11106 return ReplaceInstUsesWith(GEP, CE);
11107 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011108 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011109 if (!isa<PointerType>(X->getType())) {
11110 // Not interesting. Source pointer must be a cast from pointer.
11111 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011112 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11113 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011114 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011115 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11116 // into : GEP i8* X, ...
11117 //
Chris Lattnereed48272005-09-13 00:40:14 +000011118 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011119 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11120 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011121 if (const ArrayType *CATy =
11122 dyn_cast<ArrayType>(CPTy->getElementType())) {
11123 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11124 if (CATy->getElementType() == XTy->getElementType()) {
11125 // -> GEP i8* X, ...
11126 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11127 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11128 GEP.getName());
11129 } else if (const ArrayType *XATy =
11130 dyn_cast<ArrayType>(XTy->getElementType())) {
11131 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011132 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011133 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011134 // At this point, we know that the cast source type is a pointer
11135 // to an array of the same type as the destination pointer
11136 // array. Because the array type is never stepped over (there
11137 // is a leading zero) we can fold the cast into this GEP.
11138 GEP.setOperand(0, X);
11139 return &GEP;
11140 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011141 }
11142 }
Chris Lattnereed48272005-09-13 00:40:14 +000011143 } else if (GEP.getNumOperands() == 2) {
11144 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011145 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11146 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011147 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11148 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11149 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011150 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11151 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011152 Value *Idx[2];
11153 Idx[0] = Constant::getNullValue(Type::Int32Ty);
11154 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011155 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011156 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011157 // V and GEP are both pointer types --> BitCast
11158 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011159 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011160
11161 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011162 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011163 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011164 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011165
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011166 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011167 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011168 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011169
11170 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11171 // allow either a mul, shift, or constant here.
11172 Value *NewIdx = 0;
11173 ConstantInt *Scale = 0;
11174 if (ArrayEltSize == 1) {
11175 NewIdx = GEP.getOperand(1);
Dan Gohman6de29f82009-06-15 22:12:54 +000011176 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011177 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000011178 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011179 Scale = CI;
11180 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11181 if (Inst->getOpcode() == Instruction::Shl &&
11182 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011183 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11184 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Dan Gohman6de29f82009-06-15 22:12:54 +000011185 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11186 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011187 NewIdx = Inst->getOperand(0);
11188 } else if (Inst->getOpcode() == Instruction::Mul &&
11189 isa<ConstantInt>(Inst->getOperand(1))) {
11190 Scale = cast<ConstantInt>(Inst->getOperand(1));
11191 NewIdx = Inst->getOperand(0);
11192 }
11193 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011194
Chris Lattner7835cdd2005-09-13 18:36:04 +000011195 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011196 // out, perform the transformation. Note, we don't know whether Scale is
11197 // signed or not. We'll use unsigned version of division/modulo
11198 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011199 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011200 Scale->getZExtValue() % ArrayEltSize == 0) {
11201 Scale = ConstantInt::get(Scale->getType(),
11202 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011203 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000011204 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011205 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011206 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011207 NewIdx = InsertNewInstBefore(Sc, GEP);
11208 }
11209
11210 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011211 Value *Idx[2];
11212 Idx[0] = Constant::getNullValue(Type::Int32Ty);
11213 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011214 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011215 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011216 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11217 // The NewGEP must be pointer typed, so must the old one -> BitCast
11218 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011219 }
11220 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011221 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011222 }
Chris Lattner58407792009-01-09 04:53:57 +000011223
Chris Lattner46cd5a12009-01-09 05:44:56 +000011224 /// See if we can simplify:
11225 /// X = bitcast A to B*
11226 /// Y = gep X, <...constant indices...>
11227 /// into a gep of the original struct. This is important for SROA and alias
11228 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011229 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011230 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11231 // Determine how much the GEP moves the pointer. We are guaranteed to get
11232 // a constant back from EmitGEPOffset.
11233 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11234 int64_t Offset = OffsetV->getSExtValue();
11235
11236 // If this GEP instruction doesn't move the pointer, just replace the GEP
11237 // with a bitcast of the real input to the dest type.
11238 if (Offset == 0) {
11239 // If the bitcast is of an allocation, and the allocation will be
11240 // converted to match the type of the cast, don't touch this.
11241 if (isa<AllocationInst>(BCI->getOperand(0))) {
11242 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11243 if (Instruction *I = visitBitCast(*BCI)) {
11244 if (I != BCI) {
11245 I->takeName(BCI);
11246 BCI->getParent()->getInstList().insert(BCI, I);
11247 ReplaceInstUsesWith(*BCI, I);
11248 }
11249 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011250 }
Chris Lattner58407792009-01-09 04:53:57 +000011251 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011252 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011253 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011254
11255 // Otherwise, if the offset is non-zero, we need to find out if there is a
11256 // field at Offset in 'A's type. If so, we can pull the cast through the
11257 // GEP.
11258 SmallVector<Value*, 8> NewIndices;
11259 const Type *InTy =
11260 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11261 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11262 Instruction *NGEP =
11263 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11264 NewIndices.end());
11265 if (NGEP->getType() == GEP.getType()) return NGEP;
11266 InsertNewInstBefore(NGEP, GEP);
11267 NGEP->takeName(&GEP);
11268 return new BitCastInst(NGEP, GEP.getType());
11269 }
Chris Lattner58407792009-01-09 04:53:57 +000011270 }
11271 }
11272
Chris Lattner8a2a3112001-12-14 16:52:21 +000011273 return 0;
11274}
11275
Chris Lattner0864acf2002-11-04 16:18:53 +000011276Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11277 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011278 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011279 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11280 const Type *NewTy =
11281 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011282 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011283
11284 // Create and insert the replacement instruction...
11285 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000011286 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011287 else {
11288 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000011289 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011290 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011291
11292 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011293
Chris Lattner0864acf2002-11-04 16:18:53 +000011294 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011295 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011296 //
11297 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011298 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011299
11300 // Now that I is pointing to the first non-allocation-inst in the block,
11301 // insert our getelementptr instruction...
11302 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000011303 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011304 Value *Idx[2];
11305 Idx[0] = NullIdx;
11306 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011307 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11308 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011309
11310 // Now make everything use the getelementptr instead of the original
11311 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011312 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011313 } else if (isa<UndefValue>(AI.getArraySize())) {
11314 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011315 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011316 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011317
Dan Gohman6893cd72009-01-13 20:18:38 +000011318 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11319 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011320 // Note that we only do this for alloca's, because malloc should allocate
11321 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011322 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Dan Gohman6893cd72009-01-13 20:18:38 +000011323 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11324
11325 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11326 if (AI.getAlignment() == 0)
11327 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11328 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011329
Chris Lattner0864acf2002-11-04 16:18:53 +000011330 return 0;
11331}
11332
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011333Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11334 Value *Op = FI.getOperand(0);
11335
Chris Lattner17be6352004-10-18 02:59:09 +000011336 // free undef -> unreachable.
11337 if (isa<UndefValue>(Op)) {
11338 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000011339 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011340 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011341 return EraseInstFromFunction(FI);
11342 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011343
Chris Lattner6160e852004-02-28 04:57:37 +000011344 // If we have 'free null' delete the instruction. This can happen in stl code
11345 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011346 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011347 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011348
11349 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11350 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11351 FI.setOperand(0, CI->getOperand(0));
11352 return &FI;
11353 }
11354
11355 // Change free (gep X, 0,0,0,0) into free(X)
11356 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11357 if (GEPI->hasAllZeroIndices()) {
11358 AddToWorkList(GEPI);
11359 FI.setOperand(0, GEPI->getOperand(0));
11360 return &FI;
11361 }
11362 }
11363
11364 // Change free(malloc) into nothing, if the malloc has a single use.
11365 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11366 if (MI->hasOneUse()) {
11367 EraseInstFromFunction(FI);
11368 return EraseInstFromFunction(*MI);
11369 }
Chris Lattner6160e852004-02-28 04:57:37 +000011370
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011371 return 0;
11372}
11373
11374
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011375/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011376static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011377 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011378 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011379 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000011380
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011381 if (TD) {
11382 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11383 // Instead of loading constant c string, use corresponding integer value
11384 // directly if string length is small enough.
11385 std::string Str;
11386 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11387 unsigned len = Str.length();
11388 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11389 unsigned numBits = Ty->getPrimitiveSizeInBits();
11390 // Replace LI with immediate integer store.
11391 if ((numBits >> 3) == len + 1) {
11392 APInt StrVal(numBits, 0);
11393 APInt SingleChar(numBits, 0);
11394 if (TD->isLittleEndian()) {
11395 for (signed i = len-1; i >= 0; i--) {
11396 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11397 StrVal = (StrVal << 8) | SingleChar;
11398 }
11399 } else {
11400 for (unsigned i = 0; i < len; i++) {
11401 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11402 StrVal = (StrVal << 8) | SingleChar;
11403 }
11404 // Append NULL at the end.
11405 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011406 StrVal = (StrVal << 8) | SingleChar;
11407 }
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011408 Value *NL = ConstantInt::get(StrVal);
11409 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011410 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011411 }
11412 }
11413 }
11414
Mon P Wang6753f952009-02-07 22:19:29 +000011415 const PointerType *DestTy = cast<PointerType>(CI->getType());
11416 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011417 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011418
11419 // If the address spaces don't match, don't eliminate the cast.
11420 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11421 return 0;
11422
Chris Lattnerb89e0712004-07-13 01:49:43 +000011423 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011424
Reid Spencer42230162007-01-22 05:51:25 +000011425 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011426 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011427 // If the source is an array, the code below will not succeed. Check to
11428 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11429 // constants.
11430 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11431 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11432 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011433 Value *Idxs[2];
11434 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11435 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011436 SrcTy = cast<PointerType>(CastOp->getType());
11437 SrcPTy = SrcTy->getElementType();
11438 }
11439
Reid Spencer42230162007-01-22 05:51:25 +000011440 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011441 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011442 // Do not allow turning this into a load of an integer, which is then
11443 // casted to a pointer, this pessimizes pointer analysis a lot.
11444 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011445 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11446 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011447
Chris Lattnerf9527852005-01-31 04:50:46 +000011448 // Okay, we are casting from one integer or pointer type to another of
11449 // the same size. Instead of casting the pointer before the load, cast
11450 // the result of the loaded value.
11451 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11452 CI->getName(),
11453 LI.isVolatile()),LI);
11454 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011455 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011456 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011457 }
11458 }
11459 return 0;
11460}
11461
Chris Lattner833b8a42003-06-26 05:06:25 +000011462Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11463 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011464
Dan Gohman9941f742007-07-20 16:34:21 +000011465 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011466 unsigned KnownAlign =
11467 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011468 if (KnownAlign >
11469 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11470 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011471 LI.setAlignment(KnownAlign);
11472
Chris Lattner37366c12005-05-01 04:24:53 +000011473 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011474 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011475 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011476 return Res;
11477
11478 // None of the following transforms are legal for volatile loads.
11479 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011480
Dan Gohman2276a7b2008-10-15 23:19:35 +000011481 // Do really simple store-to-load forwarding and load CSE, to catch cases
11482 // where there are several consequtive memory accesses to the same location,
11483 // separated by a few arithmetic operations.
11484 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011485 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11486 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011487
Christopher Lambb15147e2007-12-29 07:56:53 +000011488 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11489 const Value *GEPI0 = GEPI->getOperand(0);
11490 // TODO: Consider a target hook for valid address spaces for this xform.
11491 if (isa<ConstantPointerNull>(GEPI0) &&
11492 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011493 // Insert a new store to null instruction before the load to indicate
11494 // that this code is not reachable. We do this instead of inserting
11495 // an unreachable instruction directly because we cannot modify the
11496 // CFG.
11497 new StoreInst(UndefValue::get(LI.getType()),
11498 Constant::getNullValue(Op->getType()), &LI);
11499 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11500 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011501 }
Chris Lattner37366c12005-05-01 04:24:53 +000011502
Chris Lattnere87597f2004-10-16 18:11:37 +000011503 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011504 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011505 // TODO: Consider a target hook for valid address spaces for this xform.
11506 if (isa<UndefValue>(C) || (C->isNullValue() &&
11507 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011508 // Insert a new store to null instruction before the load to indicate that
11509 // this code is not reachable. We do this instead of inserting an
11510 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000011511 new StoreInst(UndefValue::get(LI.getType()),
11512 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000011513 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011514 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011515
Chris Lattnere87597f2004-10-16 18:11:37 +000011516 // Instcombine load (constant global) into the value loaded.
11517 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011518 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011519 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011520
Chris Lattnere87597f2004-10-16 18:11:37 +000011521 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011522 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011523 if (CE->getOpcode() == Instruction::GetElementPtr) {
11524 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011525 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011526 if (Constant *V =
11527 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011528 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011529 if (CE->getOperand(0)->isNullValue()) {
11530 // Insert a new store to null instruction before the load to indicate
11531 // that this code is not reachable. We do this instead of inserting
11532 // an unreachable instruction directly because we cannot modify the
11533 // CFG.
11534 new StoreInst(UndefValue::get(LI.getType()),
11535 Constant::getNullValue(Op->getType()), &LI);
11536 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11537 }
11538
Reid Spencer3da59db2006-11-27 01:05:10 +000011539 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011540 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011541 return Res;
11542 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011543 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011544 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011545
11546 // If this load comes from anywhere in a constant global, and if the global
11547 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011548 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011549 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011550 if (GV->getInitializer()->isNullValue())
11551 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11552 else if (isa<UndefValue>(GV->getInitializer()))
11553 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11554 }
11555 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011556
Chris Lattner37366c12005-05-01 04:24:53 +000011557 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011558 // Change select and PHI nodes to select values instead of addresses: this
11559 // helps alias analysis out a lot, allows many others simplifications, and
11560 // exposes redundancy in the code.
11561 //
11562 // Note that we cannot do the transformation unless we know that the
11563 // introduced loads cannot trap! Something like this is valid as long as
11564 // the condition is always false: load (select bool %C, int* null, int* %G),
11565 // but it would not be valid if we transformed it to load from null
11566 // unconditionally.
11567 //
11568 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11569 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011570 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11571 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011572 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011573 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011574 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011575 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011576 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011577 }
11578
Chris Lattner684fe212004-09-23 15:46:00 +000011579 // load (select (cond, null, P)) -> load P
11580 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11581 if (C->isNullValue()) {
11582 LI.setOperand(0, SI->getOperand(2));
11583 return &LI;
11584 }
11585
11586 // load (select (cond, P, null)) -> load P
11587 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11588 if (C->isNullValue()) {
11589 LI.setOperand(0, SI->getOperand(1));
11590 return &LI;
11591 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011592 }
11593 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011594 return 0;
11595}
11596
Reid Spencer55af2b52007-01-19 21:20:31 +000011597/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011598/// when possible. This makes it generally easy to do alias analysis and/or
11599/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011600static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11601 User *CI = cast<User>(SI.getOperand(1));
11602 Value *CastOp = CI->getOperand(0);
11603
11604 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011605 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11606 if (SrcTy == 0) return 0;
11607
11608 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011609
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011610 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11611 return 0;
11612
Chris Lattner3914f722009-01-24 01:00:13 +000011613 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11614 /// to its first element. This allows us to handle things like:
11615 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11616 /// on 32-bit hosts.
11617 SmallVector<Value*, 4> NewGEPIndices;
11618
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011619 // If the source is an array, the code below will not succeed. Check to
11620 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11621 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011622 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11623 // Index through pointer.
11624 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11625 NewGEPIndices.push_back(Zero);
11626
11627 while (1) {
11628 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011629 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011630 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011631 NewGEPIndices.push_back(Zero);
11632 SrcPTy = STy->getElementType(0);
11633 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11634 NewGEPIndices.push_back(Zero);
11635 SrcPTy = ATy->getElementType();
11636 } else {
11637 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011638 }
Chris Lattner3914f722009-01-24 01:00:13 +000011639 }
11640
11641 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11642 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011643
11644 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11645 return 0;
11646
Chris Lattner71759c42009-01-16 20:12:52 +000011647 // If the pointers point into different address spaces or if they point to
11648 // values with different sizes, we can't do the transformation.
11649 if (SrcTy->getAddressSpace() !=
11650 cast<PointerType>(CI->getType())->getAddressSpace() ||
11651 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011652 IC.getTargetData().getTypeSizeInBits(DestPTy))
11653 return 0;
11654
11655 // Okay, we are casting from one integer or pointer type to another of
11656 // the same size. Instead of casting the pointer before
11657 // the store, cast the value to be stored.
11658 Value *NewCast;
11659 Value *SIOp0 = SI.getOperand(0);
11660 Instruction::CastOps opcode = Instruction::BitCast;
11661 const Type* CastSrcTy = SIOp0->getType();
11662 const Type* CastDstTy = SrcPTy;
11663 if (isa<PointerType>(CastDstTy)) {
11664 if (CastSrcTy->isInteger())
11665 opcode = Instruction::IntToPtr;
11666 } else if (isa<IntegerType>(CastDstTy)) {
11667 if (isa<PointerType>(SIOp0->getType()))
11668 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011669 }
Chris Lattner3914f722009-01-24 01:00:13 +000011670
11671 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11672 // emit a GEP to index into its first field.
11673 if (!NewGEPIndices.empty()) {
11674 if (Constant *C = dyn_cast<Constant>(CastOp))
11675 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11676 NewGEPIndices.size());
11677 else
11678 CastOp = IC.InsertNewInstBefore(
11679 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11680 NewGEPIndices.end()), SI);
11681 }
11682
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011683 if (Constant *C = dyn_cast<Constant>(SIOp0))
11684 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11685 else
11686 NewCast = IC.InsertNewInstBefore(
11687 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11688 SI);
11689 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011690}
11691
Chris Lattner4aebaee2008-11-27 08:56:30 +000011692/// equivalentAddressValues - Test if A and B will obviously have the same
11693/// value. This includes recognizing that %t0 and %t1 will have the same
11694/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011695/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011696/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011697/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011698/// %t2 = load i32* %t1
11699///
11700static bool equivalentAddressValues(Value *A, Value *B) {
11701 // Test if the values are trivially equivalent.
11702 if (A == B) return true;
11703
11704 // Test if the values come form identical arithmetic instructions.
11705 if (isa<BinaryOperator>(A) ||
11706 isa<CastInst>(A) ||
11707 isa<PHINode>(A) ||
11708 isa<GetElementPtrInst>(A))
11709 if (Instruction *BI = dyn_cast<Instruction>(B))
11710 if (cast<Instruction>(A)->isIdenticalTo(BI))
11711 return true;
11712
11713 // Otherwise they may not be equivalent.
11714 return false;
11715}
11716
Dale Johannesen4945c652009-03-03 21:26:39 +000011717// If this instruction has two uses, one of which is a llvm.dbg.declare,
11718// return the llvm.dbg.declare.
11719DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11720 if (!V->hasNUses(2))
11721 return 0;
11722 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11723 UI != E; ++UI) {
11724 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11725 return DI;
11726 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11727 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11728 return DI;
11729 }
11730 }
11731 return 0;
11732}
11733
Chris Lattner2f503e62005-01-31 05:36:43 +000011734Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11735 Value *Val = SI.getOperand(0);
11736 Value *Ptr = SI.getOperand(1);
11737
11738 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011739 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011740 ++NumCombined;
11741 return 0;
11742 }
Chris Lattner836692d2007-01-15 06:51:56 +000011743
11744 // If the RHS is an alloca with a single use, zapify the store, making the
11745 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011746 // If the RHS is an alloca with a two uses, the other one being a
11747 // llvm.dbg.declare, zapify the store and the declare, making the
11748 // alloca dead. We must do this to prevent declare's from affecting
11749 // codegen.
11750 if (!SI.isVolatile()) {
11751 if (Ptr->hasOneUse()) {
11752 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011753 EraseInstFromFunction(SI);
11754 ++NumCombined;
11755 return 0;
11756 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011757 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11758 if (isa<AllocaInst>(GEP->getOperand(0))) {
11759 if (GEP->getOperand(0)->hasOneUse()) {
11760 EraseInstFromFunction(SI);
11761 ++NumCombined;
11762 return 0;
11763 }
11764 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11765 EraseInstFromFunction(*DI);
11766 EraseInstFromFunction(SI);
11767 ++NumCombined;
11768 return 0;
11769 }
11770 }
11771 }
11772 }
11773 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11774 EraseInstFromFunction(*DI);
11775 EraseInstFromFunction(SI);
11776 ++NumCombined;
11777 return 0;
11778 }
Chris Lattner836692d2007-01-15 06:51:56 +000011779 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011780
Dan Gohman9941f742007-07-20 16:34:21 +000011781 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011782 unsigned KnownAlign =
11783 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011784 if (KnownAlign >
11785 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11786 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011787 SI.setAlignment(KnownAlign);
11788
Dale Johannesenacb51a32009-03-03 01:43:03 +000011789 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011790 // stores to the same location, separated by a few arithmetic operations. This
11791 // situation often occurs with bitfield accesses.
11792 BasicBlock::iterator BBI = &SI;
11793 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11794 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011795 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011796 // Don't count debug info directives, lest they affect codegen,
11797 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11798 // It is necessary for correctness to skip those that feed into a
11799 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011800 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011801 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011802 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011803 continue;
11804 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011805
11806 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11807 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011808 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11809 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011810 ++NumDeadStore;
11811 ++BBI;
11812 EraseInstFromFunction(*PrevSI);
11813 continue;
11814 }
11815 break;
11816 }
11817
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011818 // If this is a load, we have to stop. However, if the loaded value is from
11819 // the pointer we're loading and is producing the pointer we're storing,
11820 // then *this* store is dead (X = load P; store X -> P).
11821 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011822 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11823 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011824 EraseInstFromFunction(SI);
11825 ++NumCombined;
11826 return 0;
11827 }
11828 // Otherwise, this is a load from some other location. Stores before it
11829 // may not be dead.
11830 break;
11831 }
11832
Chris Lattner9ca96412006-02-08 03:25:32 +000011833 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011834 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011835 break;
11836 }
11837
11838
11839 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011840
11841 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011842 if (isa<ConstantPointerNull>(Ptr) &&
11843 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011844 if (!isa<UndefValue>(Val)) {
11845 SI.setOperand(0, UndefValue::get(Val->getType()));
11846 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011847 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011848 ++NumCombined;
11849 }
11850 return 0; // Do not modify these!
11851 }
11852
11853 // store undef, Ptr -> noop
11854 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011855 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011856 ++NumCombined;
11857 return 0;
11858 }
11859
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011860 // If the pointer destination is a cast, see if we can fold the cast into the
11861 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011862 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011863 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11864 return Res;
11865 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011866 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011867 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11868 return Res;
11869
Chris Lattner408902b2005-09-12 23:23:25 +000011870
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011871 // If this store is the last instruction in the basic block (possibly
11872 // excepting debug info instructions and the pointer bitcasts that feed
11873 // into them), and if the block ends with an unconditional branch, try
11874 // to move it to the successor block.
11875 BBI = &SI;
11876 do {
11877 ++BBI;
11878 } while (isa<DbgInfoIntrinsic>(BBI) ||
11879 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011880 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011881 if (BI->isUnconditional())
11882 if (SimplifyStoreAtEndOfBlock(SI))
11883 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011884
Chris Lattner2f503e62005-01-31 05:36:43 +000011885 return 0;
11886}
11887
Chris Lattner3284d1f2007-04-15 00:07:55 +000011888/// SimplifyStoreAtEndOfBlock - Turn things like:
11889/// if () { *P = v1; } else { *P = v2 }
11890/// into a phi node with a store in the successor.
11891///
Chris Lattner31755a02007-04-15 01:02:18 +000011892/// Simplify things like:
11893/// *P = v1; if () { *P = v2; }
11894/// into a phi node with a store in the successor.
11895///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011896bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11897 BasicBlock *StoreBB = SI.getParent();
11898
11899 // Check to see if the successor block has exactly two incoming edges. If
11900 // so, see if the other predecessor contains a store to the same location.
11901 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011902 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011903
11904 // Determine whether Dest has exactly two predecessors and, if so, compute
11905 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011906 pred_iterator PI = pred_begin(DestBB);
11907 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011908 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011909 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011910 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011911 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011912 return false;
11913
11914 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011915 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011916 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011917 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011918 }
Chris Lattner31755a02007-04-15 01:02:18 +000011919 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011920 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011921
11922 // Bail out if all the relevant blocks aren't distinct (this can happen,
11923 // for example, if SI is in an infinite loop)
11924 if (StoreBB == DestBB || OtherBB == DestBB)
11925 return false;
11926
Chris Lattner31755a02007-04-15 01:02:18 +000011927 // Verify that the other block ends in a branch and is not otherwise empty.
11928 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011929 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011930 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011931 return false;
11932
Chris Lattner31755a02007-04-15 01:02:18 +000011933 // If the other block ends in an unconditional branch, check for the 'if then
11934 // else' case. there is an instruction before the branch.
11935 StoreInst *OtherStore = 0;
11936 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011937 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011938 // Skip over debugging info.
11939 while (isa<DbgInfoIntrinsic>(BBI) ||
11940 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11941 if (BBI==OtherBB->begin())
11942 return false;
11943 --BBI;
11944 }
11945 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011946 OtherStore = dyn_cast<StoreInst>(BBI);
11947 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11948 return false;
11949 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011950 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011951 // destinations is StoreBB, then we have the if/then case.
11952 if (OtherBr->getSuccessor(0) != StoreBB &&
11953 OtherBr->getSuccessor(1) != StoreBB)
11954 return false;
11955
11956 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011957 // if/then triangle. See if there is a store to the same ptr as SI that
11958 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011959 for (;; --BBI) {
11960 // Check to see if we find the matching store.
11961 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11962 if (OtherStore->getOperand(1) != SI.getOperand(1))
11963 return false;
11964 break;
11965 }
Eli Friedman6903a242008-06-13 22:02:12 +000011966 // If we find something that may be using or overwriting the stored
11967 // value, or if we run out of instructions, we can't do the xform.
11968 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011969 BBI == OtherBB->begin())
11970 return false;
11971 }
11972
11973 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011974 // make sure nothing reads or overwrites the stored value in
11975 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011976 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11977 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011978 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011979 return false;
11980 }
11981 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011982
Chris Lattner31755a02007-04-15 01:02:18 +000011983 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011984 Value *MergedVal = OtherStore->getOperand(0);
11985 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011986 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011987 PN->reserveOperandSpace(2);
11988 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011989 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11990 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011991 }
11992
11993 // Advance to a place where it is safe to insert the new store and
11994 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011995 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011996 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11997 OtherStore->isVolatile()), *BBI);
11998
11999 // Nuke the old stores.
12000 EraseInstFromFunction(SI);
12001 EraseInstFromFunction(*OtherStore);
12002 ++NumCombined;
12003 return true;
12004}
12005
Chris Lattner2f503e62005-01-31 05:36:43 +000012006
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012007Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12008 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012009 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012010 BasicBlock *TrueDest;
12011 BasicBlock *FalseDest;
12012 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12013 !isa<Constant>(X)) {
12014 // Swap Destinations and condition...
12015 BI.setCondition(X);
12016 BI.setSuccessor(0, FalseDest);
12017 BI.setSuccessor(1, TrueDest);
12018 return &BI;
12019 }
12020
Reid Spencere4d87aa2006-12-23 06:05:41 +000012021 // Cannonicalize fcmp_one -> fcmp_oeq
12022 FCmpInst::Predicate FPred; Value *Y;
12023 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
12024 TrueDest, FalseDest)))
12025 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12026 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12027 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012028 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000012029 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
12030 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012031 // Swap Destinations and condition...
12032 BI.setCondition(NewSCC);
12033 BI.setSuccessor(0, FalseDest);
12034 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012035 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012036 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012037 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012038 return &BI;
12039 }
12040
12041 // Cannonicalize icmp_ne -> icmp_eq
12042 ICmpInst::Predicate IPred;
12043 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12044 TrueDest, FalseDest)))
12045 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12046 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12047 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12048 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012049 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000012050 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
12051 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012052 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012053 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012054 BI.setSuccessor(0, FalseDest);
12055 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012056 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012057 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012058 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012059 return &BI;
12060 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012061
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012062 return 0;
12063}
Chris Lattner0864acf2002-11-04 16:18:53 +000012064
Chris Lattner46238a62004-07-03 00:26:11 +000012065Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12066 Value *Cond = SI.getCondition();
12067 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12068 if (I->getOpcode() == Instruction::Add)
12069 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12070 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12071 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000012072 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012073 AddRHS));
12074 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012075 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012076 return &SI;
12077 }
12078 }
12079 return 0;
12080}
12081
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012082Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012083 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012084
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012085 if (!EV.hasIndices())
12086 return ReplaceInstUsesWith(EV, Agg);
12087
12088 if (Constant *C = dyn_cast<Constant>(Agg)) {
12089 if (isa<UndefValue>(C))
12090 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12091
12092 if (isa<ConstantAggregateZero>(C))
12093 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12094
12095 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12096 // Extract the element indexed by the first index out of the constant
12097 Value *V = C->getOperand(*EV.idx_begin());
12098 if (EV.getNumIndices() > 1)
12099 // Extract the remaining indices out of the constant indexed by the
12100 // first index
12101 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12102 else
12103 return ReplaceInstUsesWith(EV, V);
12104 }
12105 return 0; // Can't handle other constants
12106 }
12107 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12108 // We're extracting from an insertvalue instruction, compare the indices
12109 const unsigned *exti, *exte, *insi, *inse;
12110 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12111 exte = EV.idx_end(), inse = IV->idx_end();
12112 exti != exte && insi != inse;
12113 ++exti, ++insi) {
12114 if (*insi != *exti)
12115 // The insert and extract both reference distinctly different elements.
12116 // This means the extract is not influenced by the insert, and we can
12117 // replace the aggregate operand of the extract with the aggregate
12118 // operand of the insert. i.e., replace
12119 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12120 // %E = extractvalue { i32, { i32 } } %I, 0
12121 // with
12122 // %E = extractvalue { i32, { i32 } } %A, 0
12123 return ExtractValueInst::Create(IV->getAggregateOperand(),
12124 EV.idx_begin(), EV.idx_end());
12125 }
12126 if (exti == exte && insi == inse)
12127 // Both iterators are at the end: Index lists are identical. Replace
12128 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12129 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12130 // with "i32 42"
12131 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12132 if (exti == exte) {
12133 // The extract list is a prefix of the insert list. i.e. replace
12134 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12135 // %E = extractvalue { i32, { i32 } } %I, 1
12136 // with
12137 // %X = extractvalue { i32, { i32 } } %A, 1
12138 // %E = insertvalue { i32 } %X, i32 42, 0
12139 // by switching the order of the insert and extract (though the
12140 // insertvalue should be left in, since it may have other uses).
12141 Value *NewEV = InsertNewInstBefore(
12142 ExtractValueInst::Create(IV->getAggregateOperand(),
12143 EV.idx_begin(), EV.idx_end()),
12144 EV);
12145 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12146 insi, inse);
12147 }
12148 if (insi == inse)
12149 // The insert list is a prefix of the extract list
12150 // We can simply remove the common indices from the extract and make it
12151 // operate on the inserted value instead of the insertvalue result.
12152 // i.e., replace
12153 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12154 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12155 // with
12156 // %E extractvalue { i32 } { i32 42 }, 0
12157 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12158 exti, exte);
12159 }
12160 // Can't simplify extracts from other values. Note that nested extracts are
12161 // already simplified implicitely by the above (extract ( extract (insert) )
12162 // will be translated into extract ( insert ( extract ) ) first and then just
12163 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012164 return 0;
12165}
12166
Chris Lattner220b0cf2006-03-05 00:22:33 +000012167/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12168/// is to leave as a vector operation.
12169static bool CheapToScalarize(Value *V, bool isConstant) {
12170 if (isa<ConstantAggregateZero>(V))
12171 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012172 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012173 if (isConstant) return true;
12174 // If all elts are the same, we can extract.
12175 Constant *Op0 = C->getOperand(0);
12176 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12177 if (C->getOperand(i) != Op0)
12178 return false;
12179 return true;
12180 }
12181 Instruction *I = dyn_cast<Instruction>(V);
12182 if (!I) return false;
12183
12184 // Insert element gets simplified to the inserted element or is deleted if
12185 // this is constant idx extract element and its a constant idx insertelt.
12186 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12187 isa<ConstantInt>(I->getOperand(2)))
12188 return true;
12189 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12190 return true;
12191 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12192 if (BO->hasOneUse() &&
12193 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12194 CheapToScalarize(BO->getOperand(1), isConstant)))
12195 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012196 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12197 if (CI->hasOneUse() &&
12198 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12199 CheapToScalarize(CI->getOperand(1), isConstant)))
12200 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012201
12202 return false;
12203}
12204
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012205/// Read and decode a shufflevector mask.
12206///
12207/// It turns undef elements into values that are larger than the number of
12208/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012209static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12210 unsigned NElts = SVI->getType()->getNumElements();
12211 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12212 return std::vector<unsigned>(NElts, 0);
12213 if (isa<UndefValue>(SVI->getOperand(2)))
12214 return std::vector<unsigned>(NElts, 2*NElts);
12215
12216 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012217 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012218 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12219 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012220 Result.push_back(NElts*2); // undef -> 8
12221 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012222 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012223 return Result;
12224}
12225
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012226/// FindScalarElement - Given a vector and an element number, see if the scalar
12227/// value is already around as a register, for example if it were inserted then
12228/// extracted from the vector.
12229static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012230 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12231 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012232 unsigned Width = PTy->getNumElements();
12233 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012234 return UndefValue::get(PTy->getElementType());
12235
12236 if (isa<UndefValue>(V))
12237 return UndefValue::get(PTy->getElementType());
12238 else if (isa<ConstantAggregateZero>(V))
12239 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012240 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012241 return CP->getOperand(EltNo);
12242 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12243 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012244 if (!isa<ConstantInt>(III->getOperand(2)))
12245 return 0;
12246 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012247
12248 // If this is an insert to the element we are looking for, return the
12249 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012250 if (EltNo == IIElt)
12251 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012252
12253 // Otherwise, the insertelement doesn't modify the value, recurse on its
12254 // vector input.
12255 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000012256 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012257 unsigned LHSWidth =
12258 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012259 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012260 if (InEl < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012261 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012262 else if (InEl < LHSWidth*2)
12263 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000012264 else
12265 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012266 }
12267
12268 // Otherwise, we don't know.
12269 return 0;
12270}
12271
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012272Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012273 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012274 if (isa<UndefValue>(EI.getOperand(0)))
12275 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12276
Dan Gohman07a96762007-07-16 14:29:03 +000012277 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012278 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12279 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12280
Reid Spencer9d6565a2007-02-15 02:26:10 +000012281 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012282 // If vector val is constant with all elements the same, replace EI with
12283 // that element. When the elements are not identical, we cannot replace yet
12284 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012285 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012286 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012287 if (C->getOperand(i) != op0) {
12288 op0 = 0;
12289 break;
12290 }
12291 if (op0)
12292 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012293 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000012294
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012295 // If extracting a specified index from the vector, see if we can recursively
12296 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012297 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012298 unsigned IndexVal = IdxC->getZExtValue();
12299 unsigned VectorWidth =
12300 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12301
12302 // If this is extracting an invalid index, turn this into undef, to avoid
12303 // crashing the code below.
12304 if (IndexVal >= VectorWidth)
12305 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12306
Chris Lattner867b99f2006-10-05 06:55:50 +000012307 // This instruction only demands the single element from the input vector.
12308 // If the input vector has a single use, simplify it based on this use
12309 // property.
Chris Lattner85464092007-04-09 01:37:55 +000012310 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012311 APInt UndefElts(VectorWidth, 0);
12312 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012313 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012314 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012315 EI.setOperand(0, V);
12316 return &EI;
12317 }
12318 }
12319
Reid Spencerb83eb642006-10-20 07:07:24 +000012320 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012321 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012322
12323 // If the this extractelement is directly using a bitcast from a vector of
12324 // the same number of elements, see if we can find the source element from
12325 // it. In this case, we will end up needing to bitcast the scalars.
12326 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12327 if (const VectorType *VT =
12328 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12329 if (VT->getNumElements() == VectorWidth)
12330 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12331 return new BitCastInst(Elt, EI.getType());
12332 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012333 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012334
Chris Lattner73fa49d2006-05-25 22:53:38 +000012335 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012336 if (I->hasOneUse()) {
12337 // Push extractelement into predecessor operation if legal and
12338 // profitable to do so
12339 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012340 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12341 if (CheapToScalarize(BO, isConstantElt)) {
12342 ExtractElementInst *newEI0 =
12343 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12344 EI.getName()+".lhs");
12345 ExtractElementInst *newEI1 =
12346 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12347 EI.getName()+".rhs");
12348 InsertNewInstBefore(newEI0, EI);
12349 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012350 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012351 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012352 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012353 unsigned AS =
12354 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012355 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12356 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012357 GetElementPtrInst *GEP =
12358 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012359 InsertNewInstBefore(GEP, EI);
12360 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012361 }
12362 }
12363 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12364 // Extracting the inserted element?
12365 if (IE->getOperand(2) == EI.getOperand(1))
12366 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12367 // If the inserted and extracted elements are constants, they must not
12368 // be the same value, extract from the pre-inserted value instead.
12369 if (isa<Constant>(IE->getOperand(2)) &&
12370 isa<Constant>(EI.getOperand(1))) {
12371 AddUsesToWorkList(EI);
12372 EI.setOperand(0, IE->getOperand(0));
12373 return &EI;
12374 }
12375 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12376 // If this is extracting an element from a shufflevector, figure out where
12377 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012378 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12379 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012380 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012381 unsigned LHSWidth =
12382 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12383
12384 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012385 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012386 else if (SrcIdx < LHSWidth*2) {
12387 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012388 Src = SVI->getOperand(1);
12389 } else {
12390 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012391 }
Chris Lattner867b99f2006-10-05 06:55:50 +000012392 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012393 }
12394 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012395 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012396 return 0;
12397}
12398
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012399/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12400/// elements from either LHS or RHS, return the shuffle mask and true.
12401/// Otherwise, return false.
12402static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12403 std::vector<Constant*> &Mask) {
12404 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12405 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012406 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012407
12408 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012409 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012410 return true;
12411 } else if (V == LHS) {
12412 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012413 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012414 return true;
12415 } else if (V == RHS) {
12416 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012417 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012418 return true;
12419 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12420 // If this is an insert of an extract from some other vector, include it.
12421 Value *VecOp = IEI->getOperand(0);
12422 Value *ScalarOp = IEI->getOperand(1);
12423 Value *IdxOp = IEI->getOperand(2);
12424
Chris Lattnerd929f062006-04-27 21:14:21 +000012425 if (!isa<ConstantInt>(IdxOp))
12426 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012427 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012428
12429 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12430 // Okay, we can handle this if the vector we are insertinting into is
12431 // transitively ok.
12432 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12433 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000012434 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012435 return true;
12436 }
12437 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12438 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012439 EI->getOperand(0)->getType() == V->getType()) {
12440 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012441 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012442
12443 // This must be extracting from either LHS or RHS.
12444 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12445 // Okay, we can handle this if the vector we are insertinting into is
12446 // transitively ok.
12447 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12448 // If so, update the mask to reflect the inserted value.
12449 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012450 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012451 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012452 } else {
12453 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012454 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012455 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012456
12457 }
12458 return true;
12459 }
12460 }
12461 }
12462 }
12463 }
12464 // TODO: Handle shufflevector here!
12465
12466 return false;
12467}
12468
12469/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12470/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12471/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012472static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012473 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012474 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012475 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012476 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012477 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012478
12479 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012480 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012481 return V;
12482 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012483 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012484 return V;
12485 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12486 // If this is an insert of an extract from some other vector, include it.
12487 Value *VecOp = IEI->getOperand(0);
12488 Value *ScalarOp = IEI->getOperand(1);
12489 Value *IdxOp = IEI->getOperand(2);
12490
12491 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12492 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12493 EI->getOperand(0)->getType() == V->getType()) {
12494 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012495 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12496 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012497
12498 // Either the extracted from or inserted into vector must be RHSVec,
12499 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012500 if (EI->getOperand(0) == RHS || RHS == 0) {
12501 RHS = EI->getOperand(0);
12502 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012503 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012504 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012505 return V;
12506 }
12507
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012508 if (VecOp == RHS) {
12509 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000012510 // Everything but the extracted element is replaced with the RHS.
12511 for (unsigned i = 0; i != NumElts; ++i) {
12512 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012513 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012514 }
12515 return V;
12516 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012517
12518 // If this insertelement is a chain that comes from exactly these two
12519 // vectors, return the vector and the effective shuffle.
12520 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12521 return EI->getOperand(0);
12522
Chris Lattnerefb47352006-04-15 01:39:45 +000012523 }
12524 }
12525 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012526 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012527
12528 // Otherwise, can't do anything fancy. Return an identity vector.
12529 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012530 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012531 return V;
12532}
12533
12534Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12535 Value *VecOp = IE.getOperand(0);
12536 Value *ScalarOp = IE.getOperand(1);
12537 Value *IdxOp = IE.getOperand(2);
12538
Chris Lattner599ded12007-04-09 01:11:16 +000012539 // Inserting an undef or into an undefined place, remove this.
12540 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12541 ReplaceInstUsesWith(IE, VecOp);
12542
Chris Lattnerefb47352006-04-15 01:39:45 +000012543 // If the inserted element was extracted from some other vector, and if the
12544 // indexes are constant, try to turn this into a shufflevector operation.
12545 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12546 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12547 EI->getOperand(0)->getType() == IE.getType()) {
12548 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012549 unsigned ExtractedIdx =
12550 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012551 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012552
12553 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12554 return ReplaceInstUsesWith(IE, VecOp);
12555
12556 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12557 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12558
12559 // If we are extracting a value from a vector, then inserting it right
12560 // back into the same place, just use the input vector.
12561 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12562 return ReplaceInstUsesWith(IE, VecOp);
12563
12564 // We could theoretically do this for ANY input. However, doing so could
12565 // turn chains of insertelement instructions into a chain of shufflevector
12566 // instructions, and right now we do not merge shufflevectors. As such,
12567 // only do this in a situation where it is clear that there is benefit.
12568 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12569 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12570 // the values of VecOp, except then one read from EIOp0.
12571 // Build a new shuffle mask.
12572 std::vector<Constant*> Mask;
12573 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000012574 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012575 else {
12576 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000012577 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012578 NumVectorElts));
12579 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000012580 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012581 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000012582 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012583 }
12584
12585 // If this insertelement isn't used by some other insertelement, turn it
12586 // (and any insertelements it points to), into one big shuffle.
12587 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12588 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012589 Value *RHS = 0;
12590 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12591 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12592 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000012593 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012594 }
12595 }
12596 }
12597
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012598 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12599 APInt UndefElts(VWidth, 0);
12600 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12601 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12602 return &IE;
12603
Chris Lattnerefb47352006-04-15 01:39:45 +000012604 return 0;
12605}
12606
12607
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012608Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12609 Value *LHS = SVI.getOperand(0);
12610 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012611 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012612
12613 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012614
Chris Lattner867b99f2006-10-05 06:55:50 +000012615 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012616 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012617 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012618
Dan Gohman488fbfc2008-09-09 18:11:14 +000012619 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012620
12621 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12622 return 0;
12623
Evan Cheng388df622009-02-03 10:05:09 +000012624 APInt UndefElts(VWidth, 0);
12625 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12626 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012627 LHS = SVI.getOperand(0);
12628 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012629 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012630 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012631
Chris Lattner863bcff2006-05-25 23:48:38 +000012632 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12633 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12634 if (LHS == RHS || isa<UndefValue>(LHS)) {
12635 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012636 // shuffle(undef,undef,mask) -> undef.
12637 return ReplaceInstUsesWith(SVI, LHS);
12638 }
12639
Chris Lattner863bcff2006-05-25 23:48:38 +000012640 // Remap any references to RHS to use LHS.
12641 std::vector<Constant*> Elts;
12642 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012643 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012644 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012645 else {
12646 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012647 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012648 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000012649 Elts.push_back(UndefValue::get(Type::Int32Ty));
12650 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012651 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000012652 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12653 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012654 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012655 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012656 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012657 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000012658 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012659 LHS = SVI.getOperand(0);
12660 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012661 MadeChange = true;
12662 }
12663
Chris Lattner7b2e27922006-05-26 00:29:06 +000012664 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012665 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012666
Chris Lattner863bcff2006-05-25 23:48:38 +000012667 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12668 if (Mask[i] >= e*2) continue; // Ignore undef values.
12669 // Is this an identity shuffle of the LHS value?
12670 isLHSID &= (Mask[i] == i);
12671
12672 // Is this an identity shuffle of the RHS value?
12673 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012674 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012675
Chris Lattner863bcff2006-05-25 23:48:38 +000012676 // Eliminate identity shuffles.
12677 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12678 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012679
Chris Lattner7b2e27922006-05-26 00:29:06 +000012680 // If the LHS is a shufflevector itself, see if we can combine it with this
12681 // one without producing an unusual shuffle. Here we are really conservative:
12682 // we are absolutely afraid of producing a shuffle mask not in the input
12683 // program, because the code gen may not be smart enough to turn a merged
12684 // shuffle into two specific shuffles: it may produce worse code. As such,
12685 // we only merge two shuffles if the result is one of the two input shuffle
12686 // masks. In this case, merging the shuffles just removes one instruction,
12687 // which we know is safe. This is good for things like turning:
12688 // (splat(splat)) -> splat.
12689 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12690 if (isa<UndefValue>(RHS)) {
12691 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12692
12693 std::vector<unsigned> NewMask;
12694 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12695 if (Mask[i] >= 2*e)
12696 NewMask.push_back(2*e);
12697 else
12698 NewMask.push_back(LHSMask[Mask[i]]);
12699
12700 // If the result mask is equal to the src shuffle or this shuffle mask, do
12701 // the replacement.
12702 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012703 unsigned LHSInNElts =
12704 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012705 std::vector<Constant*> Elts;
12706 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012707 if (NewMask[i] >= LHSInNElts*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012708 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012709 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012710 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012711 }
12712 }
12713 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12714 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000012715 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012716 }
12717 }
12718 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012719
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012720 return MadeChange ? &SVI : 0;
12721}
12722
12723
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012724
Chris Lattnerea1c4542004-12-08 23:43:58 +000012725
12726/// TryToSinkInstruction - Try to move the specified instruction from its
12727/// current block into the beginning of DestBlock, which can only happen if it's
12728/// safe to move the instruction past all of the instructions between it and the
12729/// end of its block.
12730static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12731 assert(I->hasOneUse() && "Invariants didn't hold!");
12732
Chris Lattner108e9022005-10-27 17:13:11 +000012733 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012734 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012735 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012736
Chris Lattnerea1c4542004-12-08 23:43:58 +000012737 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012738 if (isa<AllocaInst>(I) && I->getParent() ==
12739 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012740 return false;
12741
Chris Lattner96a52a62004-12-09 07:14:34 +000012742 // We can only sink load instructions if there is nothing between the load and
12743 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012744 if (I->mayReadFromMemory()) {
12745 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012746 Scan != E; ++Scan)
12747 if (Scan->mayWriteToMemory())
12748 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012749 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012750
Dan Gohman02dea8b2008-05-23 21:05:58 +000012751 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012752
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012753 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012754 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012755 ++NumSunkInst;
12756 return true;
12757}
12758
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012759
12760/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12761/// all reachable code to the worklist.
12762///
12763/// This has a couple of tricks to make the code faster and more powerful. In
12764/// particular, we constant fold and DCE instructions as we go, to avoid adding
12765/// them to the worklist (this significantly speeds up instcombine on code where
12766/// many instructions are dead or constant). Additionally, if we find a branch
12767/// whose condition is a known constant, we only visit the reachable successors.
12768///
12769static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012770 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012771 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012772 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012773 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012774 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012775
Chris Lattner2c7718a2007-03-23 19:17:18 +000012776 while (!Worklist.empty()) {
12777 BB = Worklist.back();
12778 Worklist.pop_back();
12779
12780 // We have now visited this block! If we've already been here, ignore it.
12781 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012782
12783 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012784 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12785 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012786
Chris Lattner2c7718a2007-03-23 19:17:18 +000012787 // DCE instruction if trivially dead.
12788 if (isInstructionTriviallyDead(Inst)) {
12789 ++NumDeadInst;
12790 DOUT << "IC: DCE: " << *Inst;
12791 Inst->eraseFromParent();
12792 continue;
12793 }
12794
12795 // ConstantProp instruction if trivially constant.
12796 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12797 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12798 Inst->replaceAllUsesWith(C);
12799 ++NumConstProp;
12800 Inst->eraseFromParent();
12801 continue;
12802 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012803
Devang Patel7fe1dec2008-11-19 18:56:50 +000012804 // If there are two consecutive llvm.dbg.stoppoint calls then
12805 // it is likely that the optimizer deleted code in between these
12806 // two intrinsics.
12807 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12808 if (DBI_Next) {
12809 if (DBI_Prev
12810 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12811 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12812 IC.RemoveFromWorkList(DBI_Prev);
12813 DBI_Prev->eraseFromParent();
12814 }
12815 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012816 } else {
12817 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012818 }
12819
Chris Lattner2c7718a2007-03-23 19:17:18 +000012820 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012821 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012822
12823 // Recursively visit successors. If this is a branch or switch on a
12824 // constant, only visit the reachable successor.
12825 TerminatorInst *TI = BB->getTerminator();
12826 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12827 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12828 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012829 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012830 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012831 continue;
12832 }
12833 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12834 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12835 // See if this is an explicit destination.
12836 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12837 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012838 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012839 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012840 continue;
12841 }
12842
12843 // Otherwise it is the default destination.
12844 Worklist.push_back(SI->getSuccessor(0));
12845 continue;
12846 }
12847 }
12848
12849 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12850 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012851 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012852}
12853
Chris Lattnerec9c3582007-03-03 02:04:50 +000012854bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012855 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012856 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012857
12858 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12859 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012860
Chris Lattnerb3d59702005-07-07 20:40:38 +000012861 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012862 // Do a depth-first traversal of the function, populate the worklist with
12863 // the reachable instructions. Ignore blocks that are not reachable. Keep
12864 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012865 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012866 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012867
Chris Lattnerb3d59702005-07-07 20:40:38 +000012868 // Do a quick scan over the function. If we find any blocks that are
12869 // unreachable, remove any instructions inside of them. This prevents
12870 // the instcombine code from having to deal with some bad special cases.
12871 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12872 if (!Visited.count(BB)) {
12873 Instruction *Term = BB->getTerminator();
12874 while (Term != BB->begin()) { // Remove instrs bottom-up
12875 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012876
Bill Wendlingb7427032006-11-26 09:46:52 +000012877 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012878 // A debug intrinsic shouldn't force another iteration if we weren't
12879 // going to do one without it.
12880 if (!isa<DbgInfoIntrinsic>(I)) {
12881 ++NumDeadInst;
12882 Changed = true;
12883 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012884 if (!I->use_empty())
12885 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12886 I->eraseFromParent();
12887 }
12888 }
12889 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012890
Chris Lattnerdbab3862007-03-02 21:28:56 +000012891 while (!Worklist.empty()) {
12892 Instruction *I = RemoveOneFromWorkList();
12893 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012894
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012895 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012896 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012897 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012898 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012899 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012900 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012901
Bill Wendlingb7427032006-11-26 09:46:52 +000012902 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012903
12904 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012905 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012906 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012907 continue;
12908 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012909
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012910 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000012911 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012912 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012913
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012914 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012915 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012916 ReplaceInstUsesWith(*I, C);
12917
Chris Lattner62b14df2002-09-02 04:59:56 +000012918 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012919 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012920 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012921 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012922 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012923 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012924
Dan Gohman31e4c772009-05-07 19:43:39 +000012925 if (TD &&
12926 (I->getType()->getTypeID() == Type::VoidTyID ||
12927 I->isTrapping())) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012928 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012929 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12930 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012931 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012932 if (NewC != CE) {
12933 i->set(NewC);
12934 Changed = true;
12935 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012936 }
12937
Chris Lattnerea1c4542004-12-08 23:43:58 +000012938 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012939 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012940 BasicBlock *BB = I->getParent();
12941 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12942 if (UserParent != BB) {
12943 bool UserIsSuccessor = false;
12944 // See if the user is one of our successors.
12945 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12946 if (*SI == UserParent) {
12947 UserIsSuccessor = true;
12948 break;
12949 }
12950
12951 // If the user is one of our immediate successors, and if that successor
12952 // only has us as a predecessors (we'd have to split the critical edge
12953 // otherwise), we can keep going.
12954 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12955 next(pred_begin(UserParent)) == pred_end(UserParent))
12956 // Okay, the CFG is simple enough, try to sink this instruction.
12957 Changed |= TryToSinkInstruction(I, UserParent);
12958 }
12959 }
12960
Chris Lattner8a2a3112001-12-14 16:52:21 +000012961 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012962#ifndef NDEBUG
12963 std::string OrigI;
12964#endif
12965 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012966 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012967 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012968 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012969 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012970 DOUT << "IC: Old = " << *I
12971 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000012972
Chris Lattnerf523d062004-06-09 05:08:07 +000012973 // Everything uses the new instruction now.
12974 I->replaceAllUsesWith(Result);
12975
12976 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012977 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000012978 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012979
Chris Lattner6934a042007-02-11 01:23:03 +000012980 // Move the name to the new instruction first.
12981 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012982
12983 // Insert the new instruction into the basic block...
12984 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012985 BasicBlock::iterator InsertPos = I;
12986
12987 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12988 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12989 ++InsertPos;
12990
12991 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012992
Chris Lattner00d51312004-05-01 23:27:23 +000012993 // Make sure that we reprocess all operands now that we reduced their
12994 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012995 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000012996
Chris Lattnerf523d062004-06-09 05:08:07 +000012997 // Instructions can end up on the worklist more than once. Make sure
12998 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012999 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013000
13001 // Erase the old instruction.
13002 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013003 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013004#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013005 DOUT << "IC: Mod = " << OrigI
13006 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013007#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013008
Chris Lattner90ac28c2002-08-02 19:29:35 +000013009 // If the instruction was modified, it's possible that it is now dead.
13010 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013011 if (isInstructionTriviallyDead(I)) {
13012 // Make sure we process all operands now that we are reducing their
13013 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013014 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013015
Chris Lattner00d51312004-05-01 23:27:23 +000013016 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013017 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013018 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013019 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013020 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013021 AddToWorkList(I);
13022 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013023 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013024 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013025 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013026 }
13027 }
13028
Chris Lattnerec9c3582007-03-03 02:04:50 +000013029 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013030
13031 // Do an explicit clear, this shrinks the map if needed.
13032 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013033 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013034}
13035
Chris Lattnerec9c3582007-03-03 02:04:50 +000013036
13037bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013038 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13039
Chris Lattnerec9c3582007-03-03 02:04:50 +000013040 bool EverMadeChange = false;
13041
13042 // Iterate while there is work to do.
13043 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013044 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013045 EverMadeChange = true;
13046 return EverMadeChange;
13047}
13048
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013049FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013050 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013051}