blob: 162e1bf3a9381d18aa21c0831dab00eeac15d048 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000049#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000051#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000052#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000053#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000054#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000055#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000056#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000059#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000060#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000061#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000062#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000063using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000064using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000065
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000073 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000077 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000078 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000079 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000080 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000081 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000082 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000083 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000084
Chris Lattnerdbab3862007-03-02 21:28:56 +000085 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000089 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000109
Chris Lattnerdbab3862007-03-02 21:28:56 +0000110
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000115 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000118 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000119 }
120
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000127 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000128 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greif177dd3f2008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000141 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000142 // Set the operand to undef to drop the use.
Gabor Greif177dd3f2008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000144 }
145
146 return R;
147 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000148
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000149 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000150 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000151
152 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000153
Chris Lattner97e52e42002-04-28 21:27:06 +0000154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000155 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000156 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000157 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000158 }
159
Chris Lattner28977af2004-04-05 01:30:19 +0000160 TargetData &getTargetData() const { return *TD; }
161
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000166 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000168 //
Chris Lattner7e708292002-06-25 16:13:24 +0000169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000175 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000183 Instruction *visitAnd(BinaryOperator &I);
184 Instruction *visitOr (BinaryOperator &I);
185 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000186 Instruction *visitShl(BinaryOperator &I);
187 Instruction *visitAShr(BinaryOperator &I);
188 Instruction *visitLShr(BinaryOperator &I);
189 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000190 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
191 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000192 Instruction *visitFCmpInst(FCmpInst &I);
193 Instruction *visitICmpInst(ICmpInst &I);
194 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000195 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
196 Instruction *LHS,
197 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000198 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
199 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000200
Reid Spencere4d87aa2006-12-23 06:05:41 +0000201 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
202 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000203 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000204 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000205 Instruction *commonCastTransforms(CastInst &CI);
206 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000207 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000208 Instruction *visitTrunc(TruncInst &CI);
209 Instruction *visitZExt(ZExtInst &CI);
210 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000211 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000212 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000213 Instruction *visitFPToUI(FPToUIInst &FI);
214 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000215 Instruction *visitUIToFP(CastInst &CI);
216 Instruction *visitSIToFP(CastInst &CI);
217 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000218 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000219 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000220 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
221 Instruction *FI);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000222 Instruction *visitSelectInst(SelectInst &SI);
223 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000224 Instruction *visitCallInst(CallInst &CI);
225 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000226 Instruction *visitPHINode(PHINode &PN);
227 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000228 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000229 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000230 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000231 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000232 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000233 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000234 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000235 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000236 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000237 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000238
239 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000240 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000241
Chris Lattner9fe38862003-06-19 17:00:31 +0000242 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000243 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000244 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000245 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000246 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
247 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000248 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000249
Chris Lattner28977af2004-04-05 01:30:19 +0000250 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000251 // InsertNewInstBefore - insert an instruction New before instruction Old
252 // in the program. Add the new instruction to the worklist.
253 //
Chris Lattner955f3312004-09-28 21:48:02 +0000254 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000255 assert(New && New->getParent() == 0 &&
256 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000257 BasicBlock *BB = Old.getParent();
258 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000259 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000260 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000261 }
262
Chris Lattner0c967662004-09-24 15:21:34 +0000263 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
264 /// This also adds the cast to the worklist. Finally, this returns the
265 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000266 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
267 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000268 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000269
Chris Lattnere2ed0572006-04-06 19:19:17 +0000270 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000271 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000272
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000273 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000274 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000275 return C;
276 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000277
278 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
279 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
280 }
281
Chris Lattner0c967662004-09-24 15:21:34 +0000282
Chris Lattner8b170942002-08-09 23:47:40 +0000283 // ReplaceInstUsesWith - This method is to be used when an instruction is
284 // found to be dead, replacable with another preexisting expression. Here
285 // we add all uses of I to the worklist, replace all uses of I with the new
286 // value, then return I, so that the inst combiner will know that I was
287 // modified.
288 //
289 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000290 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000291 if (&I != V) {
292 I.replaceAllUsesWith(V);
293 return &I;
294 } else {
295 // If we are replacing the instruction with itself, this must be in a
296 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000297 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000298 return &I;
299 }
Chris Lattner8b170942002-08-09 23:47:40 +0000300 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000301
Chris Lattner6dce1a72006-02-07 06:56:34 +0000302 // UpdateValueUsesWith - This method is to be used when an value is
303 // found to be replacable with another preexisting expression or was
304 // updated. Here we add all uses of I to the worklist, replace all uses of
305 // I with the new value (unless the instruction was just updated), then
306 // return true, so that the inst combiner will know that I was modified.
307 //
308 bool UpdateValueUsesWith(Value *Old, Value *New) {
309 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
310 if (Old != New)
311 Old->replaceAllUsesWith(New);
312 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000313 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000314 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000315 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000316 return true;
317 }
318
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000319 // EraseInstFromFunction - When dealing with an instruction that has side
320 // effects or produces a void value, we can't rely on DCE to delete the
321 // instruction. Instead, visit methods should return the value returned by
322 // this function.
323 Instruction *EraseInstFromFunction(Instruction &I) {
324 assert(I.use_empty() && "Cannot erase instruction that is used!");
325 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000326 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000327 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000328 return 0; // Don't do anything with FI
329 }
Chris Lattner173234a2008-06-02 01:18:21 +0000330
331 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
332 APInt &KnownOne, unsigned Depth = 0) const {
333 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
334 }
335
336 bool MaskedValueIsZero(Value *V, const APInt &Mask,
337 unsigned Depth = 0) const {
338 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
339 }
340 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
341 return llvm::ComputeNumSignBits(Op, TD, Depth);
342 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000343
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000344 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000345 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
346 /// InsertBefore instruction. This is specialized a bit to avoid inserting
347 /// casts that are known to not do anything...
348 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000349 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
350 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000351 Instruction *InsertBefore);
352
Reid Spencere4d87aa2006-12-23 06:05:41 +0000353 /// SimplifyCommutative - This performs a few simplifications for
354 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000355 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000356
Reid Spencere4d87aa2006-12-23 06:05:41 +0000357 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
358 /// most-complex to least-complex order.
359 bool SimplifyCompare(CmpInst &I);
360
Reid Spencer2ec619a2007-03-23 21:24:59 +0000361 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
362 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000363 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
364 APInt& KnownZero, APInt& KnownOne,
365 unsigned Depth = 0);
366
Chris Lattner867b99f2006-10-05 06:55:50 +0000367 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
368 uint64_t &UndefElts, unsigned Depth = 0);
369
Chris Lattner4e998b22004-09-29 05:07:12 +0000370 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
371 // PHI node as operand #0, see if we can fold the instruction into the PHI
372 // (which is only possible if all operands to the PHI are constants).
373 Instruction *FoldOpIntoPhi(Instruction &I);
374
Chris Lattnerbac32862004-11-14 19:13:23 +0000375 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
376 // operator and they all are only used by the PHI, PHI together their
377 // inputs, and do the operation once, to the result of the PHI.
378 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000379 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
380
381
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000382 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
383 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000384
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000385 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000386 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000387 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000388 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000389 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000390 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000391 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000392 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000393 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000394
Chris Lattnerafe91a52006-06-15 19:07:26 +0000395
Reid Spencerc55b2432006-12-13 18:21:21 +0000396 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000397
Dan Gohmaneee962e2008-04-10 18:43:06 +0000398 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
399 unsigned CastOpc,
400 int &NumCastsRemoved);
401 unsigned GetOrEnforceKnownAlignment(Value *V,
402 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000403
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000404 };
405}
406
Dan Gohman844731a2008-05-13 00:00:25 +0000407char InstCombiner::ID = 0;
408static RegisterPass<InstCombiner>
409X("instcombine", "Combine redundant instructions");
410
Chris Lattner4f98c562003-03-10 21:43:22 +0000411// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000412// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000413static unsigned getComplexity(Value *V) {
414 if (isa<Instruction>(V)) {
415 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000416 return 3;
417 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000418 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000419 if (isa<Argument>(V)) return 3;
420 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000421}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000422
Chris Lattnerc8802d22003-03-11 00:12:48 +0000423// isOnlyUse - Return true if this instruction will be deleted if we stop using
424// it.
425static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000426 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000427}
428
Chris Lattner4cb170c2004-02-23 06:38:22 +0000429// getPromotedType - Return the specified type promoted as it would be to pass
430// though a va_arg area...
431static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000432 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
433 if (ITy->getBitWidth() < 32)
434 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000435 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000436 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000437}
438
Reid Spencer3da59db2006-11-27 01:05:10 +0000439/// getBitCastOperand - If the specified operand is a CastInst or a constant
440/// expression bitcast, return the operand value, otherwise return null.
441static Value *getBitCastOperand(Value *V) {
442 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000443 return I->getOperand(0);
444 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000445 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000446 return CE->getOperand(0);
447 return 0;
448}
449
Reid Spencer3da59db2006-11-27 01:05:10 +0000450/// This function is a wrapper around CastInst::isEliminableCastPair. It
451/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000452static Instruction::CastOps
453isEliminableCastPair(
454 const CastInst *CI, ///< The first cast instruction
455 unsigned opcode, ///< The opcode of the second cast instruction
456 const Type *DstTy, ///< The target type for the second cast instruction
457 TargetData *TD ///< The target data for pointer size
458) {
459
460 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
461 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000462
Reid Spencer3da59db2006-11-27 01:05:10 +0000463 // Get the opcodes of the two Cast instructions
464 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
465 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000466
Reid Spencer3da59db2006-11-27 01:05:10 +0000467 return Instruction::CastOps(
468 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
469 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000470}
471
472/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
473/// in any code being generated. It does not require codegen if V is simple
474/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000475static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
476 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000477 if (V->getType() == Ty || isa<Constant>(V)) return false;
478
Chris Lattner01575b72006-05-25 23:24:33 +0000479 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000480 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000481 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000482 return false;
483 return true;
484}
485
486/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
487/// InsertBefore instruction. This is specialized a bit to avoid inserting
488/// casts that are known to not do anything...
489///
Reid Spencer17212df2006-12-12 09:18:51 +0000490Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
491 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000492 Instruction *InsertBefore) {
493 if (V->getType() == DestTy) return V;
494 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000495 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000496
Reid Spencer17212df2006-12-12 09:18:51 +0000497 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000498}
499
Chris Lattner4f98c562003-03-10 21:43:22 +0000500// SimplifyCommutative - This performs a few simplifications for commutative
501// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000502//
Chris Lattner4f98c562003-03-10 21:43:22 +0000503// 1. Order operands such that they are listed from right (least complex) to
504// left (most complex). This puts constants before unary operators before
505// binary operators.
506//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000507// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
508// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000509//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000510bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000511 bool Changed = false;
512 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
513 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000514
Chris Lattner4f98c562003-03-10 21:43:22 +0000515 if (!I.isAssociative()) return Changed;
516 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000517 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
518 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
519 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000520 Constant *Folded = ConstantExpr::get(I.getOpcode(),
521 cast<Constant>(I.getOperand(1)),
522 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000523 I.setOperand(0, Op->getOperand(0));
524 I.setOperand(1, Folded);
525 return true;
526 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
527 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
528 isOnlyUse(Op) && isOnlyUse(Op1)) {
529 Constant *C1 = cast<Constant>(Op->getOperand(1));
530 Constant *C2 = cast<Constant>(Op1->getOperand(1));
531
532 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000533 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000534 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000535 Op1->getOperand(0),
536 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000537 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000538 I.setOperand(0, New);
539 I.setOperand(1, Folded);
540 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000541 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000542 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000543 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000544}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000545
Reid Spencere4d87aa2006-12-23 06:05:41 +0000546/// SimplifyCompare - For a CmpInst this function just orders the operands
547/// so that theyare listed from right (least complex) to left (most complex).
548/// This puts constants before unary operators before binary operators.
549bool InstCombiner::SimplifyCompare(CmpInst &I) {
550 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
551 return false;
552 I.swapOperands();
553 // Compare instructions are not associative so there's nothing else we can do.
554 return true;
555}
556
Chris Lattner8d969642003-03-10 23:06:50 +0000557// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
558// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000559//
Chris Lattner8d969642003-03-10 23:06:50 +0000560static inline Value *dyn_castNegVal(Value *V) {
561 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000562 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000563
Chris Lattner0ce85802004-12-14 20:08:06 +0000564 // Constants can be considered to be negated values if they can be folded.
565 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
566 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000567
568 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
569 if (C->getType()->getElementType()->isInteger())
570 return ConstantExpr::getNeg(C);
571
Chris Lattner8d969642003-03-10 23:06:50 +0000572 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000573}
574
Chris Lattner8d969642003-03-10 23:06:50 +0000575static inline Value *dyn_castNotVal(Value *V) {
576 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000577 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000578
579 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000580 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000581 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000582 return 0;
583}
584
Chris Lattnerc8802d22003-03-11 00:12:48 +0000585// dyn_castFoldableMul - If this value is a multiply that can be folded into
586// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000587// non-constant operand of the multiply, and set CST to point to the multiplier.
588// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000589//
Chris Lattner50af16a2004-11-13 19:50:12 +0000590static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000591 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000592 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000593 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000594 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000595 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000596 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000597 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000598 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000599 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000600 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000601 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000602 return I->getOperand(0);
603 }
604 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000605 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000606}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000607
Chris Lattner574da9b2005-01-13 20:14:25 +0000608/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
609/// expression, return it.
610static User *dyn_castGetElementPtr(Value *V) {
611 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
612 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
613 if (CE->getOpcode() == Instruction::GetElementPtr)
614 return cast<User>(V);
615 return false;
616}
617
Dan Gohmaneee962e2008-04-10 18:43:06 +0000618/// getOpcode - If this is an Instruction or a ConstantExpr, return the
619/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000620static unsigned getOpcode(const Value *V) {
621 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000622 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000623 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000624 return CE->getOpcode();
625 // Use UserOp1 to mean there's no opcode.
626 return Instruction::UserOp1;
627}
628
Reid Spencer7177c3a2007-03-25 05:33:51 +0000629/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000630static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000631 APInt Val(C->getValue());
632 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000633}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000634/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000635static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000636 APInt Val(C->getValue());
637 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000638}
639/// Add - Add two ConstantInts together
640static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
641 return ConstantInt::get(C1->getValue() + C2->getValue());
642}
643/// And - Bitwise AND two ConstantInts together
644static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
645 return ConstantInt::get(C1->getValue() & C2->getValue());
646}
647/// Subtract - Subtract one ConstantInt from another
648static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
649 return ConstantInt::get(C1->getValue() - C2->getValue());
650}
651/// Multiply - Multiply two ConstantInts together
652static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
653 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000654}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000655/// MultiplyOverflows - True if the multiply can not be expressed in an int
656/// this size.
657static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
658 uint32_t W = C1->getBitWidth();
659 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
660 if (sign) {
661 LHSExt.sext(W * 2);
662 RHSExt.sext(W * 2);
663 } else {
664 LHSExt.zext(W * 2);
665 RHSExt.zext(W * 2);
666 }
667
668 APInt MulExt = LHSExt * RHSExt;
669
670 if (sign) {
671 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
672 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
673 return MulExt.slt(Min) || MulExt.sgt(Max);
674 } else
675 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
676}
Chris Lattner955f3312004-09-28 21:48:02 +0000677
Reid Spencere7816b52007-03-08 01:52:58 +0000678
Chris Lattner255d8912006-02-11 09:31:47 +0000679/// ShrinkDemandedConstant - Check to see if the specified operand of the
680/// specified instruction is a constant integer. If so, check to see if there
681/// are any bits set in the constant that are not demanded. If so, shrink the
682/// constant and return true.
683static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000684 APInt Demanded) {
685 assert(I && "No instruction?");
686 assert(OpNo < I->getNumOperands() && "Operand index too large");
687
688 // If the operand is not a constant integer, nothing to do.
689 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
690 if (!OpC) return false;
691
692 // If there are no bits set that aren't demanded, nothing to do.
693 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
694 if ((~Demanded & OpC->getValue()) == 0)
695 return false;
696
697 // This instruction is producing bits that are not demanded. Shrink the RHS.
698 Demanded &= OpC->getValue();
699 I->setOperand(OpNo, ConstantInt::get(Demanded));
700 return true;
701}
702
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000703// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
704// set of known zero and one bits, compute the maximum and minimum values that
705// could have the specified known zero and known one bits, returning them in
706// min/max.
707static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000708 const APInt& KnownZero,
709 const APInt& KnownOne,
710 APInt& Min, APInt& Max) {
711 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
712 assert(KnownZero.getBitWidth() == BitWidth &&
713 KnownOne.getBitWidth() == BitWidth &&
714 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
715 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000716 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000717
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000718 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
719 // bit if it is unknown.
720 Min = KnownOne;
721 Max = KnownOne|UnknownBits;
722
Zhou Sheng4acf1552007-03-28 05:15:57 +0000723 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000724 Min.set(BitWidth-1);
725 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000726 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000727}
728
729// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
730// a set of known zero and one bits, compute the maximum and minimum values that
731// could have the specified known zero and known one bits, returning them in
732// min/max.
733static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000734 const APInt &KnownZero,
735 const APInt &KnownOne,
736 APInt &Min, APInt &Max) {
737 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000738 assert(KnownZero.getBitWidth() == BitWidth &&
739 KnownOne.getBitWidth() == BitWidth &&
740 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
741 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000742 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000743
744 // The minimum value is when the unknown bits are all zeros.
745 Min = KnownOne;
746 // The maximum value is when the unknown bits are all ones.
747 Max = KnownOne|UnknownBits;
748}
Chris Lattner255d8912006-02-11 09:31:47 +0000749
Reid Spencer8cb68342007-03-12 17:25:59 +0000750/// SimplifyDemandedBits - This function attempts to replace V with a simpler
751/// value based on the demanded bits. When this function is called, it is known
752/// that only the bits set in DemandedMask of the result of V are ever used
753/// downstream. Consequently, depending on the mask and V, it may be possible
754/// to replace V with a constant or one of its operands. In such cases, this
755/// function does the replacement and returns true. In all other cases, it
756/// returns false after analyzing the expression and setting KnownOne and known
757/// to be one in the expression. KnownZero contains all the bits that are known
758/// to be zero in the expression. These are provided to potentially allow the
759/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
760/// the expression. KnownOne and KnownZero always follow the invariant that
761/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
762/// the bits in KnownOne and KnownZero may only be accurate for those bits set
763/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
764/// and KnownOne must all be the same.
765bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
766 APInt& KnownZero, APInt& KnownOne,
767 unsigned Depth) {
768 assert(V != 0 && "Null pointer of Value???");
769 assert(Depth <= 6 && "Limit Search Depth");
770 uint32_t BitWidth = DemandedMask.getBitWidth();
771 const IntegerType *VTy = cast<IntegerType>(V->getType());
772 assert(VTy->getBitWidth() == BitWidth &&
773 KnownZero.getBitWidth() == BitWidth &&
774 KnownOne.getBitWidth() == BitWidth &&
775 "Value *V, DemandedMask, KnownZero and KnownOne \
776 must have same BitWidth");
777 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
778 // We know all of the bits for a constant!
779 KnownOne = CI->getValue() & DemandedMask;
780 KnownZero = ~KnownOne & DemandedMask;
781 return false;
782 }
783
Zhou Sheng96704452007-03-14 03:21:24 +0000784 KnownZero.clear();
785 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000786 if (!V->hasOneUse()) { // Other users may use these bits.
787 if (Depth != 0) { // Not at the root.
788 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
789 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
790 return false;
791 }
792 // If this is the root being simplified, allow it to have multiple uses,
793 // just set the DemandedMask to all bits.
794 DemandedMask = APInt::getAllOnesValue(BitWidth);
795 } else if (DemandedMask == 0) { // Not demanding any bits from V.
796 if (V != UndefValue::get(VTy))
797 return UpdateValueUsesWith(V, UndefValue::get(VTy));
798 return false;
799 } else if (Depth == 6) { // Limit search depth.
800 return false;
801 }
802
803 Instruction *I = dyn_cast<Instruction>(V);
804 if (!I) return false; // Only analyze instructions.
805
Reid Spencer8cb68342007-03-12 17:25:59 +0000806 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
807 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
808 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000809 default:
810 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
811 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000812 case Instruction::And:
813 // If either the LHS or the RHS are Zero, the result is zero.
814 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
815 RHSKnownZero, RHSKnownOne, Depth+1))
816 return true;
817 assert((RHSKnownZero & RHSKnownOne) == 0 &&
818 "Bits known to be one AND zero?");
819
820 // If something is known zero on the RHS, the bits aren't demanded on the
821 // LHS.
822 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
823 LHSKnownZero, LHSKnownOne, Depth+1))
824 return true;
825 assert((LHSKnownZero & LHSKnownOne) == 0 &&
826 "Bits known to be one AND zero?");
827
828 // If all of the demanded bits are known 1 on one side, return the other.
829 // These bits cannot contribute to the result of the 'and'.
830 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
831 (DemandedMask & ~LHSKnownZero))
832 return UpdateValueUsesWith(I, I->getOperand(0));
833 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
834 (DemandedMask & ~RHSKnownZero))
835 return UpdateValueUsesWith(I, I->getOperand(1));
836
837 // If all of the demanded bits in the inputs are known zeros, return zero.
838 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
839 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
840
841 // If the RHS is a constant, see if we can simplify it.
842 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
843 return UpdateValueUsesWith(I, I);
844
845 // Output known-1 bits are only known if set in both the LHS & RHS.
846 RHSKnownOne &= LHSKnownOne;
847 // Output known-0 are known to be clear if zero in either the LHS | RHS.
848 RHSKnownZero |= LHSKnownZero;
849 break;
850 case Instruction::Or:
851 // If either the LHS or the RHS are One, the result is One.
852 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
853 RHSKnownZero, RHSKnownOne, Depth+1))
854 return true;
855 assert((RHSKnownZero & RHSKnownOne) == 0 &&
856 "Bits known to be one AND zero?");
857 // If something is known one on the RHS, the bits aren't demanded on the
858 // LHS.
859 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
860 LHSKnownZero, LHSKnownOne, Depth+1))
861 return true;
862 assert((LHSKnownZero & LHSKnownOne) == 0 &&
863 "Bits known to be one AND zero?");
864
865 // If all of the demanded bits are known zero on one side, return the other.
866 // These bits cannot contribute to the result of the 'or'.
867 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
868 (DemandedMask & ~LHSKnownOne))
869 return UpdateValueUsesWith(I, I->getOperand(0));
870 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
871 (DemandedMask & ~RHSKnownOne))
872 return UpdateValueUsesWith(I, I->getOperand(1));
873
874 // If all of the potentially set bits on one side are known to be set on
875 // the other side, just use the 'other' side.
876 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
877 (DemandedMask & (~RHSKnownZero)))
878 return UpdateValueUsesWith(I, I->getOperand(0));
879 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
880 (DemandedMask & (~LHSKnownZero)))
881 return UpdateValueUsesWith(I, I->getOperand(1));
882
883 // If the RHS is a constant, see if we can simplify it.
884 if (ShrinkDemandedConstant(I, 1, DemandedMask))
885 return UpdateValueUsesWith(I, I);
886
887 // Output known-0 bits are only known if clear in both the LHS & RHS.
888 RHSKnownZero &= LHSKnownZero;
889 // Output known-1 are known to be set if set in either the LHS | RHS.
890 RHSKnownOne |= LHSKnownOne;
891 break;
892 case Instruction::Xor: {
893 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
894 RHSKnownZero, RHSKnownOne, Depth+1))
895 return true;
896 assert((RHSKnownZero & RHSKnownOne) == 0 &&
897 "Bits known to be one AND zero?");
898 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
899 LHSKnownZero, LHSKnownOne, Depth+1))
900 return true;
901 assert((LHSKnownZero & LHSKnownOne) == 0 &&
902 "Bits known to be one AND zero?");
903
904 // If all of the demanded bits are known zero on one side, return the other.
905 // These bits cannot contribute to the result of the 'xor'.
906 if ((DemandedMask & RHSKnownZero) == DemandedMask)
907 return UpdateValueUsesWith(I, I->getOperand(0));
908 if ((DemandedMask & LHSKnownZero) == DemandedMask)
909 return UpdateValueUsesWith(I, I->getOperand(1));
910
911 // Output known-0 bits are known if clear or set in both the LHS & RHS.
912 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
913 (RHSKnownOne & LHSKnownOne);
914 // Output known-1 are known to be set if set in only one of the LHS, RHS.
915 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
916 (RHSKnownOne & LHSKnownZero);
917
918 // If all of the demanded bits are known to be zero on one side or the
919 // other, turn this into an *inclusive* or.
920 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
921 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
922 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000923 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +0000924 I->getName());
925 InsertNewInstBefore(Or, *I);
926 return UpdateValueUsesWith(I, Or);
927 }
928
929 // If all of the demanded bits on one side are known, and all of the set
930 // bits on that side are also known to be set on the other side, turn this
931 // into an AND, as we know the bits will be cleared.
932 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
933 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
934 // all known
935 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
936 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
937 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000938 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +0000939 InsertNewInstBefore(And, *I);
940 return UpdateValueUsesWith(I, And);
941 }
942 }
943
944 // If the RHS is a constant, see if we can simplify it.
945 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
946 if (ShrinkDemandedConstant(I, 1, DemandedMask))
947 return UpdateValueUsesWith(I, I);
948
949 RHSKnownZero = KnownZeroOut;
950 RHSKnownOne = KnownOneOut;
951 break;
952 }
953 case Instruction::Select:
954 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
955 RHSKnownZero, RHSKnownOne, Depth+1))
956 return true;
957 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
958 LHSKnownZero, LHSKnownOne, Depth+1))
959 return true;
960 assert((RHSKnownZero & RHSKnownOne) == 0 &&
961 "Bits known to be one AND zero?");
962 assert((LHSKnownZero & LHSKnownOne) == 0 &&
963 "Bits known to be one AND zero?");
964
965 // If the operands are constants, see if we can simplify them.
966 if (ShrinkDemandedConstant(I, 1, DemandedMask))
967 return UpdateValueUsesWith(I, I);
968 if (ShrinkDemandedConstant(I, 2, DemandedMask))
969 return UpdateValueUsesWith(I, I);
970
971 // Only known if known in both the LHS and RHS.
972 RHSKnownOne &= LHSKnownOne;
973 RHSKnownZero &= LHSKnownZero;
974 break;
975 case Instruction::Trunc: {
976 uint32_t truncBf =
977 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +0000978 DemandedMask.zext(truncBf);
979 RHSKnownZero.zext(truncBf);
980 RHSKnownOne.zext(truncBf);
981 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
982 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +0000983 return true;
984 DemandedMask.trunc(BitWidth);
985 RHSKnownZero.trunc(BitWidth);
986 RHSKnownOne.trunc(BitWidth);
987 assert((RHSKnownZero & RHSKnownOne) == 0 &&
988 "Bits known to be one AND zero?");
989 break;
990 }
991 case Instruction::BitCast:
992 if (!I->getOperand(0)->getType()->isInteger())
993 return false;
994
995 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
996 RHSKnownZero, RHSKnownOne, Depth+1))
997 return true;
998 assert((RHSKnownZero & RHSKnownOne) == 0 &&
999 "Bits known to be one AND zero?");
1000 break;
1001 case Instruction::ZExt: {
1002 // Compute the bits in the result that are not present in the input.
1003 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001004 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001005
Zhou Shengd48653a2007-03-29 04:45:55 +00001006 DemandedMask.trunc(SrcBitWidth);
1007 RHSKnownZero.trunc(SrcBitWidth);
1008 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001009 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1010 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001011 return true;
1012 DemandedMask.zext(BitWidth);
1013 RHSKnownZero.zext(BitWidth);
1014 RHSKnownOne.zext(BitWidth);
1015 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1016 "Bits known to be one AND zero?");
1017 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001018 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001019 break;
1020 }
1021 case Instruction::SExt: {
1022 // Compute the bits in the result that are not present in the input.
1023 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001024 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001025
Reid Spencer8cb68342007-03-12 17:25:59 +00001026 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001027 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001028
Zhou Sheng01542f32007-03-29 02:26:30 +00001029 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001030 // If any of the sign extended bits are demanded, we know that the sign
1031 // bit is demanded.
1032 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001033 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001034
Zhou Shengd48653a2007-03-29 04:45:55 +00001035 InputDemandedBits.trunc(SrcBitWidth);
1036 RHSKnownZero.trunc(SrcBitWidth);
1037 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001038 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1039 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001040 return true;
1041 InputDemandedBits.zext(BitWidth);
1042 RHSKnownZero.zext(BitWidth);
1043 RHSKnownOne.zext(BitWidth);
1044 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1045 "Bits known to be one AND zero?");
1046
1047 // If the sign bit of the input is known set or clear, then we know the
1048 // top bits of the result.
1049
1050 // If the input sign bit is known zero, or if the NewBits are not demanded
1051 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001052 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001053 {
1054 // Convert to ZExt cast
1055 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1056 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001057 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001058 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001059 }
1060 break;
1061 }
1062 case Instruction::Add: {
1063 // Figure out what the input bits are. If the top bits of the and result
1064 // are not demanded, then the add doesn't demand them from its input
1065 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001066 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001067
1068 // If there is a constant on the RHS, there are a variety of xformations
1069 // we can do.
1070 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1071 // If null, this should be simplified elsewhere. Some of the xforms here
1072 // won't work if the RHS is zero.
1073 if (RHS->isZero())
1074 break;
1075
1076 // If the top bit of the output is demanded, demand everything from the
1077 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001078 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001079
1080 // Find information about known zero/one bits in the input.
1081 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1082 LHSKnownZero, LHSKnownOne, Depth+1))
1083 return true;
1084
1085 // If the RHS of the add has bits set that can't affect the input, reduce
1086 // the constant.
1087 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1088 return UpdateValueUsesWith(I, I);
1089
1090 // Avoid excess work.
1091 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1092 break;
1093
1094 // Turn it into OR if input bits are zero.
1095 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1096 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001097 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001098 I->getName());
1099 InsertNewInstBefore(Or, *I);
1100 return UpdateValueUsesWith(I, Or);
1101 }
1102
1103 // We can say something about the output known-zero and known-one bits,
1104 // depending on potential carries from the input constant and the
1105 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1106 // bits set and the RHS constant is 0x01001, then we know we have a known
1107 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1108
1109 // To compute this, we first compute the potential carry bits. These are
1110 // the bits which may be modified. I'm not aware of a better way to do
1111 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001112 const APInt& RHSVal = RHS->getValue();
1113 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001114
1115 // Now that we know which bits have carries, compute the known-1/0 sets.
1116
1117 // Bits are known one if they are known zero in one operand and one in the
1118 // other, and there is no input carry.
1119 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1120 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1121
1122 // Bits are known zero if they are known zero in both operands and there
1123 // is no input carry.
1124 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1125 } else {
1126 // If the high-bits of this ADD are not demanded, then it does not demand
1127 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001128 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001129 // Right fill the mask of bits for this ADD to demand the most
1130 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001131 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001132 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1133 LHSKnownZero, LHSKnownOne, Depth+1))
1134 return true;
1135 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1136 LHSKnownZero, LHSKnownOne, Depth+1))
1137 return true;
1138 }
1139 }
1140 break;
1141 }
1142 case Instruction::Sub:
1143 // If the high-bits of this SUB are not demanded, then it does not demand
1144 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001146 // Right fill the mask of bits for this SUB to demand the most
1147 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001148 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001149 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001150 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1151 LHSKnownZero, LHSKnownOne, Depth+1))
1152 return true;
1153 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1154 LHSKnownZero, LHSKnownOne, Depth+1))
1155 return true;
1156 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001157 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1158 // the known zeros and ones.
1159 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001160 break;
1161 case Instruction::Shl:
1162 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001163 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001164 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1165 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001166 RHSKnownZero, RHSKnownOne, Depth+1))
1167 return true;
1168 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1169 "Bits known to be one AND zero?");
1170 RHSKnownZero <<= ShiftAmt;
1171 RHSKnownOne <<= ShiftAmt;
1172 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001173 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001174 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001175 }
1176 break;
1177 case Instruction::LShr:
1178 // For a logical shift right
1179 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001180 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001181
Reid Spencer8cb68342007-03-12 17:25:59 +00001182 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001183 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1184 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001185 RHSKnownZero, RHSKnownOne, Depth+1))
1186 return true;
1187 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1188 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001189 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1190 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001191 if (ShiftAmt) {
1192 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001193 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001194 RHSKnownZero |= HighBits; // high bits known zero.
1195 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001196 }
1197 break;
1198 case Instruction::AShr:
1199 // If this is an arithmetic shift right and only the low-bit is set, we can
1200 // always convert this into a logical shr, even if the shift amount is
1201 // variable. The low bit of the shift cannot be an input sign bit unless
1202 // the shift amount is >= the size of the datatype, which is undefined.
1203 if (DemandedMask == 1) {
1204 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001205 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001206 I->getOperand(0), I->getOperand(1), I->getName());
1207 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1208 return UpdateValueUsesWith(I, NewVal);
1209 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001210
1211 // If the sign bit is the only bit demanded by this ashr, then there is no
1212 // need to do it, the shift doesn't change the high bit.
1213 if (DemandedMask.isSignBit())
1214 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001215
1216 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001217 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001218
Reid Spencer8cb68342007-03-12 17:25:59 +00001219 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001220 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001221 // If any of the "high bits" are demanded, we should set the sign bit as
1222 // demanded.
1223 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1224 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001225 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001226 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001227 RHSKnownZero, RHSKnownOne, Depth+1))
1228 return true;
1229 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1230 "Bits known to be one AND zero?");
1231 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001232 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001233 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1234 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1235
1236 // Handle the sign bits.
1237 APInt SignBit(APInt::getSignBit(BitWidth));
1238 // Adjust to where it is now in the mask.
1239 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1240
1241 // If the input sign bit is known to be zero, or if none of the top bits
1242 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001243 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001244 (HighBits & ~DemandedMask) == HighBits) {
1245 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001246 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001247 I->getOperand(0), SA, I->getName());
1248 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1249 return UpdateValueUsesWith(I, NewVal);
1250 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1251 RHSKnownOne |= HighBits;
1252 }
1253 }
1254 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001255 case Instruction::SRem:
1256 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1257 APInt RA = Rem->getValue();
1258 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001259 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
1260 return UpdateValueUsesWith(I, I->getOperand(0));
1261
Dan Gohman23e1df82008-05-06 00:51:48 +00001262 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001263 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1264 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1265 LHSKnownZero, LHSKnownOne, Depth+1))
1266 return true;
1267
1268 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1269 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001270
1271 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001272
1273 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1274 }
1275 }
1276 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001277 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001278 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1279 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001280 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1281 KnownZero2, KnownOne2, Depth+1))
1282 return true;
1283
Dan Gohman23e8b712008-04-28 17:02:21 +00001284 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001285 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001286 KnownZero2, KnownOne2, Depth+1))
1287 return true;
1288
1289 Leaders = std::max(Leaders,
1290 KnownZero2.countLeadingOnes());
1291 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001292 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001293 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001294 case Instruction::Call:
1295 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1296 switch (II->getIntrinsicID()) {
1297 default: break;
1298 case Intrinsic::bswap: {
1299 // If the only bits demanded come from one byte of the bswap result,
1300 // just shift the input byte into position to eliminate the bswap.
1301 unsigned NLZ = DemandedMask.countLeadingZeros();
1302 unsigned NTZ = DemandedMask.countTrailingZeros();
1303
1304 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1305 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1306 // have 14 leading zeros, round to 8.
1307 NLZ &= ~7;
1308 NTZ &= ~7;
1309 // If we need exactly one byte, we can do this transformation.
1310 if (BitWidth-NLZ-NTZ == 8) {
1311 unsigned ResultBit = NTZ;
1312 unsigned InputBit = BitWidth-NTZ-8;
1313
1314 // Replace this with either a left or right shift to get the byte into
1315 // the right place.
1316 Instruction *NewVal;
1317 if (InputBit > ResultBit)
1318 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1319 ConstantInt::get(I->getType(), InputBit-ResultBit));
1320 else
1321 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1322 ConstantInt::get(I->getType(), ResultBit-InputBit));
1323 NewVal->takeName(I);
1324 InsertNewInstBefore(NewVal, *I);
1325 return UpdateValueUsesWith(I, NewVal);
1326 }
1327
1328 // TODO: Could compute known zero/one bits based on the input.
1329 break;
1330 }
1331 }
1332 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001333 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001334 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001335 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001336
1337 // If the client is only demanding bits that we know, return the known
1338 // constant.
1339 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1340 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1341 return false;
1342}
1343
Chris Lattner867b99f2006-10-05 06:55:50 +00001344
1345/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1346/// 64 or fewer elements. DemandedElts contains the set of elements that are
1347/// actually used by the caller. This method analyzes which elements of the
1348/// operand are undef and returns that information in UndefElts.
1349///
1350/// If the information about demanded elements can be used to simplify the
1351/// operation, the operation is simplified, then the resultant value is
1352/// returned. This returns null if no change was made.
1353Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1354 uint64_t &UndefElts,
1355 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001356 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001357 assert(VWidth <= 64 && "Vector too wide to analyze!");
1358 uint64_t EltMask = ~0ULL >> (64-VWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001359 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001360
1361 if (isa<UndefValue>(V)) {
1362 // If the entire vector is undefined, just return this info.
1363 UndefElts = EltMask;
1364 return 0;
1365 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1366 UndefElts = EltMask;
1367 return UndefValue::get(V->getType());
1368 }
1369
1370 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001371 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1372 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001373 Constant *Undef = UndefValue::get(EltTy);
1374
1375 std::vector<Constant*> Elts;
1376 for (unsigned i = 0; i != VWidth; ++i)
1377 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1378 Elts.push_back(Undef);
1379 UndefElts |= (1ULL << i);
1380 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1381 Elts.push_back(Undef);
1382 UndefElts |= (1ULL << i);
1383 } else { // Otherwise, defined.
1384 Elts.push_back(CP->getOperand(i));
1385 }
1386
1387 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001388 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001389 return NewCP != CP ? NewCP : 0;
1390 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001391 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001392 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001393 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001394 Constant *Zero = Constant::getNullValue(EltTy);
1395 Constant *Undef = UndefValue::get(EltTy);
1396 std::vector<Constant*> Elts;
1397 for (unsigned i = 0; i != VWidth; ++i)
1398 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1399 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001400 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001401 }
1402
Dan Gohman488fbfc2008-09-09 18:11:14 +00001403 // Limit search depth.
1404 if (Depth == 10)
1405 return false;
1406
1407 // If multiple users are using the root value, procede with
1408 // simplification conservatively assuming that all elements
1409 // are needed.
1410 if (!V->hasOneUse()) {
1411 // Quit if we find multiple users of a non-root value though.
1412 // They'll be handled when it's their turn to be visited by
1413 // the main instcombine process.
1414 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001415 // TODO: Just compute the UndefElts information recursively.
1416 return false;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001417
1418 // Conservatively assume that all elements are needed.
1419 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001420 }
1421
1422 Instruction *I = dyn_cast<Instruction>(V);
1423 if (!I) return false; // Only analyze instructions.
1424
1425 bool MadeChange = false;
1426 uint64_t UndefElts2;
1427 Value *TmpV;
1428 switch (I->getOpcode()) {
1429 default: break;
1430
1431 case Instruction::InsertElement: {
1432 // If this is a variable index, we don't know which element it overwrites.
1433 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001434 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001435 if (Idx == 0) {
1436 // Note that we can't propagate undef elt info, because we don't know
1437 // which elt is getting updated.
1438 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1439 UndefElts2, Depth+1);
1440 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1441 break;
1442 }
1443
1444 // If this is inserting an element that isn't demanded, remove this
1445 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001446 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001447 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1448 return AddSoonDeadInstToWorklist(*I, 0);
1449
1450 // Otherwise, the element inserted overwrites whatever was there, so the
1451 // input demanded set is simpler than the output set.
1452 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1453 DemandedElts & ~(1ULL << IdxNo),
1454 UndefElts, Depth+1);
1455 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1456
1457 // The inserted element is defined.
Dan Gohman488fbfc2008-09-09 18:11:14 +00001458 UndefElts &= ~(1ULL << IdxNo);
1459 break;
1460 }
1461 case Instruction::ShuffleVector: {
1462 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1463 uint64_t LeftDemanded = 0, RightDemanded = 0;
1464 for (unsigned i = 0; i < VWidth; i++) {
1465 if (DemandedElts & (1ULL << i)) {
1466 unsigned MaskVal = Shuffle->getMaskValue(i);
1467 if (MaskVal != -1u) {
1468 assert(MaskVal < VWidth * 2 &&
1469 "shufflevector mask index out of range!");
1470 if (MaskVal < VWidth)
1471 LeftDemanded |= 1ULL << MaskVal;
1472 else
1473 RightDemanded |= 1ULL << (MaskVal - VWidth);
1474 }
1475 }
1476 }
1477
1478 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1479 UndefElts2, Depth+1);
1480 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1481
1482 uint64_t UndefElts3;
1483 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1484 UndefElts3, Depth+1);
1485 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1486
1487 bool NewUndefElts = false;
1488 for (unsigned i = 0; i < VWidth; i++) {
1489 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001490 if (MaskVal == -1u) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001491 uint64_t NewBit = 1ULL << i;
1492 UndefElts |= NewBit;
1493 } else if (MaskVal < VWidth) {
1494 uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1495 NewUndefElts |= NewBit;
1496 UndefElts |= NewBit;
1497 } else {
1498 uint64_t NewBit = ((UndefElts3 >> (MaskVal - VWidth)) & 1) << i;
1499 NewUndefElts |= NewBit;
1500 UndefElts |= NewBit;
1501 }
1502 }
1503
1504 if (NewUndefElts) {
1505 // Add additional discovered undefs.
1506 std::vector<Constant*> Elts;
1507 for (unsigned i = 0; i < VWidth; ++i) {
1508 if (UndefElts & (1ULL << i))
1509 Elts.push_back(UndefValue::get(Type::Int32Ty));
1510 else
1511 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1512 Shuffle->getMaskValue(i)));
1513 }
1514 I->setOperand(2, ConstantVector::get(Elts));
1515 MadeChange = true;
1516 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001517 break;
1518 }
Chris Lattner69878332007-04-14 22:29:23 +00001519 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001520 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001521 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1522 if (!VTy) break;
1523 unsigned InVWidth = VTy->getNumElements();
1524 uint64_t InputDemandedElts = 0;
1525 unsigned Ratio;
1526
1527 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001528 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001529 // elements as are demanded of us.
1530 Ratio = 1;
1531 InputDemandedElts = DemandedElts;
1532 } else if (VWidth > InVWidth) {
1533 // Untested so far.
1534 break;
1535
1536 // If there are more elements in the result than there are in the source,
1537 // then an input element is live if any of the corresponding output
1538 // elements are live.
1539 Ratio = VWidth/InVWidth;
1540 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1541 if (DemandedElts & (1ULL << OutIdx))
1542 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1543 }
1544 } else {
1545 // Untested so far.
1546 break;
1547
1548 // If there are more elements in the source than there are in the result,
1549 // then an input element is live if the corresponding output element is
1550 // live.
1551 Ratio = InVWidth/VWidth;
1552 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1553 if (DemandedElts & (1ULL << InIdx/Ratio))
1554 InputDemandedElts |= 1ULL << InIdx;
1555 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001556
Chris Lattner69878332007-04-14 22:29:23 +00001557 // div/rem demand all inputs, because they don't want divide by zero.
1558 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1559 UndefElts2, Depth+1);
1560 if (TmpV) {
1561 I->setOperand(0, TmpV);
1562 MadeChange = true;
1563 }
1564
1565 UndefElts = UndefElts2;
1566 if (VWidth > InVWidth) {
1567 assert(0 && "Unimp");
1568 // If there are more elements in the result than there are in the source,
1569 // then an output element is undef if the corresponding input element is
1570 // undef.
1571 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1572 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1573 UndefElts |= 1ULL << OutIdx;
1574 } else if (VWidth < InVWidth) {
1575 assert(0 && "Unimp");
1576 // If there are more elements in the source than there are in the result,
1577 // then a result element is undef if all of the corresponding input
1578 // elements are undef.
1579 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1580 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1581 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1582 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1583 }
1584 break;
1585 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001586 case Instruction::And:
1587 case Instruction::Or:
1588 case Instruction::Xor:
1589 case Instruction::Add:
1590 case Instruction::Sub:
1591 case Instruction::Mul:
1592 // div/rem demand all inputs, because they don't want divide by zero.
1593 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1594 UndefElts, Depth+1);
1595 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1596 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1597 UndefElts2, Depth+1);
1598 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1599
1600 // Output elements are undefined if both are undefined. Consider things
1601 // like undef&0. The result is known zero, not undef.
1602 UndefElts &= UndefElts2;
1603 break;
1604
1605 case Instruction::Call: {
1606 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1607 if (!II) break;
1608 switch (II->getIntrinsicID()) {
1609 default: break;
1610
1611 // Binary vector operations that work column-wise. A dest element is a
1612 // function of the corresponding input elements from the two inputs.
1613 case Intrinsic::x86_sse_sub_ss:
1614 case Intrinsic::x86_sse_mul_ss:
1615 case Intrinsic::x86_sse_min_ss:
1616 case Intrinsic::x86_sse_max_ss:
1617 case Intrinsic::x86_sse2_sub_sd:
1618 case Intrinsic::x86_sse2_mul_sd:
1619 case Intrinsic::x86_sse2_min_sd:
1620 case Intrinsic::x86_sse2_max_sd:
1621 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1622 UndefElts, Depth+1);
1623 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1624 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1625 UndefElts2, Depth+1);
1626 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1627
1628 // If only the low elt is demanded and this is a scalarizable intrinsic,
1629 // scalarize it now.
1630 if (DemandedElts == 1) {
1631 switch (II->getIntrinsicID()) {
1632 default: break;
1633 case Intrinsic::x86_sse_sub_ss:
1634 case Intrinsic::x86_sse_mul_ss:
1635 case Intrinsic::x86_sse2_sub_sd:
1636 case Intrinsic::x86_sse2_mul_sd:
1637 // TODO: Lower MIN/MAX/ABS/etc
1638 Value *LHS = II->getOperand(1);
1639 Value *RHS = II->getOperand(2);
1640 // Extract the element as scalars.
1641 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1642 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1643
1644 switch (II->getIntrinsicID()) {
1645 default: assert(0 && "Case stmts out of sync!");
1646 case Intrinsic::x86_sse_sub_ss:
1647 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001648 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001649 II->getName()), *II);
1650 break;
1651 case Intrinsic::x86_sse_mul_ss:
1652 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001653 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001654 II->getName()), *II);
1655 break;
1656 }
1657
1658 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001659 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1660 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001661 InsertNewInstBefore(New, *II);
1662 AddSoonDeadInstToWorklist(*II, 0);
1663 return New;
1664 }
1665 }
1666
1667 // Output elements are undefined if both are undefined. Consider things
1668 // like undef&0. The result is known zero, not undef.
1669 UndefElts &= UndefElts2;
1670 break;
1671 }
1672 break;
1673 }
1674 }
1675 return MadeChange ? I : 0;
1676}
1677
Dan Gohman45b4e482008-05-19 22:14:15 +00001678
Chris Lattner564a7272003-08-13 19:01:45 +00001679/// AssociativeOpt - Perform an optimization on an associative operator. This
1680/// function is designed to check a chain of associative operators for a
1681/// potential to apply a certain optimization. Since the optimization may be
1682/// applicable if the expression was reassociated, this checks the chain, then
1683/// reassociates the expression as necessary to expose the optimization
1684/// opportunity. This makes use of a special Functor, which must define
1685/// 'shouldApply' and 'apply' methods.
1686///
1687template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001688static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001689 unsigned Opcode = Root.getOpcode();
1690 Value *LHS = Root.getOperand(0);
1691
1692 // Quick check, see if the immediate LHS matches...
1693 if (F.shouldApply(LHS))
1694 return F.apply(Root);
1695
1696 // Otherwise, if the LHS is not of the same opcode as the root, return.
1697 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001698 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001699 // Should we apply this transform to the RHS?
1700 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1701
1702 // If not to the RHS, check to see if we should apply to the LHS...
1703 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1704 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1705 ShouldApply = true;
1706 }
1707
1708 // If the functor wants to apply the optimization to the RHS of LHSI,
1709 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1710 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001711 // Now all of the instructions are in the current basic block, go ahead
1712 // and perform the reassociation.
1713 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1714
1715 // First move the selected RHS to the LHS of the root...
1716 Root.setOperand(0, LHSI->getOperand(1));
1717
1718 // Make what used to be the LHS of the root be the user of the root...
1719 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001720 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001721 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1722 return 0;
1723 }
Chris Lattner65725312004-04-16 18:08:07 +00001724 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001725 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001726 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001727 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001728 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001729
1730 // Now propagate the ExtraOperand down the chain of instructions until we
1731 // get to LHSI.
1732 while (TmpLHSI != LHSI) {
1733 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001734 // Move the instruction to immediately before the chain we are
1735 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001736 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001737 ARI = NextLHSI;
1738
Chris Lattner564a7272003-08-13 19:01:45 +00001739 Value *NextOp = NextLHSI->getOperand(1);
1740 NextLHSI->setOperand(1, ExtraOperand);
1741 TmpLHSI = NextLHSI;
1742 ExtraOperand = NextOp;
1743 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001744
Chris Lattner564a7272003-08-13 19:01:45 +00001745 // Now that the instructions are reassociated, have the functor perform
1746 // the transformation...
1747 return F.apply(Root);
1748 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001749
Chris Lattner564a7272003-08-13 19:01:45 +00001750 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1751 }
1752 return 0;
1753}
1754
Dan Gohman844731a2008-05-13 00:00:25 +00001755namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001756
Nick Lewycky02d639f2008-05-23 04:34:58 +00001757// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001758struct AddRHS {
1759 Value *RHS;
1760 AddRHS(Value *rhs) : RHS(rhs) {}
1761 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1762 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001763 return BinaryOperator::CreateShl(Add.getOperand(0),
1764 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001765 }
1766};
1767
1768// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1769// iff C1&C2 == 0
1770struct AddMaskingAnd {
1771 Constant *C2;
1772 AddMaskingAnd(Constant *c) : C2(c) {}
1773 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001774 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001775 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001776 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001777 }
1778 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001779 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001780 }
1781};
1782
Dan Gohman844731a2008-05-13 00:00:25 +00001783}
1784
Chris Lattner6e7ba452005-01-01 16:22:27 +00001785static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001786 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001787 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001788 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001789 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001790
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001791 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00001792 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001793 }
1794
Chris Lattner2eefe512004-04-09 19:05:30 +00001795 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001796 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1797 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001798
Chris Lattner2eefe512004-04-09 19:05:30 +00001799 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1800 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001801 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1802 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001803 }
1804
1805 Value *Op0 = SO, *Op1 = ConstOperand;
1806 if (!ConstIsRHS)
1807 std::swap(Op0, Op1);
1808 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001809 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001810 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001811 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001812 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001813 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001814 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001815 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001816 abort();
1817 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001818 return IC->InsertNewInstBefore(New, I);
1819}
1820
1821// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1822// constant as the other operand, try to fold the binary operator into the
1823// select arguments. This also works for Cast instructions, which obviously do
1824// not have a second operand.
1825static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1826 InstCombiner *IC) {
1827 // Don't modify shared select instructions
1828 if (!SI->hasOneUse()) return 0;
1829 Value *TV = SI->getOperand(1);
1830 Value *FV = SI->getOperand(2);
1831
1832 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001833 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001834 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001835
Chris Lattner6e7ba452005-01-01 16:22:27 +00001836 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1837 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1838
Gabor Greif051a9502008-04-06 20:25:17 +00001839 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1840 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001841 }
1842 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001843}
1844
Chris Lattner4e998b22004-09-29 05:07:12 +00001845
1846/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1847/// node as operand #0, see if we can fold the instruction into the PHI (which
1848/// is only possible if all operands to the PHI are constants).
1849Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1850 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001851 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001852 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001853
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001854 // Check to see if all of the operands of the PHI are constants. If there is
1855 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001856 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001857 BasicBlock *NonConstBB = 0;
1858 for (unsigned i = 0; i != NumPHIValues; ++i)
1859 if (!isa<Constant>(PN->getIncomingValue(i))) {
1860 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001861 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001862 NonConstBB = PN->getIncomingBlock(i);
1863
1864 // If the incoming non-constant value is in I's block, we have an infinite
1865 // loop.
1866 if (NonConstBB == I.getParent())
1867 return 0;
1868 }
1869
1870 // If there is exactly one non-constant value, we can insert a copy of the
1871 // operation in that block. However, if this is a critical edge, we would be
1872 // inserting the computation one some other paths (e.g. inside a loop). Only
1873 // do this if the pred block is unconditionally branching into the phi block.
1874 if (NonConstBB) {
1875 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1876 if (!BI || !BI->isUnconditional()) return 0;
1877 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001878
1879 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001880 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001881 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001882 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001883 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001884
1885 // Next, add all of the operands to the PHI.
1886 if (I.getNumOperands() == 2) {
1887 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001888 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001889 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001890 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001891 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1892 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1893 else
1894 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001895 } else {
1896 assert(PN->getIncomingBlock(i) == NonConstBB);
1897 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001898 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001899 PN->getIncomingValue(i), C, "phitmp",
1900 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001901 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001902 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001903 CI->getPredicate(),
1904 PN->getIncomingValue(i), C, "phitmp",
1905 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001906 else
1907 assert(0 && "Unknown binop!");
1908
Chris Lattnerdbab3862007-03-02 21:28:56 +00001909 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001910 }
1911 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001912 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001913 } else {
1914 CastInst *CI = cast<CastInst>(&I);
1915 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001916 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001917 Value *InV;
1918 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001919 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001920 } else {
1921 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001922 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001923 I.getType(), "phitmp",
1924 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001925 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001926 }
1927 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001928 }
1929 }
1930 return ReplaceInstUsesWith(I, NewPN);
1931}
1932
Chris Lattner2454a2e2008-01-29 06:52:45 +00001933
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001934/// WillNotOverflowSignedAdd - Return true if we can prove that:
1935/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1936/// This basically requires proving that the add in the original type would not
1937/// overflow to change the sign bit or have a carry out.
1938bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1939 // There are different heuristics we can use for this. Here are some simple
1940 // ones.
1941
1942 // Add has the property that adding any two 2's complement numbers can only
1943 // have one carry bit which can change a sign. As such, if LHS and RHS each
1944 // have at least two sign bits, we know that the addition of the two values will
1945 // sign extend fine.
1946 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1947 return true;
1948
1949
1950 // If one of the operands only has one non-zero bit, and if the other operand
1951 // has a known-zero bit in a more significant place than it (not including the
1952 // sign bit) the ripple may go up to and fill the zero, but won't change the
1953 // sign. For example, (X & ~4) + 1.
1954
1955 // TODO: Implement.
1956
1957 return false;
1958}
1959
Chris Lattner2454a2e2008-01-29 06:52:45 +00001960
Chris Lattner7e708292002-06-25 16:13:24 +00001961Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001962 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001963 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001964
Chris Lattner66331a42004-04-10 22:01:55 +00001965 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001966 // X + undef -> undef
1967 if (isa<UndefValue>(RHS))
1968 return ReplaceInstUsesWith(I, RHS);
1969
Chris Lattner66331a42004-04-10 22:01:55 +00001970 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001971 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001972 if (RHSC->isNullValue())
1973 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001974 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001975 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1976 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00001977 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001978 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001979
Chris Lattner66331a42004-04-10 22:01:55 +00001980 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001981 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001982 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001983 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001984 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001985 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001986
1987 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1988 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00001989 if (!isa<VectorType>(I.getType())) {
1990 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1991 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1992 KnownZero, KnownOne))
1993 return &I;
1994 }
Chris Lattner66331a42004-04-10 22:01:55 +00001995 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001996
1997 if (isa<PHINode>(LHS))
1998 if (Instruction *NV = FoldOpIntoPhi(I))
1999 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002000
Chris Lattner4f637d42006-01-06 17:59:59 +00002001 ConstantInt *XorRHS = 0;
2002 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002003 if (isa<ConstantInt>(RHSC) &&
2004 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002005 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002006 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002007
Zhou Sheng4351c642007-04-02 08:20:41 +00002008 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002009 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2010 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002011 do {
2012 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002013 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2014 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002015 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2016 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002017 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002018 if (!MaskedValueIsZero(XorLHS,
2019 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002020 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002021 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002022 }
2023 }
2024 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002025 C0080Val = APIntOps::lshr(C0080Val, Size);
2026 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2027 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002028
Reid Spencer35c38852007-03-28 01:36:16 +00002029 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002030 // with funny bit widths then this switch statement should be removed. It
2031 // is just here to get the size of the "middle" type back up to something
2032 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002033 const Type *MiddleType = 0;
2034 switch (Size) {
2035 default: break;
2036 case 32: MiddleType = Type::Int32Ty; break;
2037 case 16: MiddleType = Type::Int16Ty; break;
2038 case 8: MiddleType = Type::Int8Ty; break;
2039 }
2040 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002041 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002042 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002043 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002044 }
2045 }
Chris Lattner66331a42004-04-10 22:01:55 +00002046 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002047
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002048 if (I.getType() == Type::Int1Ty)
2049 return BinaryOperator::CreateXor(LHS, RHS);
2050
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002051 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002052 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002053 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002054
2055 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2056 if (RHSI->getOpcode() == Instruction::Sub)
2057 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2058 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2059 }
2060 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2061 if (LHSI->getOpcode() == Instruction::Sub)
2062 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2063 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2064 }
Robert Bocchino71698282004-07-27 21:02:21 +00002065 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002066
Chris Lattner5c4afb92002-05-08 22:46:53 +00002067 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002068 // -A + -B --> -(A + B)
2069 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002070 if (LHS->getType()->isIntOrIntVector()) {
2071 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002072 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002073 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002074 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002075 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002076 }
2077
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002078 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002079 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002080
2081 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002082 if (!isa<Constant>(RHS))
2083 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002084 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002085
Misha Brukmanfd939082005-04-21 23:48:37 +00002086
Chris Lattner50af16a2004-11-13 19:50:12 +00002087 ConstantInt *C2;
2088 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2089 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002090 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002091
2092 // X*C1 + X*C2 --> X * (C1+C2)
2093 ConstantInt *C1;
2094 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002095 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002096 }
2097
2098 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002099 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002100 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002101
Chris Lattnere617c9e2007-01-05 02:17:46 +00002102 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002103 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2104 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002105
Chris Lattnerad3448c2003-02-18 19:57:07 +00002106
Chris Lattner564a7272003-08-13 19:01:45 +00002107 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002108 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002109 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2110 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002111
2112 // A+B --> A|B iff A and B have no bits set in common.
2113 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2114 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2115 APInt LHSKnownOne(IT->getBitWidth(), 0);
2116 APInt LHSKnownZero(IT->getBitWidth(), 0);
2117 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2118 if (LHSKnownZero != 0) {
2119 APInt RHSKnownOne(IT->getBitWidth(), 0);
2120 APInt RHSKnownZero(IT->getBitWidth(), 0);
2121 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2122
2123 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002124 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002125 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002126 }
2127 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002128
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002129 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002130 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002131 Value *W, *X, *Y, *Z;
2132 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2133 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2134 if (W != Y) {
2135 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002136 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002137 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002138 std::swap(W, X);
2139 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002140 std::swap(Y, Z);
2141 std::swap(W, X);
2142 }
2143 }
2144
2145 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002146 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002147 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002148 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002149 }
2150 }
2151 }
2152
Chris Lattner6b032052003-10-02 15:11:26 +00002153 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002154 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002155 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002156 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002157
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002158 // (X & FF00) + xx00 -> (X+xx00) & FF00
2159 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002160 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002161 if (Anded == CRHS) {
2162 // See if all bits from the first bit set in the Add RHS up are included
2163 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002164 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002165
2166 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002167 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002168
2169 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002170 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002171
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002172 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2173 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002174 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002175 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002176 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002177 }
2178 }
2179 }
2180
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002181 // Try to fold constant add into select arguments.
2182 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002183 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002184 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002185 }
2186
Reid Spencer1628cec2006-10-26 06:15:43 +00002187 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002188 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002189 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002190 CastInst *CI = dyn_cast<CastInst>(LHS);
2191 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002192 if (!CI) {
2193 CI = dyn_cast<CastInst>(RHS);
2194 Other = LHS;
2195 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002196 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002197 (CI->getType()->getPrimitiveSizeInBits() ==
2198 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002199 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002200 unsigned AS =
2201 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002202 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2203 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002204 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002205 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002206 }
2207 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002208
Chris Lattner42790482007-12-20 01:56:58 +00002209 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002210 {
2211 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2212 Value *Other = RHS;
2213 if (!SI) {
2214 SI = dyn_cast<SelectInst>(RHS);
2215 Other = LHS;
2216 }
Chris Lattner42790482007-12-20 01:56:58 +00002217 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002218 Value *TV = SI->getTrueValue();
2219 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002220 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002221
2222 // Can we fold the add into the argument of the select?
2223 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002224 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2225 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002226 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002227 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2228 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002229 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002230 }
2231 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002232
2233 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2234 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2235 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2236 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002237
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002238 // Check for (add (sext x), y), see if we can merge this into an
2239 // integer add followed by a sext.
2240 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2241 // (add (sext x), cst) --> (sext (add x, cst'))
2242 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2243 Constant *CI =
2244 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2245 if (LHSConv->hasOneUse() &&
2246 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2247 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2248 // Insert the new, smaller add.
2249 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2250 CI, "addconv");
2251 InsertNewInstBefore(NewAdd, I);
2252 return new SExtInst(NewAdd, I.getType());
2253 }
2254 }
2255
2256 // (add (sext x), (sext y)) --> (sext (add int x, y))
2257 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2258 // Only do this if x/y have the same type, if at last one of them has a
2259 // single use (so we don't increase the number of sexts), and if the
2260 // integer add will not overflow.
2261 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2262 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2263 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2264 RHSConv->getOperand(0))) {
2265 // Insert the new integer add.
2266 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2267 RHSConv->getOperand(0),
2268 "addconv");
2269 InsertNewInstBefore(NewAdd, I);
2270 return new SExtInst(NewAdd, I.getType());
2271 }
2272 }
2273 }
2274
2275 // Check for (add double (sitofp x), y), see if we can merge this into an
2276 // integer add followed by a promotion.
2277 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2278 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2279 // ... if the constant fits in the integer value. This is useful for things
2280 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2281 // requires a constant pool load, and generally allows the add to be better
2282 // instcombined.
2283 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2284 Constant *CI =
2285 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2286 if (LHSConv->hasOneUse() &&
2287 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2288 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2289 // Insert the new integer add.
2290 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2291 CI, "addconv");
2292 InsertNewInstBefore(NewAdd, I);
2293 return new SIToFPInst(NewAdd, I.getType());
2294 }
2295 }
2296
2297 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2298 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2299 // Only do this if x/y have the same type, if at last one of them has a
2300 // single use (so we don't increase the number of int->fp conversions),
2301 // and if the integer add will not overflow.
2302 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2303 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2304 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2305 RHSConv->getOperand(0))) {
2306 // Insert the new integer add.
2307 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2308 RHSConv->getOperand(0),
2309 "addconv");
2310 InsertNewInstBefore(NewAdd, I);
2311 return new SIToFPInst(NewAdd, I.getType());
2312 }
2313 }
2314 }
2315
Chris Lattner7e708292002-06-25 16:13:24 +00002316 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002317}
2318
Chris Lattner7e708292002-06-25 16:13:24 +00002319Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002320 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002321
Chris Lattnerd137ab42008-07-17 06:07:20 +00002322 if (Op0 == Op1 && // sub X, X -> 0
2323 !I.getType()->isFPOrFPVector())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002324 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002325
Chris Lattner233f7dc2002-08-12 21:17:25 +00002326 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002327 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002328 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002329
Chris Lattnere87597f2004-10-16 18:11:37 +00002330 if (isa<UndefValue>(Op0))
2331 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2332 if (isa<UndefValue>(Op1))
2333 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2334
Chris Lattnerd65460f2003-11-05 01:06:05 +00002335 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2336 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002337 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002338 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002339
Chris Lattnerd65460f2003-11-05 01:06:05 +00002340 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002341 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002342 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002343 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002344
Chris Lattner76b7a062007-01-15 07:02:54 +00002345 // -(X >>u 31) -> (X >>s 31)
2346 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002347 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002348 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002349 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002350 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002351 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002352 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002353 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002354 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002355 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002356 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002357 }
2358 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002359 }
2360 else if (SI->getOpcode() == Instruction::AShr) {
2361 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2362 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002363 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002364 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002365 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002366 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002367 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002368 }
2369 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002370 }
2371 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002372 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002373
2374 // Try to fold constant sub into select arguments.
2375 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002376 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002377 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002378
2379 if (isa<PHINode>(Op0))
2380 if (Instruction *NV = FoldOpIntoPhi(I))
2381 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002382 }
2383
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002384 if (I.getType() == Type::Int1Ty)
2385 return BinaryOperator::CreateXor(Op0, Op1);
2386
Chris Lattner43d84d62005-04-07 16:15:25 +00002387 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2388 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002389 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002390 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002391 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002392 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002393 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002394 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2395 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2396 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002397 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002398 Op1I->getOperand(0));
2399 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002400 }
2401
Chris Lattnerfd059242003-10-15 16:48:29 +00002402 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002403 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2404 // is not used by anyone else...
2405 //
Chris Lattner0517e722004-02-02 20:09:56 +00002406 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002407 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002408 // Swap the two operands of the subexpr...
2409 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2410 Op1I->setOperand(0, IIOp1);
2411 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002412
Chris Lattnera2881962003-02-18 19:28:33 +00002413 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002414 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002415 }
2416
2417 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2418 //
2419 if (Op1I->getOpcode() == Instruction::And &&
2420 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2421 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2422
Chris Lattnerf523d062004-06-09 05:08:07 +00002423 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002424 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2425 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002426 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002427
Reid Spencerac5209e2006-10-16 23:08:08 +00002428 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002429 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002430 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002431 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002432 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002433 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002434 ConstantExpr::getNeg(DivRHS));
2435
Chris Lattnerad3448c2003-02-18 19:57:07 +00002436 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002437 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002438 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002439 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002440 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002441 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002442
2443 // X - ((X / Y) * Y) --> X % Y
2444 if (Op1I->getOpcode() == Instruction::Mul)
2445 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2446 if (Op0 == I->getOperand(0) &&
2447 Op1I->getOperand(1) == I->getOperand(1)) {
2448 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002449 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002450 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002451 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002452 }
Chris Lattner40371712002-05-09 01:29:19 +00002453 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002454 }
Chris Lattnera2881962003-02-18 19:28:33 +00002455
Chris Lattner9919e3d2006-12-02 00:13:08 +00002456 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002457 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002458 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002459 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2460 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2461 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2462 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002463 } else if (Op0I->getOpcode() == Instruction::Sub) {
2464 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002465 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002466 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002467 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002468
Chris Lattner50af16a2004-11-13 19:50:12 +00002469 ConstantInt *C1;
2470 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002471 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002472 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002473
Chris Lattner50af16a2004-11-13 19:50:12 +00002474 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2475 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002476 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002477 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002478 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002479}
2480
Chris Lattnera0141b92007-07-15 20:42:37 +00002481/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2482/// comparison only checks the sign bit. If it only checks the sign bit, set
2483/// TrueIfSigned if the result of the comparison is true when the input value is
2484/// signed.
2485static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2486 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002487 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002488 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2489 TrueIfSigned = true;
2490 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002491 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2492 TrueIfSigned = true;
2493 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002494 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2495 TrueIfSigned = false;
2496 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002497 case ICmpInst::ICMP_UGT:
2498 // True if LHS u> RHS and RHS == high-bit-mask - 1
2499 TrueIfSigned = true;
2500 return RHS->getValue() ==
2501 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2502 case ICmpInst::ICMP_UGE:
2503 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2504 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002505 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002506 default:
2507 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002508 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002509}
2510
Chris Lattner7e708292002-06-25 16:13:24 +00002511Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002512 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002513 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002514
Chris Lattnere87597f2004-10-16 18:11:37 +00002515 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2516 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2517
Chris Lattner233f7dc2002-08-12 21:17:25 +00002518 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002519 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2520 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002521
2522 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002523 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002524 if (SI->getOpcode() == Instruction::Shl)
2525 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002526 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002527 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002528
Zhou Sheng843f07672007-04-19 05:39:12 +00002529 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002530 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2531 if (CI->equalsInt(1)) // X * 1 == X
2532 return ReplaceInstUsesWith(I, Op0);
2533 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002534 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002535
Zhou Sheng97b52c22007-03-29 01:57:21 +00002536 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002537 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002538 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002539 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002540 }
Robert Bocchino71698282004-07-27 21:02:21 +00002541 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002542 if (Op1F->isNullValue())
2543 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002544
Chris Lattnera2881962003-02-18 19:28:33 +00002545 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2546 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002547 if (Op1F->isExactlyValue(1.0))
2548 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2549 } else if (isa<VectorType>(Op1->getType())) {
2550 if (isa<ConstantAggregateZero>(Op1))
2551 return ReplaceInstUsesWith(I, Op1);
2552
2553 // As above, vector X*splat(1.0) -> X in all defined cases.
2554 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1))
2555 if (ConstantFP *F = dyn_cast_or_null<ConstantFP>(Op1V->getSplatValue()))
2556 if (F->isExactlyValue(1.0))
2557 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +00002558 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002559
2560 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2561 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002562 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002563 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002564 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002565 Op1, "tmp");
2566 InsertNewInstBefore(Add, I);
2567 Value *C1C2 = ConstantExpr::getMul(Op1,
2568 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002569 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002570
2571 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002572
2573 // Try to fold constant mul into select arguments.
2574 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002575 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002576 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002577
2578 if (isa<PHINode>(Op0))
2579 if (Instruction *NV = FoldOpIntoPhi(I))
2580 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002581 }
2582
Chris Lattnera4f445b2003-03-10 23:23:04 +00002583 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2584 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002585 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002586
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002587 if (I.getType() == Type::Int1Ty)
2588 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2589
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002590 // If one of the operands of the multiply is a cast from a boolean value, then
2591 // we know the bool is either zero or one, so this is a 'masking' multiply.
2592 // See if we can simplify things based on how the boolean was originally
2593 // formed.
2594 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002595 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002596 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002597 BoolCast = CI;
2598 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002599 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002600 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002601 BoolCast = CI;
2602 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002603 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002604 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2605 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002606 bool TIS = false;
2607
Reid Spencere4d87aa2006-12-23 06:05:41 +00002608 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002609 // multiply into a shift/and combination.
2610 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002611 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2612 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002613 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002614 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002615 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002616 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002617 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002618 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002619 BoolCast->getOperand(0)->getName()+
2620 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002621
2622 // If the multiply type is not the same as the source type, sign extend
2623 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002624 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002625 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2626 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002627 Instruction::CastOps opcode =
2628 (SrcBits == DstBits ? Instruction::BitCast :
2629 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2630 V = InsertCastBefore(opcode, V, I.getType(), I);
2631 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002632
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002633 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002634 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002635 }
2636 }
2637 }
2638
Chris Lattner7e708292002-06-25 16:13:24 +00002639 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002640}
2641
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002642/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2643/// instruction.
2644bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2645 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2646
2647 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2648 int NonNullOperand = -1;
2649 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2650 if (ST->isNullValue())
2651 NonNullOperand = 2;
2652 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2653 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2654 if (ST->isNullValue())
2655 NonNullOperand = 1;
2656
2657 if (NonNullOperand == -1)
2658 return false;
2659
2660 Value *SelectCond = SI->getOperand(0);
2661
2662 // Change the div/rem to use 'Y' instead of the select.
2663 I.setOperand(1, SI->getOperand(NonNullOperand));
2664
2665 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2666 // problem. However, the select, or the condition of the select may have
2667 // multiple uses. Based on our knowledge that the operand must be non-zero,
2668 // propagate the known value for the select into other uses of it, and
2669 // propagate a known value of the condition into its other users.
2670
2671 // If the select and condition only have a single use, don't bother with this,
2672 // early exit.
2673 if (SI->use_empty() && SelectCond->hasOneUse())
2674 return true;
2675
2676 // Scan the current block backward, looking for other uses of SI.
2677 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2678
2679 while (BBI != BBFront) {
2680 --BBI;
2681 // If we found a call to a function, we can't assume it will return, so
2682 // information from below it cannot be propagated above it.
2683 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2684 break;
2685
2686 // Replace uses of the select or its condition with the known values.
2687 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2688 I != E; ++I) {
2689 if (*I == SI) {
2690 *I = SI->getOperand(NonNullOperand);
2691 AddToWorkList(BBI);
2692 } else if (*I == SelectCond) {
2693 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2694 ConstantInt::getFalse();
2695 AddToWorkList(BBI);
2696 }
2697 }
2698
2699 // If we past the instruction, quit looking for it.
2700 if (&*BBI == SI)
2701 SI = 0;
2702 if (&*BBI == SelectCond)
2703 SelectCond = 0;
2704
2705 // If we ran out of things to eliminate, break out of the loop.
2706 if (SelectCond == 0 && SI == 0)
2707 break;
2708
2709 }
2710 return true;
2711}
2712
2713
Reid Spencer1628cec2006-10-26 06:15:43 +00002714/// This function implements the transforms on div instructions that work
2715/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2716/// used by the visitors to those instructions.
2717/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002718Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002719 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002720
Chris Lattner50b2ca42008-02-19 06:12:18 +00002721 // undef / X -> 0 for integer.
2722 // undef / X -> undef for FP (the undef could be a snan).
2723 if (isa<UndefValue>(Op0)) {
2724 if (Op0->getType()->isFPOrFPVector())
2725 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002726 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002727 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002728
2729 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002730 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002731 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002732
Reid Spencer1628cec2006-10-26 06:15:43 +00002733 return 0;
2734}
Misha Brukmanfd939082005-04-21 23:48:37 +00002735
Reid Spencer1628cec2006-10-26 06:15:43 +00002736/// This function implements the transforms common to both integer division
2737/// instructions (udiv and sdiv). It is called by the visitors to those integer
2738/// division instructions.
2739/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002740Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002741 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2742
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002743 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002744 if (Op0 == Op1) {
2745 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2746 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2747 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2748 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2749 }
2750
2751 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2752 return ReplaceInstUsesWith(I, CI);
2753 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002754
Reid Spencer1628cec2006-10-26 06:15:43 +00002755 if (Instruction *Common = commonDivTransforms(I))
2756 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002757
2758 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2759 // This does not apply for fdiv.
2760 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2761 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002762
2763 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2764 // div X, 1 == X
2765 if (RHS->equalsInt(1))
2766 return ReplaceInstUsesWith(I, Op0);
2767
2768 // (X / C1) / C2 -> X / (C1*C2)
2769 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2770 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2771 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002772 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2773 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2774 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002775 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002776 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002777 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002778
Reid Spencerbca0e382007-03-23 20:05:17 +00002779 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002780 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2781 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2782 return R;
2783 if (isa<PHINode>(Op0))
2784 if (Instruction *NV = FoldOpIntoPhi(I))
2785 return NV;
2786 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002787 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002788
Chris Lattnera2881962003-02-18 19:28:33 +00002789 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002790 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002791 if (LHS->equalsInt(0))
2792 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2793
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002794 // It can't be division by zero, hence it must be division by one.
2795 if (I.getType() == Type::Int1Ty)
2796 return ReplaceInstUsesWith(I, Op0);
2797
Reid Spencer1628cec2006-10-26 06:15:43 +00002798 return 0;
2799}
2800
2801Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2802 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2803
2804 // Handle the integer div common cases
2805 if (Instruction *Common = commonIDivTransforms(I))
2806 return Common;
2807
2808 // X udiv C^2 -> X >> C
2809 // Check to see if this is an unsigned division with an exact power of 2,
2810 // if so, convert to a right shift.
2811 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002812 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002813 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002814 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002815 }
2816
2817 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002818 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002819 if (RHSI->getOpcode() == Instruction::Shl &&
2820 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002821 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002822 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002823 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002824 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002825 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002826 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002827 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002828 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002829 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002830 }
2831 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002832 }
2833
Reid Spencer1628cec2006-10-26 06:15:43 +00002834 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2835 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002836 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002837 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002838 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002839 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002840 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002841 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002842 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002843 // Construct the "on true" case of the select
2844 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002845 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002846 Op0, TC, SI->getName()+".t");
2847 TSI = InsertNewInstBefore(TSI, I);
2848
2849 // Construct the "on false" case of the select
2850 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002851 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002852 Op0, FC, SI->getName()+".f");
2853 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002854
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002855 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002856 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002857 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002858 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002859 return 0;
2860}
2861
Reid Spencer1628cec2006-10-26 06:15:43 +00002862Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2863 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2864
2865 // Handle the integer div common cases
2866 if (Instruction *Common = commonIDivTransforms(I))
2867 return Common;
2868
2869 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2870 // sdiv X, -1 == -X
2871 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002872 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002873
2874 // -X/C -> X/-C
2875 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002876 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00002877 }
2878
2879 // If the sign bits of both operands are zero (i.e. we can prove they are
2880 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002881 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002882 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002883 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002884 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002885 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002886 }
2887 }
2888
2889 return 0;
2890}
2891
2892Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2893 return commonDivTransforms(I);
2894}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002895
Reid Spencer0a783f72006-11-02 01:53:59 +00002896/// This function implements the transforms on rem instructions that work
2897/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2898/// is used by the visitors to those instructions.
2899/// @brief Transforms common to all three rem instructions
2900Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002901 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002902
Chris Lattner50b2ca42008-02-19 06:12:18 +00002903 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002904 if (Constant *LHS = dyn_cast<Constant>(Op0))
2905 if (LHS->isNullValue())
2906 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2907
Chris Lattner50b2ca42008-02-19 06:12:18 +00002908 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2909 if (I.getType()->isFPOrFPVector())
2910 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002911 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002912 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002913 if (isa<UndefValue>(Op1))
2914 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002915
2916 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002917 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2918 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00002919
Reid Spencer0a783f72006-11-02 01:53:59 +00002920 return 0;
2921}
2922
2923/// This function implements the transforms common to both integer remainder
2924/// instructions (urem and srem). It is called by the visitors to those integer
2925/// remainder instructions.
2926/// @brief Common integer remainder transforms
2927Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2928 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2929
2930 if (Instruction *common = commonRemTransforms(I))
2931 return common;
2932
Chris Lattner857e8cd2004-12-12 21:48:58 +00002933 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002934 // X % 0 == undef, we don't need to preserve faults!
2935 if (RHS->equalsInt(0))
2936 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2937
Chris Lattnera2881962003-02-18 19:28:33 +00002938 if (RHS->equalsInt(1)) // X % 1 == 0
2939 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2940
Chris Lattner97943922006-02-28 05:49:21 +00002941 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2942 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2943 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2944 return R;
2945 } else if (isa<PHINode>(Op0I)) {
2946 if (Instruction *NV = FoldOpIntoPhi(I))
2947 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002948 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002949
2950 // See if we can fold away this rem instruction.
2951 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2952 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2953 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2954 KnownZero, KnownOne))
2955 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00002956 }
Chris Lattnera2881962003-02-18 19:28:33 +00002957 }
2958
Reid Spencer0a783f72006-11-02 01:53:59 +00002959 return 0;
2960}
2961
2962Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2963 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2964
2965 if (Instruction *common = commonIRemTransforms(I))
2966 return common;
2967
2968 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2969 // X urem C^2 -> X and C
2970 // Check to see if this is an unsigned remainder with an exact power of 2,
2971 // if so, convert to a bitwise and.
2972 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002973 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002974 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00002975 }
2976
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002977 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002978 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2979 if (RHSI->getOpcode() == Instruction::Shl &&
2980 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002981 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002982 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002983 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002984 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002985 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002986 }
2987 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002988 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002989
Reid Spencer0a783f72006-11-02 01:53:59 +00002990 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2991 // where C1&C2 are powers of two.
2992 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2993 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2994 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2995 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002996 if ((STO->getValue().isPowerOf2()) &&
2997 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002998 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002999 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003000 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003001 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003002 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003003 }
3004 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003005 }
3006
Chris Lattner3f5b8772002-05-06 16:14:14 +00003007 return 0;
3008}
3009
Reid Spencer0a783f72006-11-02 01:53:59 +00003010Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3011 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3012
Dan Gohmancff55092007-11-05 23:16:33 +00003013 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003014 if (Instruction *common = commonIRemTransforms(I))
3015 return common;
3016
3017 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003018 if (!isa<Constant>(RHSNeg) ||
3019 (isa<ConstantInt>(RHSNeg) &&
3020 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003021 // X % -Y -> X % Y
3022 AddUsesToWorkList(I);
3023 I.setOperand(1, RHSNeg);
3024 return &I;
3025 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003026
Dan Gohmancff55092007-11-05 23:16:33 +00003027 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003028 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003029 if (I.getType()->isInteger()) {
3030 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3031 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3032 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003033 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003034 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003035 }
3036
3037 return 0;
3038}
3039
3040Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003041 return commonRemTransforms(I);
3042}
3043
Chris Lattner457dd822004-06-09 07:59:58 +00003044// isOneBitSet - Return true if there is exactly one bit set in the specified
3045// constant.
3046static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003047 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003048}
3049
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003050// isHighOnes - Return true if the constant is of the form 1+0+.
3051// This is the same as lowones(~X).
3052static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003053 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003054}
3055
Reid Spencere4d87aa2006-12-23 06:05:41 +00003056/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003057/// are carefully arranged to allow folding of expressions such as:
3058///
3059/// (A < B) | (A > B) --> (A != B)
3060///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003061/// Note that this is only valid if the first and second predicates have the
3062/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003063///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003064/// Three bits are used to represent the condition, as follows:
3065/// 0 A > B
3066/// 1 A == B
3067/// 2 A < B
3068///
3069/// <=> Value Definition
3070/// 000 0 Always false
3071/// 001 1 A > B
3072/// 010 2 A == B
3073/// 011 3 A >= B
3074/// 100 4 A < B
3075/// 101 5 A != B
3076/// 110 6 A <= B
3077/// 111 7 Always true
3078///
3079static unsigned getICmpCode(const ICmpInst *ICI) {
3080 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003081 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003082 case ICmpInst::ICMP_UGT: return 1; // 001
3083 case ICmpInst::ICMP_SGT: return 1; // 001
3084 case ICmpInst::ICMP_EQ: return 2; // 010
3085 case ICmpInst::ICMP_UGE: return 3; // 011
3086 case ICmpInst::ICMP_SGE: return 3; // 011
3087 case ICmpInst::ICMP_ULT: return 4; // 100
3088 case ICmpInst::ICMP_SLT: return 4; // 100
3089 case ICmpInst::ICMP_NE: return 5; // 101
3090 case ICmpInst::ICMP_ULE: return 6; // 110
3091 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003092 // True -> 7
3093 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003094 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003095 return 0;
3096 }
3097}
3098
Reid Spencere4d87aa2006-12-23 06:05:41 +00003099/// getICmpValue - This is the complement of getICmpCode, which turns an
3100/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003101/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003102/// of predicate to use in new icmp instructions.
3103static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3104 switch (code) {
3105 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003106 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003107 case 1:
3108 if (sign)
3109 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3110 else
3111 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3112 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3113 case 3:
3114 if (sign)
3115 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3116 else
3117 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3118 case 4:
3119 if (sign)
3120 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3121 else
3122 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3123 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3124 case 6:
3125 if (sign)
3126 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3127 else
3128 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003129 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003130 }
3131}
3132
Reid Spencere4d87aa2006-12-23 06:05:41 +00003133static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3134 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3135 (ICmpInst::isSignedPredicate(p1) &&
3136 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3137 (ICmpInst::isSignedPredicate(p2) &&
3138 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3139}
3140
3141namespace {
3142// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3143struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003144 InstCombiner &IC;
3145 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003146 ICmpInst::Predicate pred;
3147 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3148 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3149 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003150 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003151 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3152 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003153 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3154 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003155 return false;
3156 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003157 Instruction *apply(Instruction &Log) const {
3158 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3159 if (ICI->getOperand(0) != LHS) {
3160 assert(ICI->getOperand(1) == LHS);
3161 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003162 }
3163
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003164 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003165 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003166 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003167 unsigned Code;
3168 switch (Log.getOpcode()) {
3169 case Instruction::And: Code = LHSCode & RHSCode; break;
3170 case Instruction::Or: Code = LHSCode | RHSCode; break;
3171 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003172 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003173 }
3174
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003175 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3176 ICmpInst::isSignedPredicate(ICI->getPredicate());
3177
3178 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003179 if (Instruction *I = dyn_cast<Instruction>(RV))
3180 return I;
3181 // Otherwise, it's a constant boolean value...
3182 return IC.ReplaceInstUsesWith(Log, RV);
3183 }
3184};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003185} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003186
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003187// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3188// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003189// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003190Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003191 ConstantInt *OpRHS,
3192 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003193 BinaryOperator &TheAnd) {
3194 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003195 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003196 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003197 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003198
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003199 switch (Op->getOpcode()) {
3200 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003201 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003202 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003203 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003204 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003205 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003206 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003207 }
3208 break;
3209 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003210 if (Together == AndRHS) // (X | C) & C --> C
3211 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003212
Chris Lattner6e7ba452005-01-01 16:22:27 +00003213 if (Op->hasOneUse() && Together != OpRHS) {
3214 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003215 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003216 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003217 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003218 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003219 }
3220 break;
3221 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003222 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003223 // Adding a one to a single bit bit-field should be turned into an XOR
3224 // of the bit. First thing to check is to see if this AND is with a
3225 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003226 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003227
3228 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003229 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003230 // Ok, at this point, we know that we are masking the result of the
3231 // ADD down to exactly one bit. If the constant we are adding has
3232 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003233 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003234
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003235 // Check to see if any bits below the one bit set in AndRHSV are set.
3236 if ((AddRHS & (AndRHSV-1)) == 0) {
3237 // If not, the only thing that can effect the output of the AND is
3238 // the bit specified by AndRHSV. If that bit is set, the effect of
3239 // the XOR is to toggle the bit. If it is clear, then the ADD has
3240 // no effect.
3241 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3242 TheAnd.setOperand(0, X);
3243 return &TheAnd;
3244 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003245 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003246 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003247 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003248 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003249 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003250 }
3251 }
3252 }
3253 }
3254 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003255
3256 case Instruction::Shl: {
3257 // We know that the AND will not produce any of the bits shifted in, so if
3258 // the anded constant includes them, clear them now!
3259 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003260 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003261 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003262 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3263 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003264
Zhou Sheng290bec52007-03-29 08:15:12 +00003265 if (CI->getValue() == ShlMask) {
3266 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003267 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3268 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003269 TheAnd.setOperand(1, CI);
3270 return &TheAnd;
3271 }
3272 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003273 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003274 case Instruction::LShr:
3275 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003276 // We know that the AND will not produce any of the bits shifted in, so if
3277 // the anded constant includes them, clear them now! This only applies to
3278 // unsigned shifts, because a signed shr may bring in set bits!
3279 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003280 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003281 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003282 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3283 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003284
Zhou Sheng290bec52007-03-29 08:15:12 +00003285 if (CI->getValue() == ShrMask) {
3286 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003287 return ReplaceInstUsesWith(TheAnd, Op);
3288 } else if (CI != AndRHS) {
3289 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3290 return &TheAnd;
3291 }
3292 break;
3293 }
3294 case Instruction::AShr:
3295 // Signed shr.
3296 // See if this is shifting in some sign extension, then masking it out
3297 // with an and.
3298 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003299 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003300 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003301 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3302 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003303 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003304 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003305 // Make the argument unsigned.
3306 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003307 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003308 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003309 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003310 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003311 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003312 }
3313 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003314 }
3315 return 0;
3316}
3317
Chris Lattner8b170942002-08-09 23:47:40 +00003318
Chris Lattnera96879a2004-09-29 17:40:11 +00003319/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3320/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003321/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3322/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003323/// insert new instructions.
3324Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003325 bool isSigned, bool Inside,
3326 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003327 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003328 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003329 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003330
Chris Lattnera96879a2004-09-29 17:40:11 +00003331 if (Inside) {
3332 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003333 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003334
Reid Spencere4d87aa2006-12-23 06:05:41 +00003335 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003336 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003337 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003338 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3339 return new ICmpInst(pred, V, Hi);
3340 }
3341
3342 // Emit V-Lo <u Hi-Lo
3343 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003344 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003345 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003346 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3347 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003348 }
3349
3350 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003351 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003352
Reid Spencere4e40032007-03-21 23:19:50 +00003353 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003354 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003355 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003356 ICmpInst::Predicate pred = (isSigned ?
3357 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3358 return new ICmpInst(pred, V, Hi);
3359 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003360
Reid Spencere4e40032007-03-21 23:19:50 +00003361 // Emit V-Lo >u Hi-1-Lo
3362 // Note that Hi has already had one subtracted from it, above.
3363 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003364 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003365 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003366 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3367 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003368}
3369
Chris Lattner7203e152005-09-18 07:22:02 +00003370// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3371// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3372// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3373// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003374static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003375 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003376 uint32_t BitWidth = Val->getType()->getBitWidth();
3377 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003378
3379 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003380 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003381 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003382 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003383 return true;
3384}
3385
Chris Lattner7203e152005-09-18 07:22:02 +00003386/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3387/// where isSub determines whether the operator is a sub. If we can fold one of
3388/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003389///
3390/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3391/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3392/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3393///
3394/// return (A +/- B).
3395///
3396Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003397 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003398 Instruction &I) {
3399 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3400 if (!LHSI || LHSI->getNumOperands() != 2 ||
3401 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3402
3403 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3404
3405 switch (LHSI->getOpcode()) {
3406 default: return 0;
3407 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003408 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003409 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003410 if ((Mask->getValue().countLeadingZeros() +
3411 Mask->getValue().countPopulation()) ==
3412 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003413 break;
3414
3415 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3416 // part, we don't need any explicit masks to take them out of A. If that
3417 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003418 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003419 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003420 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003421 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003422 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003423 break;
3424 }
3425 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003426 return 0;
3427 case Instruction::Or:
3428 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003429 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003430 if ((Mask->getValue().countLeadingZeros() +
3431 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003432 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003433 break;
3434 return 0;
3435 }
3436
3437 Instruction *New;
3438 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003439 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003440 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003441 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003442 return InsertNewInstBefore(New, I);
3443}
3444
Chris Lattner7e708292002-06-25 16:13:24 +00003445Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003446 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003447 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003448
Chris Lattnere87597f2004-10-16 18:11:37 +00003449 if (isa<UndefValue>(Op1)) // X & undef -> 0
3450 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3451
Chris Lattner6e7ba452005-01-01 16:22:27 +00003452 // and X, X = X
3453 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003454 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003455
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003456 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003457 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003458 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003459 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3460 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3461 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003462 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003463 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003464 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003465 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003466 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003467 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003468 } else if (isa<ConstantAggregateZero>(Op1)) {
3469 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003470 }
3471 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003472
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003473 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003474 const APInt& AndRHSMask = AndRHS->getValue();
3475 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003476
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003477 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003478 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003479 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003480 Value *Op0LHS = Op0I->getOperand(0);
3481 Value *Op0RHS = Op0I->getOperand(1);
3482 switch (Op0I->getOpcode()) {
3483 case Instruction::Xor:
3484 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003485 // If the mask is only needed on one incoming arm, push it up.
3486 if (Op0I->hasOneUse()) {
3487 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3488 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003489 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003490 Op0RHS->getName()+".masked");
3491 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003492 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003493 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003494 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003495 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003496 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3497 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003498 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003499 Op0LHS->getName()+".masked");
3500 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003501 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003502 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3503 }
3504 }
3505
Chris Lattner6e7ba452005-01-01 16:22:27 +00003506 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003507 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003508 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3509 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3510 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3511 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003512 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003513 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003514 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003515 break;
3516
3517 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003518 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3519 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3520 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3521 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003522 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003523
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003524 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3525 // has 1's for all bits that the subtraction with A might affect.
3526 if (Op0I->hasOneUse()) {
3527 uint32_t BitWidth = AndRHSMask.getBitWidth();
3528 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3529 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3530
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003531 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003532 if (!(A && A->isZero()) && // avoid infinite recursion.
3533 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003534 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3535 InsertNewInstBefore(NewNeg, I);
3536 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3537 }
3538 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003539 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003540
3541 case Instruction::Shl:
3542 case Instruction::LShr:
3543 // (1 << x) & 1 --> zext(x == 0)
3544 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00003545 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003546 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3547 Constant::getNullValue(I.getType()));
3548 InsertNewInstBefore(NewICmp, I);
3549 return new ZExtInst(NewICmp, I.getType());
3550 }
3551 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003552 }
3553
Chris Lattner58403262003-07-23 19:25:52 +00003554 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003555 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003556 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003557 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003558 // If this is an integer truncation or change from signed-to-unsigned, and
3559 // if the source is an and/or with immediate, transform it. This
3560 // frequently occurs for bitfield accesses.
3561 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003562 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003563 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003564 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003565 if (CastOp->getOpcode() == Instruction::And) {
3566 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003567 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3568 // This will fold the two constants together, which may allow
3569 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003570 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003571 CastOp->getOperand(0), I.getType(),
3572 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003573 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003574 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003575 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003576 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003577 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003578 } else if (CastOp->getOpcode() == Instruction::Or) {
3579 // Change: and (cast (or X, C1) to T), C2
3580 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003581 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003582 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3583 return ReplaceInstUsesWith(I, AndRHS);
3584 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003585 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003586 }
Chris Lattner06782f82003-07-23 19:36:21 +00003587 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003588
3589 // Try to fold constant and into select arguments.
3590 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003591 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003592 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003593 if (isa<PHINode>(Op0))
3594 if (Instruction *NV = FoldOpIntoPhi(I))
3595 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003596 }
3597
Chris Lattner8d969642003-03-10 23:06:50 +00003598 Value *Op0NotVal = dyn_castNotVal(Op0);
3599 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003600
Chris Lattner5b62aa72004-06-18 06:07:51 +00003601 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3602 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3603
Misha Brukmancb6267b2004-07-30 12:50:08 +00003604 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003605 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003606 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003607 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003608 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003609 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003610 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003611
3612 {
Chris Lattner003b6202007-06-15 05:58:24 +00003613 Value *A = 0, *B = 0, *C = 0, *D = 0;
3614 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003615 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3616 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003617
3618 // (A|B) & ~(A&B) -> A^B
3619 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3620 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003621 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003622 }
3623 }
3624
3625 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003626 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3627 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003628
3629 // ~(A&B) & (A|B) -> A^B
3630 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3631 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003632 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003633 }
3634 }
Chris Lattner64daab52006-04-01 08:03:55 +00003635
3636 if (Op0->hasOneUse() &&
3637 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3638 if (A == Op1) { // (A^B)&A -> A&(A^B)
3639 I.swapOperands(); // Simplify below
3640 std::swap(Op0, Op1);
3641 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3642 cast<BinaryOperator>(Op0)->swapOperands();
3643 I.swapOperands(); // Simplify below
3644 std::swap(Op0, Op1);
3645 }
3646 }
3647 if (Op1->hasOneUse() &&
3648 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3649 if (B == Op0) { // B&(A^B) -> B&(B^A)
3650 cast<BinaryOperator>(Op1)->swapOperands();
3651 std::swap(A, B);
3652 }
3653 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003654 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003655 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003656 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003657 }
3658 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003659 }
3660
Nick Lewyckyb30591e2008-08-06 04:54:03 +00003661 { // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3662 // where C is a power of 2
3663 Value *A, *B;
3664 ConstantInt *C1, *C2;
Evan Chengab5d5e32008-08-20 23:36:48 +00003665 ICmpInst::Predicate LHSCC = ICmpInst::BAD_ICMP_PREDICATE;
3666 ICmpInst::Predicate RHSCC = ICmpInst::BAD_ICMP_PREDICATE;
Nick Lewyckyb30591e2008-08-06 04:54:03 +00003667 if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3668 m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3669 if (C1 == C2 && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3670 C1->getValue().isPowerOf2()) {
3671 Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3672 InsertNewInstBefore(NewOr, I);
3673 return new ICmpInst(LHSCC, NewOr, C1);
3674 }
3675 }
3676
Reid Spencere4d87aa2006-12-23 06:05:41 +00003677 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3678 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3679 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003680 return R;
3681
Chris Lattner955f3312004-09-28 21:48:02 +00003682 Value *LHSVal, *RHSVal;
3683 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003684 ICmpInst::Predicate LHSCC, RHSCC;
3685 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3686 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3687 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3688 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3689 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3690 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3691 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003692 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3693
3694 // Don't try to fold ICMP_SLT + ICMP_ULT.
3695 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3696 ICmpInst::isSignedPredicate(LHSCC) ==
3697 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003698 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003699 ICmpInst::Predicate GT;
3700 if (ICmpInst::isSignedPredicate(LHSCC) ||
3701 (ICmpInst::isEquality(LHSCC) &&
3702 ICmpInst::isSignedPredicate(RHSCC)))
3703 GT = ICmpInst::ICMP_SGT;
3704 else
3705 GT = ICmpInst::ICMP_UGT;
3706
Reid Spencere4d87aa2006-12-23 06:05:41 +00003707 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3708 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003709 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003710 std::swap(LHS, RHS);
3711 std::swap(LHSCst, RHSCst);
3712 std::swap(LHSCC, RHSCC);
3713 }
3714
Reid Spencere4d87aa2006-12-23 06:05:41 +00003715 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003716 // comparing a value against two constants and and'ing the result
3717 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003718 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3719 // (from the FoldICmpLogical check above), that the two constants
3720 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003721 assert(LHSCst != RHSCst && "Compares not folded above?");
3722
3723 switch (LHSCC) {
3724 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003725 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003726 switch (RHSCC) {
3727 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003728 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3729 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3730 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003731 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003732 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3733 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3734 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003735 return ReplaceInstUsesWith(I, LHS);
3736 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003737 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003738 switch (RHSCC) {
3739 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003740 case ICmpInst::ICMP_ULT:
3741 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3742 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3743 break; // (X != 13 & X u< 15) -> no change
3744 case ICmpInst::ICMP_SLT:
3745 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3746 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3747 break; // (X != 13 & X s< 15) -> no change
3748 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3749 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3750 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003751 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003752 case ICmpInst::ICMP_NE:
3753 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003754 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003755 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00003756 LHSVal->getName()+".off");
3757 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003758 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3759 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003760 }
3761 break; // (X != 13 & X != 15) -> no change
3762 }
3763 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003764 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003765 switch (RHSCC) {
3766 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003767 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3768 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003769 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003770 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3771 break;
3772 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3773 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003774 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003775 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3776 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003777 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003778 break;
3779 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003780 switch (RHSCC) {
3781 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003782 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3783 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003784 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003785 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3786 break;
3787 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3788 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003789 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003790 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3791 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003792 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003793 break;
3794 case ICmpInst::ICMP_UGT:
3795 switch (RHSCC) {
3796 default: assert(0 && "Unknown integer condition code!");
Eli Friedman5c1f1722008-06-21 23:36:13 +00003797 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003798 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3799 return ReplaceInstUsesWith(I, RHS);
3800 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3801 break;
3802 case ICmpInst::ICMP_NE:
3803 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3804 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3805 break; // (X u> 13 & X != 15) -> no change
3806 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3807 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3808 true, I);
3809 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3810 break;
3811 }
3812 break;
3813 case ICmpInst::ICMP_SGT:
3814 switch (RHSCC) {
3815 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003816 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003817 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3818 return ReplaceInstUsesWith(I, RHS);
3819 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3820 break;
3821 case ICmpInst::ICMP_NE:
3822 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3823 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3824 break; // (X s> 13 & X != 15) -> no change
3825 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3826 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3827 true, I);
3828 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3829 break;
3830 }
3831 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003832 }
3833 }
3834 }
3835
Chris Lattner6fc205f2006-05-05 06:39:07 +00003836 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003837 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3838 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3839 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3840 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003841 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003842 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003843 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3844 I.getType(), TD) &&
3845 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3846 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003847 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003848 Op1C->getOperand(0),
3849 I.getName());
3850 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003851 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003852 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003853 }
Chris Lattnere511b742006-11-14 07:46:50 +00003854
3855 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003856 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3857 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3858 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003859 SI0->getOperand(1) == SI1->getOperand(1) &&
3860 (SI0->hasOneUse() || SI1->hasOneUse())) {
3861 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003862 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00003863 SI1->getOperand(0),
3864 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003865 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00003866 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003867 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003868 }
3869
Chris Lattner99c65742007-10-24 05:38:08 +00003870 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3871 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3872 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3873 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3874 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3875 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3876 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3877 // If either of the constants are nans, then the whole thing returns
3878 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003879 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003880 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3881 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3882 RHS->getOperand(0));
3883 }
3884 }
3885 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003886
Chris Lattner7e708292002-06-25 16:13:24 +00003887 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003888}
3889
Chris Lattner8c34cd22008-10-05 02:13:19 +00003890/// CollectBSwapParts - Analyze the specified subexpression and see if it is
3891/// capable of providing pieces of a bswap. The subexpression provides pieces
3892/// of a bswap if it is proven that each of the non-zero bytes in the output of
3893/// the expression came from the corresponding "byte swapped" byte in some other
3894/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
3895/// we know that the expression deposits the low byte of %X into the high byte
3896/// of the bswap result and that all other bytes are zero. This expression is
3897/// accepted, the high byte of ByteValues is set to X to indicate a correct
3898/// match.
3899///
3900/// This function returns true if the match was unsuccessful and false if so.
3901/// On entry to the function the "OverallLeftShift" is a signed integer value
3902/// indicating the number of bytes that the subexpression is later shifted. For
3903/// example, if the expression is later right shifted by 16 bits, the
3904/// OverallLeftShift value would be -2 on entry. This is used to specify which
3905/// byte of ByteValues is actually being set.
3906///
3907/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
3908/// byte is masked to zero by a user. For example, in (X & 255), X will be
3909/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
3910/// this function to working on up to 32-byte (256 bit) values. ByteMask is
3911/// always in the local (OverallLeftShift) coordinate space.
3912///
3913static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
3914 SmallVector<Value*, 8> &ByteValues) {
3915 if (Instruction *I = dyn_cast<Instruction>(V)) {
3916 // If this is an or instruction, it may be an inner node of the bswap.
3917 if (I->getOpcode() == Instruction::Or) {
3918 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3919 ByteValues) ||
3920 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
3921 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003922 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00003923
3924 // If this is a logical shift by a constant multiple of 8, recurse with
3925 // OverallLeftShift and ByteMask adjusted.
3926 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
3927 unsigned ShAmt =
3928 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
3929 // Ensure the shift amount is defined and of a byte value.
3930 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
3931 return true;
3932
3933 unsigned ByteShift = ShAmt >> 3;
3934 if (I->getOpcode() == Instruction::Shl) {
3935 // X << 2 -> collect(X, +2)
3936 OverallLeftShift += ByteShift;
3937 ByteMask >>= ByteShift;
3938 } else {
3939 // X >>u 2 -> collect(X, -2)
3940 OverallLeftShift -= ByteShift;
3941 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00003942 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00003943 }
3944
3945 if (OverallLeftShift >= (int)ByteValues.size()) return true;
3946 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
3947
3948 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3949 ByteValues);
3950 }
3951
3952 // If this is a logical 'and' with a mask that clears bytes, clear the
3953 // corresponding bytes in ByteMask.
3954 if (I->getOpcode() == Instruction::And &&
3955 isa<ConstantInt>(I->getOperand(1))) {
3956 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
3957 unsigned NumBytes = ByteValues.size();
3958 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
3959 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
3960
3961 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
3962 // If this byte is masked out by a later operation, we don't care what
3963 // the and mask is.
3964 if ((ByteMask & (1 << i)) == 0)
3965 continue;
3966
3967 // If the AndMask is all zeros for this byte, clear the bit.
3968 APInt MaskB = AndMask & Byte;
3969 if (MaskB == 0) {
3970 ByteMask &= ~(1U << i);
3971 continue;
3972 }
3973
3974 // If the AndMask is not all ones for this byte, it's not a bytezap.
3975 if (MaskB != Byte)
3976 return true;
3977
3978 // Otherwise, this byte is kept.
3979 }
3980
3981 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3982 ByteValues);
3983 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00003984 }
3985
Chris Lattner8c34cd22008-10-05 02:13:19 +00003986 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
3987 // the input value to the bswap. Some observations: 1) if more than one byte
3988 // is demanded from this input, then it could not be successfully assembled
3989 // into a byteswap. At least one of the two bytes would not be aligned with
3990 // their ultimate destination.
3991 if (!isPowerOf2_32(ByteMask)) return true;
3992 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003993
Chris Lattner8c34cd22008-10-05 02:13:19 +00003994 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
3995 // is demanded, it needs to go into byte 0 of the result. This means that the
3996 // byte needs to be shifted until it lands in the right byte bucket. The
3997 // shift amount depends on the position: if the byte is coming from the high
3998 // part of the value (e.g. byte 3) then it must be shifted right. If from the
3999 // low part, it must be shifted left.
4000 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4001 if (InputByteNo < ByteValues.size()/2) {
4002 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4003 return true;
4004 } else {
4005 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4006 return true;
4007 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004008
4009 // If the destination byte value is already defined, the values are or'd
4010 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004011 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004012 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004013 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004014 return false;
4015}
4016
4017/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4018/// If so, insert the new bswap intrinsic and return it.
4019Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004020 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004021 if (!ITy || ITy->getBitWidth() % 16 ||
4022 // ByteMask only allows up to 32-byte values.
4023 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004024 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004025
4026 /// ByteValues - For each byte of the result, we keep track of which value
4027 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004028 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004029 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004030
4031 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004032 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4033 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004034 return 0;
4035
4036 // Check to see if all of the bytes come from the same value.
4037 Value *V = ByteValues[0];
4038 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4039
4040 // Check to make sure that all of the bytes come from the same value.
4041 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4042 if (ByteValues[i] != V)
4043 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004044 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004045 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004046 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004047 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004048}
4049
4050
Chris Lattner7e708292002-06-25 16:13:24 +00004051Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004052 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004053 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004054
Chris Lattner42593e62007-03-24 23:56:43 +00004055 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004056 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004057
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004058 // or X, X = X
4059 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004060 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004061
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004062 // See if we can simplify any instructions used by the instruction whose sole
4063 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004064 if (!isa<VectorType>(I.getType())) {
4065 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4066 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4067 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4068 KnownZero, KnownOne))
4069 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004070 } else if (isa<ConstantAggregateZero>(Op1)) {
4071 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4072 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4073 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4074 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004075 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004076
4077
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004078
Chris Lattner3f5b8772002-05-06 16:14:14 +00004079 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004080 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004081 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004082 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4083 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004084 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004085 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004086 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004087 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004088 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004089 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004090
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004091 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4092 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004093 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004094 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004095 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004096 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004097 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004098 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004099
4100 // Try to fold constant and into select arguments.
4101 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004102 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004103 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004104 if (isa<PHINode>(Op0))
4105 if (Instruction *NV = FoldOpIntoPhi(I))
4106 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004107 }
4108
Chris Lattner4f637d42006-01-06 17:59:59 +00004109 Value *A = 0, *B = 0;
4110 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004111
4112 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4113 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4114 return ReplaceInstUsesWith(I, Op1);
4115 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4116 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4117 return ReplaceInstUsesWith(I, Op0);
4118
Chris Lattner6423d4c2006-07-10 20:25:24 +00004119 // (A | B) | C and A | (B | C) -> bswap if possible.
4120 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004121 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004122 match(Op1, m_Or(m_Value(), m_Value())) ||
4123 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4124 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004125 if (Instruction *BSwap = MatchBSwap(I))
4126 return BSwap;
4127 }
4128
Chris Lattner6e4c6492005-05-09 04:58:36 +00004129 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4130 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004131 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004132 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004133 InsertNewInstBefore(NOr, I);
4134 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004135 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004136 }
4137
4138 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4139 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004140 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004141 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004142 InsertNewInstBefore(NOr, I);
4143 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004144 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004145 }
4146
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004147 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004148 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004149 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4150 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004151 Value *V1 = 0, *V2 = 0, *V3 = 0;
4152 C1 = dyn_cast<ConstantInt>(C);
4153 C2 = dyn_cast<ConstantInt>(D);
4154 if (C1 && C2) { // (A & C1)|(B & C2)
4155 // If we have: ((V + N) & C1) | (V & C2)
4156 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4157 // replace with V+N.
4158 if (C1->getValue() == ~C2->getValue()) {
4159 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4160 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4161 // Add commutes, try both ways.
4162 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4163 return ReplaceInstUsesWith(I, A);
4164 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4165 return ReplaceInstUsesWith(I, A);
4166 }
4167 // Or commutes, try both ways.
4168 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4169 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4170 // Add commutes, try both ways.
4171 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4172 return ReplaceInstUsesWith(I, B);
4173 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4174 return ReplaceInstUsesWith(I, B);
4175 }
4176 }
Chris Lattner044e5332007-04-08 08:01:49 +00004177 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004178 }
4179
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004180 // Check to see if we have any common things being and'ed. If so, find the
4181 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004182 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4183 if (A == B) // (A & C)|(A & D) == A & (C|D)
4184 V1 = A, V2 = C, V3 = D;
4185 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4186 V1 = A, V2 = B, V3 = C;
4187 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4188 V1 = C, V2 = A, V3 = D;
4189 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4190 V1 = C, V2 = A, V3 = B;
4191
4192 if (V1) {
4193 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004194 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4195 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004196 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004197 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004198 }
Chris Lattnere511b742006-11-14 07:46:50 +00004199
4200 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004201 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4202 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4203 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004204 SI0->getOperand(1) == SI1->getOperand(1) &&
4205 (SI0->hasOneUse() || SI1->hasOneUse())) {
4206 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004207 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004208 SI1->getOperand(0),
4209 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004210 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004211 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004212 }
4213 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004214
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004215 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4216 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004217 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004218 } else {
4219 A = 0;
4220 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004221 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004222 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4223 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004224 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004225
Misha Brukmancb6267b2004-07-30 12:50:08 +00004226 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004227 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004228 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004229 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004230 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004231 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004232 }
Chris Lattnera2881962003-02-18 19:28:33 +00004233
Reid Spencere4d87aa2006-12-23 06:05:41 +00004234 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4235 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4236 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004237 return R;
4238
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004239 Value *LHSVal, *RHSVal;
4240 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004241 ICmpInst::Predicate LHSCC, RHSCC;
4242 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4243 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4244 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4245 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4246 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4247 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4248 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004249 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4250 // We can't fold (ugt x, C) | (sgt x, C2).
4251 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004252 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004253 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004254 bool NeedsSwap;
Nick Lewyckya06cf822008-09-30 06:08:34 +00004255 if (ICmpInst::isEquality(LHSCC) ? ICmpInst::isSignedPredicate(RHSCC)
4256 : ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004257 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004258 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004259 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004260
4261 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004262 std::swap(LHS, RHS);
4263 std::swap(LHSCst, RHSCst);
4264 std::swap(LHSCC, RHSCC);
4265 }
4266
Reid Spencere4d87aa2006-12-23 06:05:41 +00004267 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004268 // comparing a value against two constants and or'ing the result
4269 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004270 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4271 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004272 // equal.
4273 assert(LHSCst != RHSCst && "Compares not folded above?");
4274
4275 switch (LHSCC) {
4276 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004277 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004278 switch (RHSCC) {
4279 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004280 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004281 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4282 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004283 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004284 LHSVal->getName()+".off");
4285 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004286 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004287 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004288 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004289 break; // (X == 13 | X == 15) -> no change
4290 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4291 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004292 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004293 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4294 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4295 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004296 return ReplaceInstUsesWith(I, RHS);
4297 }
4298 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004299 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004300 switch (RHSCC) {
4301 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004302 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4303 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4304 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004305 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004306 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4307 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4308 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004309 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004310 }
4311 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004312 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004313 switch (RHSCC) {
4314 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004315 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004316 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004317 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004318 // If RHSCst is [us]MAXINT, it is always false. Not handling
4319 // this can cause overflow.
4320 if (RHSCst->isMaxValue(false))
4321 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004322 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4323 false, I);
4324 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4325 break;
4326 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4327 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004328 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004329 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4330 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004331 }
4332 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004333 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004334 switch (RHSCC) {
4335 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004336 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4337 break;
4338 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004339 // If RHSCst is [us]MAXINT, it is always false. Not handling
4340 // this can cause overflow.
4341 if (RHSCst->isMaxValue(true))
4342 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004343 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4344 false, I);
4345 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4346 break;
4347 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4348 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4349 return ReplaceInstUsesWith(I, RHS);
4350 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4351 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004352 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004353 break;
4354 case ICmpInst::ICMP_UGT:
4355 switch (RHSCC) {
4356 default: assert(0 && "Unknown integer condition code!");
4357 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4358 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4359 return ReplaceInstUsesWith(I, LHS);
4360 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4361 break;
4362 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4363 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004364 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004365 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4366 break;
4367 }
4368 break;
4369 case ICmpInst::ICMP_SGT:
4370 switch (RHSCC) {
4371 default: assert(0 && "Unknown integer condition code!");
4372 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4373 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4374 return ReplaceInstUsesWith(I, LHS);
4375 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4376 break;
4377 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4378 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004379 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004380 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4381 break;
4382 }
4383 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004384 }
4385 }
4386 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004387
4388 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004389 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004390 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004391 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004392 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4393 !isa<ICmpInst>(Op1C->getOperand(0))) {
4394 const Type *SrcTy = Op0C->getOperand(0)->getType();
4395 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4396 // Only do this if the casts both really cause code to be
4397 // generated.
4398 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4399 I.getType(), TD) &&
4400 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4401 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004402 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004403 Op1C->getOperand(0),
4404 I.getName());
4405 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004406 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004407 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004408 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004409 }
Chris Lattner99c65742007-10-24 05:38:08 +00004410 }
4411
4412
4413 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4414 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4415 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4416 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004417 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4418 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004419 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4420 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4421 // If either of the constants are nans, then the whole thing returns
4422 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004423 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004424 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4425
4426 // Otherwise, no need to compare the two constants, compare the
4427 // rest.
4428 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4429 RHS->getOperand(0));
4430 }
4431 }
4432 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004433
Chris Lattner7e708292002-06-25 16:13:24 +00004434 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004435}
4436
Dan Gohman844731a2008-05-13 00:00:25 +00004437namespace {
4438
Chris Lattnerc317d392004-02-16 01:20:27 +00004439// XorSelf - Implements: X ^ X --> 0
4440struct XorSelf {
4441 Value *RHS;
4442 XorSelf(Value *rhs) : RHS(rhs) {}
4443 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4444 Instruction *apply(BinaryOperator &Xor) const {
4445 return &Xor;
4446 }
4447};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004448
Dan Gohman844731a2008-05-13 00:00:25 +00004449}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004450
Chris Lattner7e708292002-06-25 16:13:24 +00004451Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004452 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004453 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004454
Evan Chengd34af782008-03-25 20:07:13 +00004455 if (isa<UndefValue>(Op1)) {
4456 if (isa<UndefValue>(Op0))
4457 // Handle undef ^ undef -> 0 special case. This is a common
4458 // idiom (misuse).
4459 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004460 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004461 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004462
Chris Lattnerc317d392004-02-16 01:20:27 +00004463 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4464 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004465 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004466 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004467 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004468
4469 // See if we can simplify any instructions used by the instruction whose sole
4470 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004471 if (!isa<VectorType>(I.getType())) {
4472 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4473 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4474 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4475 KnownZero, KnownOne))
4476 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004477 } else if (isa<ConstantAggregateZero>(Op1)) {
4478 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004479 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004480
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004481 // Is this a ~ operation?
4482 if (Value *NotOp = dyn_castNotVal(&I)) {
4483 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4484 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4485 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4486 if (Op0I->getOpcode() == Instruction::And ||
4487 Op0I->getOpcode() == Instruction::Or) {
4488 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4489 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4490 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004491 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004492 Op0I->getOperand(1)->getName()+".not");
4493 InsertNewInstBefore(NotY, I);
4494 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004495 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004496 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004497 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004498 }
4499 }
4500 }
4501 }
4502
4503
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004504 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004505 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4506 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4507 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004508 return new ICmpInst(ICI->getInversePredicate(),
4509 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004510
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004511 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4512 return new FCmpInst(FCI->getInversePredicate(),
4513 FCI->getOperand(0), FCI->getOperand(1));
4514 }
4515
Nick Lewycky517e1f52008-05-31 19:01:33 +00004516 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4517 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4518 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4519 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4520 Instruction::CastOps Opcode = Op0C->getOpcode();
4521 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4522 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4523 Op0C->getDestTy())) {
4524 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4525 CI->getOpcode(), CI->getInversePredicate(),
4526 CI->getOperand(0), CI->getOperand(1)), I);
4527 NewCI->takeName(CI);
4528 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4529 }
4530 }
4531 }
4532 }
4533 }
4534
Reid Spencere4d87aa2006-12-23 06:05:41 +00004535 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004536 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004537 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4538 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004539 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4540 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004541 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004542 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004543 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004544
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004545 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004546 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004547 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004548 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004549 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004550 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004551 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004552 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004553 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004554 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004555 // (X + C) ^ signbit -> (X + C + signbit)
4556 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004557 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004558
Chris Lattner7c4049c2004-01-12 19:35:11 +00004559 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004560 } else if (Op0I->getOpcode() == Instruction::Or) {
4561 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004562 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004563 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4564 // Anything in both C1 and C2 is known to be zero, remove it from
4565 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004566 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004567 NewRHS = ConstantExpr::getAnd(NewRHS,
4568 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004569 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004570 I.setOperand(0, Op0I->getOperand(0));
4571 I.setOperand(1, NewRHS);
4572 return &I;
4573 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004574 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004575 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004576 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004577
4578 // Try to fold constant and into select arguments.
4579 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004580 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004581 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004582 if (isa<PHINode>(Op0))
4583 if (Instruction *NV = FoldOpIntoPhi(I))
4584 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004585 }
4586
Chris Lattner8d969642003-03-10 23:06:50 +00004587 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004588 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004589 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004590
Chris Lattner8d969642003-03-10 23:06:50 +00004591 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004592 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004593 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004594
Chris Lattner318bf792007-03-18 22:51:34 +00004595
4596 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4597 if (Op1I) {
4598 Value *A, *B;
4599 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4600 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004601 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004602 I.swapOperands();
4603 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004604 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004605 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004606 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004607 }
Chris Lattner318bf792007-03-18 22:51:34 +00004608 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4609 if (Op0 == A) // A^(A^B) == B
4610 return ReplaceInstUsesWith(I, B);
4611 else if (Op0 == B) // A^(B^A) == B
4612 return ReplaceInstUsesWith(I, A);
4613 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004614 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004615 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004616 std::swap(A, B);
4617 }
Chris Lattner318bf792007-03-18 22:51:34 +00004618 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004619 I.swapOperands(); // Simplified below.
4620 std::swap(Op0, Op1);
4621 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004622 }
Chris Lattner318bf792007-03-18 22:51:34 +00004623 }
4624
4625 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4626 if (Op0I) {
4627 Value *A, *B;
4628 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4629 if (A == Op1) // (B|A)^B == (A|B)^B
4630 std::swap(A, B);
4631 if (B == Op1) { // (A|B)^B == A & ~B
4632 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004633 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4634 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004635 }
Chris Lattner318bf792007-03-18 22:51:34 +00004636 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4637 if (Op1 == A) // (A^B)^A == B
4638 return ReplaceInstUsesWith(I, B);
4639 else if (Op1 == B) // (B^A)^A == B
4640 return ReplaceInstUsesWith(I, A);
4641 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4642 if (A == Op1) // (A&B)^A -> (B&A)^A
4643 std::swap(A, B);
4644 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004645 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004646 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004647 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4648 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004649 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004650 }
Chris Lattner318bf792007-03-18 22:51:34 +00004651 }
4652
4653 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4654 if (Op0I && Op1I && Op0I->isShift() &&
4655 Op0I->getOpcode() == Op1I->getOpcode() &&
4656 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4657 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4658 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004659 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004660 Op1I->getOperand(0),
4661 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004662 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004663 Op1I->getOperand(1));
4664 }
4665
4666 if (Op0I && Op1I) {
4667 Value *A, *B, *C, *D;
4668 // (A & B)^(A | B) -> A ^ B
4669 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4670 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4671 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004672 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004673 }
4674 // (A | B)^(A & B) -> A ^ B
4675 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4676 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4677 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004678 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004679 }
4680
4681 // (A & B)^(C & D)
4682 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4683 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4684 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4685 // (X & Y)^(X & Y) -> (Y^Z) & X
4686 Value *X = 0, *Y = 0, *Z = 0;
4687 if (A == C)
4688 X = A, Y = B, Z = D;
4689 else if (A == D)
4690 X = A, Y = B, Z = C;
4691 else if (B == C)
4692 X = B, Y = A, Z = D;
4693 else if (B == D)
4694 X = B, Y = A, Z = C;
4695
4696 if (X) {
4697 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004698 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4699 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004700 }
4701 }
4702 }
4703
Reid Spencere4d87aa2006-12-23 06:05:41 +00004704 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4705 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4706 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004707 return R;
4708
Chris Lattner6fc205f2006-05-05 06:39:07 +00004709 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004710 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004711 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004712 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4713 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004714 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004715 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004716 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4717 I.getType(), TD) &&
4718 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4719 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004720 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004721 Op1C->getOperand(0),
4722 I.getName());
4723 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004724 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004725 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004726 }
Chris Lattner99c65742007-10-24 05:38:08 +00004727 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00004728
Chris Lattner7e708292002-06-25 16:13:24 +00004729 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004730}
4731
Chris Lattnera96879a2004-09-29 17:40:11 +00004732/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4733/// overflowed for this type.
4734static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004735 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004736 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004737
Reid Spencere4e40032007-03-21 23:19:50 +00004738 if (IsSigned)
4739 if (In2->getValue().isNegative())
4740 return Result->getValue().sgt(In1->getValue());
4741 else
4742 return Result->getValue().slt(In1->getValue());
4743 else
4744 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004745}
4746
Dan Gohman1df3fd62008-09-10 23:30:57 +00004747/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
4748/// overflowed for this type.
4749static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4750 ConstantInt *In2, bool IsSigned = false) {
Dan Gohmanbcb37fd2008-09-11 18:53:02 +00004751 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohman1df3fd62008-09-10 23:30:57 +00004752
4753 if (IsSigned)
4754 if (In2->getValue().isNegative())
4755 return Result->getValue().slt(In1->getValue());
4756 else
4757 return Result->getValue().sgt(In1->getValue());
4758 else
4759 return Result->getValue().ugt(In1->getValue());
4760}
4761
Chris Lattner574da9b2005-01-13 20:14:25 +00004762/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4763/// code necessary to compute the offset from the base pointer (without adding
4764/// in the base pointer). Return the result as a signed integer of intptr size.
4765static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4766 TargetData &TD = IC.getTargetData();
4767 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004768 const Type *IntPtrTy = TD.getIntPtrType();
4769 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004770
4771 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004772 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004773 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004774
Gabor Greif177dd3f2008-06-12 21:37:33 +00004775 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4776 ++i, ++GTI) {
4777 Value *Op = *i;
Duncan Sands514ab342007-11-01 20:53:16 +00004778 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004779 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4780 if (OpC->isZero()) continue;
4781
4782 // Handle a struct index, which adds its field offset to the pointer.
4783 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4784 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4785
4786 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4787 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004788 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004789 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004790 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004791 ConstantInt::get(IntPtrTy, Size),
4792 GEP->getName()+".offs"), I);
4793 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004794 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004795
4796 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4797 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4798 Scale = ConstantExpr::getMul(OC, Scale);
4799 if (Constant *RC = dyn_cast<Constant>(Result))
4800 Result = ConstantExpr::getAdd(RC, Scale);
4801 else {
4802 // Emit an add instruction.
4803 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004804 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004805 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004806 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004807 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004808 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004809 // Convert to correct type.
4810 if (Op->getType() != IntPtrTy) {
4811 if (Constant *OpC = dyn_cast<Constant>(Op))
4812 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4813 else
4814 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4815 Op->getName()+".c"), I);
4816 }
4817 if (Size != 1) {
4818 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4819 if (Constant *OpC = dyn_cast<Constant>(Op))
4820 Op = ConstantExpr::getMul(OpC, Scale);
4821 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004822 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004823 GEP->getName()+".idx"), I);
4824 }
4825
4826 // Emit an add instruction.
4827 if (isa<Constant>(Op) && isa<Constant>(Result))
4828 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4829 cast<Constant>(Result));
4830 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004831 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004832 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004833 }
4834 return Result;
4835}
4836
Chris Lattner10c0d912008-04-22 02:53:33 +00004837
4838/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4839/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4840/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4841/// complex, and scales are involved. The above expression would also be legal
4842/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4843/// later form is less amenable to optimization though, and we are allowed to
4844/// generate the first by knowing that pointer arithmetic doesn't overflow.
4845///
4846/// If we can't emit an optimized form for this expression, this returns null.
4847///
4848static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4849 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00004850 TargetData &TD = IC.getTargetData();
4851 gep_type_iterator GTI = gep_type_begin(GEP);
4852
4853 // Check to see if this gep only has a single variable index. If so, and if
4854 // any constant indices are a multiple of its scale, then we can compute this
4855 // in terms of the scale of the variable index. For example, if the GEP
4856 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4857 // because the expression will cross zero at the same point.
4858 unsigned i, e = GEP->getNumOperands();
4859 int64_t Offset = 0;
4860 for (i = 1; i != e; ++i, ++GTI) {
4861 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4862 // Compute the aggregate offset of constant indices.
4863 if (CI->isZero()) continue;
4864
4865 // Handle a struct index, which adds its field offset to the pointer.
4866 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4867 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4868 } else {
4869 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4870 Offset += Size*CI->getSExtValue();
4871 }
4872 } else {
4873 // Found our variable index.
4874 break;
4875 }
4876 }
4877
4878 // If there are no variable indices, we must have a constant offset, just
4879 // evaluate it the general way.
4880 if (i == e) return 0;
4881
4882 Value *VariableIdx = GEP->getOperand(i);
4883 // Determine the scale factor of the variable element. For example, this is
4884 // 4 if the variable index is into an array of i32.
4885 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4886
4887 // Verify that there are no other variable indices. If so, emit the hard way.
4888 for (++i, ++GTI; i != e; ++i, ++GTI) {
4889 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4890 if (!CI) return 0;
4891
4892 // Compute the aggregate offset of constant indices.
4893 if (CI->isZero()) continue;
4894
4895 // Handle a struct index, which adds its field offset to the pointer.
4896 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4897 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4898 } else {
4899 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4900 Offset += Size*CI->getSExtValue();
4901 }
4902 }
4903
4904 // Okay, we know we have a single variable index, which must be a
4905 // pointer/array/vector index. If there is no offset, life is simple, return
4906 // the index.
4907 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4908 if (Offset == 0) {
4909 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4910 // we don't need to bother extending: the extension won't affect where the
4911 // computation crosses zero.
4912 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4913 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4914 VariableIdx->getNameStart(), &I);
4915 return VariableIdx;
4916 }
4917
4918 // Otherwise, there is an index. The computation we will do will be modulo
4919 // the pointer size, so get it.
4920 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4921
4922 Offset &= PtrSizeMask;
4923 VariableScale &= PtrSizeMask;
4924
4925 // To do this transformation, any constant index must be a multiple of the
4926 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4927 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4928 // multiple of the variable scale.
4929 int64_t NewOffs = Offset / (int64_t)VariableScale;
4930 if (Offset != NewOffs*(int64_t)VariableScale)
4931 return 0;
4932
4933 // Okay, we can do this evaluation. Start by converting the index to intptr.
4934 const Type *IntPtrTy = TD.getIntPtrType();
4935 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004936 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00004937 true /*SExt*/,
4938 VariableIdx->getNameStart(), &I);
4939 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004940 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00004941}
4942
4943
Reid Spencere4d87aa2006-12-23 06:05:41 +00004944/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004945/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004946Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4947 ICmpInst::Predicate Cond,
4948 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004949 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004950
Chris Lattner10c0d912008-04-22 02:53:33 +00004951 // Look through bitcasts.
4952 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4953 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004954
Chris Lattner574da9b2005-01-13 20:14:25 +00004955 Value *PtrBase = GEPLHS->getOperand(0);
4956 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004957 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00004958 // This transformation (ignoring the base and scales) is valid because we
4959 // know pointers can't overflow. See if we can output an optimized form.
4960 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4961
4962 // If not, synthesize the offset the hard way.
4963 if (Offset == 0)
4964 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00004965 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4966 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004967 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004968 // If the base pointers are different, but the indices are the same, just
4969 // compare the base pointer.
4970 if (PtrBase != GEPRHS->getOperand(0)) {
4971 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004972 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004973 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004974 if (IndicesTheSame)
4975 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4976 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4977 IndicesTheSame = false;
4978 break;
4979 }
4980
4981 // If all indices are the same, just compare the base pointers.
4982 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004983 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4984 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004985
4986 // Otherwise, the base pointers are different and the indices are
4987 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004988 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004989 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004990
Chris Lattnere9d782b2005-01-13 22:25:21 +00004991 // If one of the GEPs has all zero indices, recurse.
4992 bool AllZeros = true;
4993 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4994 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4995 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4996 AllZeros = false;
4997 break;
4998 }
4999 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005000 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5001 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005002
5003 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005004 AllZeros = true;
5005 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5006 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5007 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5008 AllZeros = false;
5009 break;
5010 }
5011 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005012 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005013
Chris Lattner4401c9c2005-01-14 00:20:05 +00005014 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5015 // If the GEPs only differ by one index, compare it.
5016 unsigned NumDifferences = 0; // Keep track of # differences.
5017 unsigned DiffOperand = 0; // The operand that differs.
5018 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5019 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005020 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5021 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005022 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005023 NumDifferences = 2;
5024 break;
5025 } else {
5026 if (NumDifferences++) break;
5027 DiffOperand = i;
5028 }
5029 }
5030
5031 if (NumDifferences == 0) // SAME GEP?
5032 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005033 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005034 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005035
Chris Lattner4401c9c2005-01-14 00:20:05 +00005036 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005037 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5038 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005039 // Make sure we do a signed comparison here.
5040 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005041 }
5042 }
5043
Reid Spencere4d87aa2006-12-23 06:05:41 +00005044 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005045 // the result to fold to a constant!
5046 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5047 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5048 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5049 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5050 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005051 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005052 }
5053 }
5054 return 0;
5055}
5056
Chris Lattnera5406232008-05-19 20:18:56 +00005057/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5058///
5059Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5060 Instruction *LHSI,
5061 Constant *RHSC) {
5062 if (!isa<ConstantFP>(RHSC)) return 0;
5063 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5064
5065 // Get the width of the mantissa. We don't want to hack on conversions that
5066 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005067 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005068 if (MantissaWidth == -1) return 0; // Unknown.
5069
5070 // Check to see that the input is converted from an integer type that is small
5071 // enough that preserves all bits. TODO: check here for "known" sign bits.
5072 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5073 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5074
5075 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5076 if (isa<UIToFPInst>(LHSI))
5077 ++InputSize;
5078
5079 // If the conversion would lose info, don't hack on this.
5080 if ((int)InputSize > MantissaWidth)
5081 return 0;
5082
5083 // Otherwise, we can potentially simplify the comparison. We know that it
5084 // will always come through as an integer value and we know the constant is
5085 // not a NAN (it would have been previously simplified).
5086 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5087
5088 ICmpInst::Predicate Pred;
5089 switch (I.getPredicate()) {
5090 default: assert(0 && "Unexpected predicate!");
5091 case FCmpInst::FCMP_UEQ:
5092 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5093 case FCmpInst::FCMP_UGT:
5094 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5095 case FCmpInst::FCMP_UGE:
5096 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5097 case FCmpInst::FCMP_ULT:
5098 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5099 case FCmpInst::FCMP_ULE:
5100 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5101 case FCmpInst::FCMP_UNE:
5102 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5103 case FCmpInst::FCMP_ORD:
5104 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5105 case FCmpInst::FCMP_UNO:
5106 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5107 }
5108
5109 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5110
5111 // Now we know that the APFloat is a normal number, zero or inf.
5112
Chris Lattner85162782008-05-20 03:50:52 +00005113 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005114 // comparing an i8 to 300.0.
5115 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5116
5117 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5118 // and large values.
5119 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5120 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5121 APFloat::rmNearestTiesToEven);
5122 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00005123 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5124 Pred == ICmpInst::ICMP_SLE)
Chris Lattnera5406232008-05-19 20:18:56 +00005125 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5126 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5127 }
5128
5129 // See if the RHS value is < SignedMin.
5130 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5131 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5132 APFloat::rmNearestTiesToEven);
5133 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00005134 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5135 Pred == ICmpInst::ICMP_SGE)
Chris Lattnera5406232008-05-19 20:18:56 +00005136 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5137 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5138 }
5139
5140 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5141 // it may still be fractional. See if it is fractional by casting the FP
5142 // value to the integer value and back, checking for equality. Don't do this
5143 // for zero, because -0.0 is not fractional.
5144 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5145 if (!RHS.isZero() &&
5146 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5147 // If we had a comparison against a fractional value, we have to adjust
5148 // the compare predicate and sometimes the value. RHSC is rounded towards
5149 // zero at this point.
5150 switch (Pred) {
5151 default: assert(0 && "Unexpected integer comparison!");
5152 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5153 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5154 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5155 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5156 case ICmpInst::ICMP_SLE:
5157 // (float)int <= 4.4 --> int <= 4
5158 // (float)int <= -4.4 --> int < -4
5159 if (RHS.isNegative())
5160 Pred = ICmpInst::ICMP_SLT;
5161 break;
5162 case ICmpInst::ICMP_SLT:
5163 // (float)int < -4.4 --> int < -4
5164 // (float)int < 4.4 --> int <= 4
5165 if (!RHS.isNegative())
5166 Pred = ICmpInst::ICMP_SLE;
5167 break;
5168 case ICmpInst::ICMP_SGT:
5169 // (float)int > 4.4 --> int > 4
5170 // (float)int > -4.4 --> int >= -4
5171 if (RHS.isNegative())
5172 Pred = ICmpInst::ICMP_SGE;
5173 break;
5174 case ICmpInst::ICMP_SGE:
5175 // (float)int >= -4.4 --> int >= -4
5176 // (float)int >= 4.4 --> int > 4
5177 if (!RHS.isNegative())
5178 Pred = ICmpInst::ICMP_SGT;
5179 break;
5180 }
5181 }
5182
5183 // Lower this FP comparison into an appropriate integer version of the
5184 // comparison.
5185 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5186}
5187
Reid Spencere4d87aa2006-12-23 06:05:41 +00005188Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5189 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005190 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005191
Chris Lattner58e97462007-01-14 19:42:17 +00005192 // Fold trivial predicates.
5193 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5194 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5195 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5196 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5197
5198 // Simplify 'fcmp pred X, X'
5199 if (Op0 == Op1) {
5200 switch (I.getPredicate()) {
5201 default: assert(0 && "Unknown predicate!");
5202 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5203 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5204 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5205 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5206 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5207 case FCmpInst::FCMP_OLT: // True if ordered and less than
5208 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5209 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5210
5211 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5212 case FCmpInst::FCMP_ULT: // True if unordered or less than
5213 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5214 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5215 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5216 I.setPredicate(FCmpInst::FCMP_UNO);
5217 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5218 return &I;
5219
5220 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5221 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5222 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5223 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5224 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5225 I.setPredicate(FCmpInst::FCMP_ORD);
5226 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5227 return &I;
5228 }
5229 }
5230
Reid Spencere4d87aa2006-12-23 06:05:41 +00005231 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005232 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005233
Reid Spencere4d87aa2006-12-23 06:05:41 +00005234 // Handle fcmp with constant RHS
5235 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005236 // If the constant is a nan, see if we can fold the comparison based on it.
5237 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5238 if (CFP->getValueAPF().isNaN()) {
5239 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5240 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005241 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5242 "Comparison must be either ordered or unordered!");
5243 // True if unordered.
5244 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005245 }
5246 }
5247
Reid Spencere4d87aa2006-12-23 06:05:41 +00005248 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5249 switch (LHSI->getOpcode()) {
5250 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005251 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5252 // block. If in the same block, we're encouraging jump threading. If
5253 // not, we are just pessimizing the code by making an i1 phi.
5254 if (LHSI->getParent() == I.getParent())
5255 if (Instruction *NV = FoldOpIntoPhi(I))
5256 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005257 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005258 case Instruction::SIToFP:
5259 case Instruction::UIToFP:
5260 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5261 return NV;
5262 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005263 case Instruction::Select:
5264 // If either operand of the select is a constant, we can fold the
5265 // comparison into the select arms, which will cause one to be
5266 // constant folded and the select turned into a bitwise or.
5267 Value *Op1 = 0, *Op2 = 0;
5268 if (LHSI->hasOneUse()) {
5269 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5270 // Fold the known value into the constant operand.
5271 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5272 // Insert a new FCmp of the other select operand.
5273 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5274 LHSI->getOperand(2), RHSC,
5275 I.getName()), I);
5276 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5277 // Fold the known value into the constant operand.
5278 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5279 // Insert a new FCmp of the other select operand.
5280 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5281 LHSI->getOperand(1), RHSC,
5282 I.getName()), I);
5283 }
5284 }
5285
5286 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005287 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005288 break;
5289 }
5290 }
5291
5292 return Changed ? &I : 0;
5293}
5294
5295Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5296 bool Changed = SimplifyCompare(I);
5297 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5298 const Type *Ty = Op0->getType();
5299
5300 // icmp X, X
5301 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005302 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005303 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005304
5305 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005306 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005307
Reid Spencere4d87aa2006-12-23 06:05:41 +00005308 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005309 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005310 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5311 isa<ConstantPointerNull>(Op0)) &&
5312 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005313 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005314 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005315 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005316
Reid Spencere4d87aa2006-12-23 06:05:41 +00005317 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005318 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005319 switch (I.getPredicate()) {
5320 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005321 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005322 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005323 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005324 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005325 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005326 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005327 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005328
Reid Spencere4d87aa2006-12-23 06:05:41 +00005329 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005330 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005331 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005332 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005333 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005334 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005335 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005336 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005337 case ICmpInst::ICMP_SGT:
5338 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005339 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005340 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5341 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5342 InsertNewInstBefore(Not, I);
5343 return BinaryOperator::CreateAnd(Not, Op0);
5344 }
5345 case ICmpInst::ICMP_UGE:
5346 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5347 // FALL THROUGH
5348 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005349 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005350 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005351 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005352 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005353 case ICmpInst::ICMP_SGE:
5354 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5355 // FALL THROUGH
5356 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5357 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5358 InsertNewInstBefore(Not, I);
5359 return BinaryOperator::CreateOr(Not, Op0);
5360 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005361 }
Chris Lattner8b170942002-08-09 23:47:40 +00005362 }
5363
Dan Gohman81b28ce2008-09-16 18:46:06 +00005364 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005365 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerf2991842008-07-11 04:09:09 +00005366 Value *A, *B;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005367
Chris Lattnerb6566012008-01-05 01:18:20 +00005368 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5369 if (I.isEquality() && CI->isNullValue() &&
5370 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5371 // (icmp cond A B) if cond is equality
5372 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005373 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005374
Dan Gohman81b28ce2008-09-16 18:46:06 +00005375 // If we have an icmp le or icmp ge instruction, turn it into the
5376 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5377 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005378 switch (I.getPredicate()) {
5379 default: break;
5380 case ICmpInst::ICMP_ULE:
5381 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5382 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5383 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5384 case ICmpInst::ICMP_SLE:
5385 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5386 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5387 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5388 case ICmpInst::ICMP_UGE:
5389 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5390 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5391 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5392 case ICmpInst::ICMP_SGE:
5393 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5394 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5395 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5396 }
5397
Chris Lattner183661e2008-07-11 05:40:05 +00005398 // See if we can fold the comparison based on range information we can get
5399 // by checking whether bits are known to be zero or one in the input.
5400 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5401 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5402
5403 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005404 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005405 bool UnusedBit;
5406 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5407
Chris Lattner4241e4d2007-07-15 20:54:51 +00005408 if (SimplifyDemandedBits(Op0,
5409 isSignBit ? APInt::getSignBit(BitWidth)
5410 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005411 KnownZero, KnownOne, 0))
5412 return &I;
5413
5414 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00005415 // in. Compute the Min, Max and RHS values based on the known bits. For the
5416 // EQ and NE we use unsigned values.
5417 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner84dff672008-07-11 05:08:55 +00005418 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5419 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5420 else
5421 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5422
Chris Lattner183661e2008-07-11 05:40:05 +00005423 // If Min and Max are known to be the same, then SimplifyDemandedBits
5424 // figured out that the LHS is a constant. Just constant fold this now so
5425 // that code below can assume that Min != Max.
5426 if (Min == Max)
5427 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5428 ConstantInt::get(Min),
5429 CI));
5430
5431 // Based on the range information we know about the LHS, see if we can
5432 // simplify this comparison. For example, (x&4) < 8 is always true.
5433 const APInt &RHSVal = CI->getValue();
Chris Lattner84dff672008-07-11 05:08:55 +00005434 switch (I.getPredicate()) { // LE/GE have been folded already.
5435 default: assert(0 && "Unknown icmp opcode!");
5436 case ICmpInst::ICMP_EQ:
5437 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5438 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5439 break;
5440 case ICmpInst::ICMP_NE:
5441 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5442 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5443 break;
5444 case ICmpInst::ICMP_ULT:
Chris Lattner183661e2008-07-11 05:40:05 +00005445 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005446 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005447 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005448 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005449 if (RHSVal == Max) // A <u MAX -> A != MAX
5450 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5451 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5452 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5453
5454 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5455 if (CI->isMinValue(true))
5456 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5457 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005458 break;
5459 case ICmpInst::ICMP_UGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005460 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005461 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005462 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005463 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005464
5465 if (RHSVal == Min) // A >u MIN -> A != MIN
5466 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5467 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5468 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5469
5470 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5471 if (CI->isMaxValue(true))
5472 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5473 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005474 break;
5475 case ICmpInst::ICMP_SLT:
Chris Lattner183661e2008-07-11 05:40:05 +00005476 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005477 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerd01bee72008-07-11 06:40:29 +00005478 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005479 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005480 if (RHSVal == Max) // A <s MAX -> A != MAX
5481 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattnera8ff4a82008-07-11 06:36:01 +00005482 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattnerf9685ac2008-07-11 06:38:16 +00005483 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005484 break;
5485 case ICmpInst::ICMP_SGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005486 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005487 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005488 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005489 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005490
5491 if (RHSVal == Min) // A >s MIN -> A != MIN
5492 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5493 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5494 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005495 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005496 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00005497 }
5498
5499 // Test if the ICmpInst instruction is used exclusively by a select as
5500 // part of a minimum or maximum operation. If so, refrain from doing
5501 // any other folding. This helps out other analyses which understand
5502 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5503 // and CodeGen. And in this case, at least one of the comparison
5504 // operands has at least one user besides the compare (the select),
5505 // which would often largely negate the benefit of folding anyway.
5506 if (I.hasOneUse())
5507 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5508 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5509 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5510 return 0;
5511
5512 // See if we are doing a comparison between a constant and an instruction that
5513 // can be folded into the comparison.
5514 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005515 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005516 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005517 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005518 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005519 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5520 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005521 }
5522
Chris Lattner01deb9d2007-04-03 17:43:25 +00005523 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005524 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5525 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5526 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005527 case Instruction::GetElementPtr:
5528 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005529 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005530 bool isAllZeros = true;
5531 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5532 if (!isa<Constant>(LHSI->getOperand(i)) ||
5533 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5534 isAllZeros = false;
5535 break;
5536 }
5537 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005538 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005539 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5540 }
5541 break;
5542
Chris Lattner6970b662005-04-23 15:31:55 +00005543 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005544 // Only fold icmp into the PHI if the phi and fcmp are in the same
5545 // block. If in the same block, we're encouraging jump threading. If
5546 // not, we are just pessimizing the code by making an i1 phi.
5547 if (LHSI->getParent() == I.getParent())
5548 if (Instruction *NV = FoldOpIntoPhi(I))
5549 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00005550 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005551 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005552 // If either operand of the select is a constant, we can fold the
5553 // comparison into the select arms, which will cause one to be
5554 // constant folded and the select turned into a bitwise or.
5555 Value *Op1 = 0, *Op2 = 0;
5556 if (LHSI->hasOneUse()) {
5557 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5558 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005559 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5560 // Insert a new ICmp of the other select operand.
5561 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5562 LHSI->getOperand(2), RHSC,
5563 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005564 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5565 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005566 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5567 // Insert a new ICmp of the other select operand.
5568 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5569 LHSI->getOperand(1), RHSC,
5570 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005571 }
5572 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005573
Chris Lattner6970b662005-04-23 15:31:55 +00005574 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005575 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005576 break;
5577 }
Chris Lattner4802d902007-04-06 18:57:34 +00005578 case Instruction::Malloc:
5579 // If we have (malloc != null), and if the malloc has a single use, we
5580 // can assume it is successful and remove the malloc.
5581 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5582 AddToWorkList(LHSI);
5583 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005584 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005585 }
5586 break;
5587 }
Chris Lattner6970b662005-04-23 15:31:55 +00005588 }
5589
Reid Spencere4d87aa2006-12-23 06:05:41 +00005590 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005591 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005592 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005593 return NI;
5594 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005595 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5596 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005597 return NI;
5598
Reid Spencere4d87aa2006-12-23 06:05:41 +00005599 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005600 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5601 // now.
5602 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5603 if (isa<PointerType>(Op0->getType()) &&
5604 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005605 // We keep moving the cast from the left operand over to the right
5606 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005607 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005608
Chris Lattner57d86372007-01-06 01:45:59 +00005609 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5610 // so eliminate it as well.
5611 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5612 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005613
Chris Lattnerde90b762003-11-03 04:25:02 +00005614 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005615 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005616 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005617 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005618 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005619 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005620 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005621 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005622 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005623 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005624 }
Chris Lattner57d86372007-01-06 01:45:59 +00005625 }
5626
5627 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005628 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005629 // This comes up when you have code like
5630 // int X = A < B;
5631 // if (X) ...
5632 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005633 // with a constant or another cast from the same type.
5634 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005635 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005636 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005637 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005638
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005639 // See if it's the same type of instruction on the left and right.
5640 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5641 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00005642 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5643 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5644 I.isEquality()) {
Nick Lewycky23c04302008-09-03 06:24:21 +00005645 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005646 default: break;
5647 case Instruction::Add:
5648 case Instruction::Sub:
5649 case Instruction::Xor:
Nick Lewycky5d52c452008-08-21 05:56:10 +00005650 // a+x icmp eq/ne b+x --> a icmp b
5651 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5652 Op1I->getOperand(0));
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005653 break;
5654 case Instruction::Mul:
Nick Lewycky5d52c452008-08-21 05:56:10 +00005655 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5656 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5657 // Mask = -1 >> count-trailing-zeros(Cst).
5658 if (!CI->isZero() && !CI->isOne()) {
5659 const APInt &AP = CI->getValue();
5660 ConstantInt *Mask = ConstantInt::get(
5661 APInt::getLowBitsSet(AP.getBitWidth(),
5662 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005663 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00005664 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
5665 Mask);
5666 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
5667 Mask);
5668 InsertNewInstBefore(And1, I);
5669 InsertNewInstBefore(And2, I);
5670 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005671 }
5672 }
5673 break;
5674 }
5675 }
5676 }
5677 }
5678
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005679 // ~x < ~y --> y < x
5680 { Value *A, *B;
5681 if (match(Op0, m_Not(m_Value(A))) &&
5682 match(Op1, m_Not(m_Value(B))))
5683 return new ICmpInst(I.getPredicate(), B, A);
5684 }
5685
Chris Lattner65b72ba2006-09-18 04:22:48 +00005686 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005687 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005688
5689 // -x == -y --> x == y
5690 if (match(Op0, m_Neg(m_Value(A))) &&
5691 match(Op1, m_Neg(m_Value(B))))
5692 return new ICmpInst(I.getPredicate(), A, B);
5693
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005694 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5695 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5696 Value *OtherVal = A == Op1 ? B : A;
5697 return new ICmpInst(I.getPredicate(), OtherVal,
5698 Constant::getNullValue(A->getType()));
5699 }
5700
5701 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5702 // A^c1 == C^c2 --> A == C^(c1^c2)
5703 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5704 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5705 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005706 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005707 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005708 return new ICmpInst(I.getPredicate(), A,
5709 InsertNewInstBefore(Xor, I));
5710 }
5711
5712 // A^B == A^D -> B == D
5713 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5714 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5715 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5716 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5717 }
5718 }
5719
5720 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5721 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005722 // A == (A^B) -> B == 0
5723 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005724 return new ICmpInst(I.getPredicate(), OtherVal,
5725 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005726 }
5727 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005728 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005729 return new ICmpInst(I.getPredicate(), B,
5730 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005731 }
5732 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005733 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005734 return new ICmpInst(I.getPredicate(), B,
5735 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005736 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005737
Chris Lattner9c2328e2006-11-14 06:06:06 +00005738 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5739 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5740 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5741 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5742 Value *X = 0, *Y = 0, *Z = 0;
5743
5744 if (A == C) {
5745 X = B; Y = D; Z = A;
5746 } else if (A == D) {
5747 X = B; Y = C; Z = A;
5748 } else if (B == C) {
5749 X = A; Y = D; Z = B;
5750 } else if (B == D) {
5751 X = A; Y = C; Z = B;
5752 }
5753
5754 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005755 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5756 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005757 I.setOperand(0, Op1);
5758 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5759 return &I;
5760 }
5761 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005762 }
Chris Lattner7e708292002-06-25 16:13:24 +00005763 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005764}
5765
Chris Lattner562ef782007-06-20 23:46:26 +00005766
5767/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5768/// and CmpRHS are both known to be integer constants.
5769Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5770 ConstantInt *DivRHS) {
5771 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5772 const APInt &CmpRHSV = CmpRHS->getValue();
5773
5774 // FIXME: If the operand types don't match the type of the divide
5775 // then don't attempt this transform. The code below doesn't have the
5776 // logic to deal with a signed divide and an unsigned compare (and
5777 // vice versa). This is because (x /s C1) <s C2 produces different
5778 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5779 // (x /u C1) <u C2. Simply casting the operands and result won't
5780 // work. :( The if statement below tests that condition and bails
5781 // if it finds it.
5782 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5783 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5784 return 0;
5785 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005786 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00005787 if (DivIsSigned && DivRHS->isAllOnesValue())
5788 return 0; // The overflow computation also screws up here
5789 if (DivRHS->isOne())
5790 return 0; // Not worth bothering, and eliminates some funny cases
5791 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00005792
5793 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5794 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5795 // C2 (CI). By solving for X we can turn this into a range check
5796 // instead of computing a divide.
5797 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5798
5799 // Determine if the product overflows by seeing if the product is
5800 // not equal to the divide. Make sure we do the same kind of divide
5801 // as in the LHS instruction that we're folding.
5802 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5803 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5804
5805 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005806 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005807
Chris Lattner1dbfd482007-06-21 18:11:19 +00005808 // Figure out the interval that is being checked. For example, a comparison
5809 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5810 // Compute this interval based on the constants involved and the signedness of
5811 // the compare/divide. This computes a half-open interval, keeping track of
5812 // whether either value in the interval overflows. After analysis each
5813 // overflow variable is set to 0 if it's corresponding bound variable is valid
5814 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5815 int LoOverflow = 0, HiOverflow = 0;
5816 ConstantInt *LoBound = 0, *HiBound = 0;
5817
Chris Lattner562ef782007-06-20 23:46:26 +00005818 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005819 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005820 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005821 HiOverflow = LoOverflow = ProdOV;
5822 if (!HiOverflow)
5823 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005824 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005825 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005826 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005827 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5828 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005829 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005830 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5831 HiOverflow = LoOverflow = ProdOV;
5832 if (!HiOverflow)
5833 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005834 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005835 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005836 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00005837 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
5838 if (!LoOverflow) {
5839 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5840 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
5841 true) ? -1 : 0;
5842 }
Chris Lattner562ef782007-06-20 23:46:26 +00005843 }
Dan Gohman76491272008-02-13 22:09:18 +00005844 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005845 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005846 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005847 LoBound = AddOne(DivRHS);
5848 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005849 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5850 HiOverflow = 1; // [INTMIN+1, overflow)
5851 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5852 }
Dan Gohman76491272008-02-13 22:09:18 +00005853 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005854 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnera6321b42008-10-11 22:55:00 +00005855 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005856 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005857 if (!LoOverflow)
Chris Lattnera6321b42008-10-11 22:55:00 +00005858 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005859 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00005860 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
5861 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00005862 if (!HiOverflow)
5863 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005864 }
5865
Chris Lattner1dbfd482007-06-21 18:11:19 +00005866 // Dividing by a negative swaps the condition. LT <-> GT
5867 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005868 }
5869
5870 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005871 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005872 default: assert(0 && "Unhandled icmp opcode!");
5873 case ICmpInst::ICMP_EQ:
5874 if (LoOverflow && HiOverflow)
5875 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5876 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005877 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005878 ICmpInst::ICMP_UGE, X, LoBound);
5879 else if (LoOverflow)
5880 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5881 ICmpInst::ICMP_ULT, X, HiBound);
5882 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005883 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005884 case ICmpInst::ICMP_NE:
5885 if (LoOverflow && HiOverflow)
5886 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5887 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005888 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005889 ICmpInst::ICMP_ULT, X, LoBound);
5890 else if (LoOverflow)
5891 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5892 ICmpInst::ICMP_UGE, X, HiBound);
5893 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005894 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005895 case ICmpInst::ICMP_ULT:
5896 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005897 if (LoOverflow == +1) // Low bound is greater than input range.
5898 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5899 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005900 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005901 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005902 case ICmpInst::ICMP_UGT:
5903 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005904 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005905 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005906 else if (HiOverflow == -1) // High bound less than input range.
5907 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5908 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005909 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5910 else
5911 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5912 }
5913}
5914
5915
Chris Lattner01deb9d2007-04-03 17:43:25 +00005916/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5917///
5918Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5919 Instruction *LHSI,
5920 ConstantInt *RHS) {
5921 const APInt &RHSV = RHS->getValue();
5922
5923 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005924 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005925 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5926 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5927 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005928 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5929 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005930 Value *CompareVal = LHSI->getOperand(0);
5931
5932 // If the sign bit of the XorCST is not set, there is no change to
5933 // the operation, just stop using the Xor.
5934 if (!XorCST->getValue().isNegative()) {
5935 ICI.setOperand(0, CompareVal);
5936 AddToWorkList(LHSI);
5937 return &ICI;
5938 }
5939
5940 // Was the old condition true if the operand is positive?
5941 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5942
5943 // If so, the new one isn't.
5944 isTrueIfPositive ^= true;
5945
5946 if (isTrueIfPositive)
5947 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5948 else
5949 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5950 }
5951 }
5952 break;
5953 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5954 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5955 LHSI->getOperand(0)->hasOneUse()) {
5956 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5957
5958 // If the LHS is an AND of a truncating cast, we can widen the
5959 // and/compare to be the input width without changing the value
5960 // produced, eliminating a cast.
5961 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5962 // We can do this transformation if either the AND constant does not
5963 // have its sign bit set or if it is an equality comparison.
5964 // Extending a relational comparison when we're checking the sign
5965 // bit would not work.
5966 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005967 (ICI.isEquality() ||
5968 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005969 uint32_t BitWidth =
5970 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5971 APInt NewCST = AndCST->getValue();
5972 NewCST.zext(BitWidth);
5973 APInt NewCI = RHSV;
5974 NewCI.zext(BitWidth);
5975 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005976 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00005977 ConstantInt::get(NewCST),LHSI->getName());
5978 InsertNewInstBefore(NewAnd, ICI);
5979 return new ICmpInst(ICI.getPredicate(), NewAnd,
5980 ConstantInt::get(NewCI));
5981 }
5982 }
5983
5984 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5985 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5986 // happens a LOT in code produced by the C front-end, for bitfield
5987 // access.
5988 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5989 if (Shift && !Shift->isShift())
5990 Shift = 0;
5991
5992 ConstantInt *ShAmt;
5993 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5994 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5995 const Type *AndTy = AndCST->getType(); // Type of the and.
5996
5997 // We can fold this as long as we can't shift unknown bits
5998 // into the mask. This can only happen with signed shift
5999 // rights, as they sign-extend.
6000 if (ShAmt) {
6001 bool CanFold = Shift->isLogicalShift();
6002 if (!CanFold) {
6003 // To test for the bad case of the signed shr, see if any
6004 // of the bits shifted in could be tested after the mask.
6005 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6006 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6007
6008 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6009 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6010 AndCST->getValue()) == 0)
6011 CanFold = true;
6012 }
6013
6014 if (CanFold) {
6015 Constant *NewCst;
6016 if (Shift->getOpcode() == Instruction::Shl)
6017 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6018 else
6019 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6020
6021 // Check to see if we are shifting out any of the bits being
6022 // compared.
6023 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6024 // If we shifted bits out, the fold is not going to work out.
6025 // As a special case, check to see if this means that the
6026 // result is always true or false now.
6027 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6028 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6029 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6030 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6031 } else {
6032 ICI.setOperand(1, NewCst);
6033 Constant *NewAndCST;
6034 if (Shift->getOpcode() == Instruction::Shl)
6035 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6036 else
6037 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6038 LHSI->setOperand(1, NewAndCST);
6039 LHSI->setOperand(0, Shift->getOperand(0));
6040 AddToWorkList(Shift); // Shift is dead.
6041 AddUsesToWorkList(ICI);
6042 return &ICI;
6043 }
6044 }
6045 }
6046
6047 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6048 // preferable because it allows the C<<Y expression to be hoisted out
6049 // of a loop if Y is invariant and X is not.
6050 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6051 ICI.isEquality() && !Shift->isArithmeticShift() &&
6052 isa<Instruction>(Shift->getOperand(0))) {
6053 // Compute C << Y.
6054 Value *NS;
6055 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006056 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006057 Shift->getOperand(1), "tmp");
6058 } else {
6059 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006060 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006061 Shift->getOperand(1), "tmp");
6062 }
6063 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6064
6065 // Compute X & (C << Y).
6066 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006067 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006068 InsertNewInstBefore(NewAnd, ICI);
6069
6070 ICI.setOperand(0, NewAnd);
6071 return &ICI;
6072 }
6073 }
6074 break;
6075
Chris Lattnera0141b92007-07-15 20:42:37 +00006076 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6077 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6078 if (!ShAmt) break;
6079
6080 uint32_t TypeBits = RHSV.getBitWidth();
6081
6082 // Check that the shift amount is in range. If not, don't perform
6083 // undefined shifts. When the shift is visited it will be
6084 // simplified.
6085 if (ShAmt->uge(TypeBits))
6086 break;
6087
6088 if (ICI.isEquality()) {
6089 // If we are comparing against bits always shifted out, the
6090 // comparison cannot succeed.
6091 Constant *Comp =
6092 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6093 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6094 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6095 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6096 return ReplaceInstUsesWith(ICI, Cst);
6097 }
6098
6099 if (LHSI->hasOneUse()) {
6100 // Otherwise strength reduce the shift into an and.
6101 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6102 Constant *Mask =
6103 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006104
Chris Lattnera0141b92007-07-15 20:42:37 +00006105 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006106 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006107 Mask, LHSI->getName()+".mask");
6108 Value *And = InsertNewInstBefore(AndI, ICI);
6109 return new ICmpInst(ICI.getPredicate(), And,
6110 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006111 }
6112 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006113
6114 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6115 bool TrueIfSigned = false;
6116 if (LHSI->hasOneUse() &&
6117 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6118 // (X << 31) <s 0 --> (X&1) != 0
6119 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6120 (TypeBits-ShAmt->getZExtValue()-1));
6121 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006122 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006123 Mask, LHSI->getName()+".mask");
6124 Value *And = InsertNewInstBefore(AndI, ICI);
6125
6126 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6127 And, Constant::getNullValue(And->getType()));
6128 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006129 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006130 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006131
6132 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006133 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006134 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006135 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006136 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006137
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006138 // Check that the shift amount is in range. If not, don't perform
6139 // undefined shifts. When the shift is visited it will be
6140 // simplified.
6141 uint32_t TypeBits = RHSV.getBitWidth();
6142 if (ShAmt->uge(TypeBits))
6143 break;
6144
6145 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006146
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006147 // If we are comparing against bits always shifted out, the
6148 // comparison cannot succeed.
6149 APInt Comp = RHSV << ShAmtVal;
6150 if (LHSI->getOpcode() == Instruction::LShr)
6151 Comp = Comp.lshr(ShAmtVal);
6152 else
6153 Comp = Comp.ashr(ShAmtVal);
6154
6155 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6156 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6157 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6158 return ReplaceInstUsesWith(ICI, Cst);
6159 }
6160
6161 // Otherwise, check to see if the bits shifted out are known to be zero.
6162 // If so, we can compare against the unshifted value:
6163 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006164 if (LHSI->hasOneUse() &&
6165 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006166 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6167 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6168 ConstantExpr::getShl(RHS, ShAmt));
6169 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006170
Evan Chengf30752c2008-04-23 00:38:06 +00006171 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006172 // Otherwise strength reduce the shift into an and.
6173 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6174 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006175
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006176 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006177 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006178 Mask, LHSI->getName()+".mask");
6179 Value *And = InsertNewInstBefore(AndI, ICI);
6180 return new ICmpInst(ICI.getPredicate(), And,
6181 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006182 }
6183 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006184 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006185
6186 case Instruction::SDiv:
6187 case Instruction::UDiv:
6188 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6189 // Fold this div into the comparison, producing a range check.
6190 // Determine, based on the divide type, what the range is being
6191 // checked. If there is an overflow on the low or high side, remember
6192 // it, otherwise compute the range [low, hi) bounding the new value.
6193 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006194 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6195 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6196 DivRHS))
6197 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006198 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006199
6200 case Instruction::Add:
6201 // Fold: icmp pred (add, X, C1), C2
6202
6203 if (!ICI.isEquality()) {
6204 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6205 if (!LHSC) break;
6206 const APInt &LHSV = LHSC->getValue();
6207
6208 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6209 .subtract(LHSV);
6210
6211 if (ICI.isSignedPredicate()) {
6212 if (CR.getLower().isSignBit()) {
6213 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6214 ConstantInt::get(CR.getUpper()));
6215 } else if (CR.getUpper().isSignBit()) {
6216 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6217 ConstantInt::get(CR.getLower()));
6218 }
6219 } else {
6220 if (CR.getLower().isMinValue()) {
6221 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6222 ConstantInt::get(CR.getUpper()));
6223 } else if (CR.getUpper().isMinValue()) {
6224 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6225 ConstantInt::get(CR.getLower()));
6226 }
6227 }
6228 }
6229 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006230 }
6231
6232 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6233 if (ICI.isEquality()) {
6234 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6235
6236 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6237 // the second operand is a constant, simplify a bit.
6238 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6239 switch (BO->getOpcode()) {
6240 case Instruction::SRem:
6241 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6242 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6243 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6244 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6245 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006246 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006247 BO->getName());
6248 InsertNewInstBefore(NewRem, ICI);
6249 return new ICmpInst(ICI.getPredicate(), NewRem,
6250 Constant::getNullValue(BO->getType()));
6251 }
6252 }
6253 break;
6254 case Instruction::Add:
6255 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6256 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6257 if (BO->hasOneUse())
6258 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6259 Subtract(RHS, BOp1C));
6260 } else if (RHSV == 0) {
6261 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6262 // efficiently invertible, or if the add has just this one use.
6263 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6264
6265 if (Value *NegVal = dyn_castNegVal(BOp1))
6266 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6267 else if (Value *NegVal = dyn_castNegVal(BOp0))
6268 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6269 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006270 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006271 InsertNewInstBefore(Neg, ICI);
6272 Neg->takeName(BO);
6273 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6274 }
6275 }
6276 break;
6277 case Instruction::Xor:
6278 // For the xor case, we can xor two constants together, eliminating
6279 // the explicit xor.
6280 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6281 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6282 ConstantExpr::getXor(RHS, BOC));
6283
6284 // FALLTHROUGH
6285 case Instruction::Sub:
6286 // Replace (([sub|xor] A, B) != 0) with (A != B)
6287 if (RHSV == 0)
6288 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6289 BO->getOperand(1));
6290 break;
6291
6292 case Instruction::Or:
6293 // If bits are being or'd in that are not present in the constant we
6294 // are comparing against, then the comparison could never succeed!
6295 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6296 Constant *NotCI = ConstantExpr::getNot(RHS);
6297 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6298 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6299 isICMP_NE));
6300 }
6301 break;
6302
6303 case Instruction::And:
6304 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6305 // If bits are being compared against that are and'd out, then the
6306 // comparison can never succeed!
6307 if ((RHSV & ~BOC->getValue()) != 0)
6308 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6309 isICMP_NE));
6310
6311 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6312 if (RHS == BOC && RHSV.isPowerOf2())
6313 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6314 ICmpInst::ICMP_NE, LHSI,
6315 Constant::getNullValue(RHS->getType()));
6316
6317 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006318 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006319 Value *X = BO->getOperand(0);
6320 Constant *Zero = Constant::getNullValue(X->getType());
6321 ICmpInst::Predicate pred = isICMP_NE ?
6322 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6323 return new ICmpInst(pred, X, Zero);
6324 }
6325
6326 // ((X & ~7) == 0) --> X < 8
6327 if (RHSV == 0 && isHighOnes(BOC)) {
6328 Value *X = BO->getOperand(0);
6329 Constant *NegX = ConstantExpr::getNeg(BOC);
6330 ICmpInst::Predicate pred = isICMP_NE ?
6331 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6332 return new ICmpInst(pred, X, NegX);
6333 }
6334 }
6335 default: break;
6336 }
6337 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6338 // Handle icmp {eq|ne} <intrinsic>, intcst.
6339 if (II->getIntrinsicID() == Intrinsic::bswap) {
6340 AddToWorkList(II);
6341 ICI.setOperand(0, II->getOperand(1));
6342 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6343 return &ICI;
6344 }
6345 }
6346 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006347 // If the LHS is a cast from an integral value of the same size,
6348 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006349 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6350 Value *CastOp = Cast->getOperand(0);
6351 const Type *SrcTy = CastOp->getType();
6352 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6353 if (SrcTy->isInteger() &&
6354 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6355 // If this is an unsigned comparison, try to make the comparison use
6356 // smaller constant values.
6357 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6358 // X u< 128 => X s> -1
6359 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6360 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6361 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6362 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6363 // X u> 127 => X s< 0
6364 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6365 Constant::getNullValue(SrcTy));
6366 }
6367 }
6368 }
6369 }
6370 return 0;
6371}
6372
6373/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6374/// We only handle extending casts so far.
6375///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006376Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6377 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006378 Value *LHSCIOp = LHSCI->getOperand(0);
6379 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006380 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006381 Value *RHSCIOp;
6382
Chris Lattner8c756c12007-05-05 22:41:33 +00006383 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6384 // integer type is the same size as the pointer type.
6385 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6386 getTargetData().getPointerSizeInBits() ==
6387 cast<IntegerType>(DestTy)->getBitWidth()) {
6388 Value *RHSOp = 0;
6389 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006390 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006391 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6392 RHSOp = RHSC->getOperand(0);
6393 // If the pointer types don't match, insert a bitcast.
6394 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006395 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006396 }
6397
6398 if (RHSOp)
6399 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6400 }
6401
6402 // The code below only handles extension cast instructions, so far.
6403 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006404 if (LHSCI->getOpcode() != Instruction::ZExt &&
6405 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006406 return 0;
6407
Reid Spencere4d87aa2006-12-23 06:05:41 +00006408 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6409 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006410
Reid Spencere4d87aa2006-12-23 06:05:41 +00006411 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006412 // Not an extension from the same type?
6413 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006414 if (RHSCIOp->getType() != LHSCIOp->getType())
6415 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006416
Nick Lewycky4189a532008-01-28 03:48:02 +00006417 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006418 // and the other is a zext), then we can't handle this.
6419 if (CI->getOpcode() != LHSCI->getOpcode())
6420 return 0;
6421
Nick Lewycky4189a532008-01-28 03:48:02 +00006422 // Deal with equality cases early.
6423 if (ICI.isEquality())
6424 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6425
6426 // A signed comparison of sign extended values simplifies into a
6427 // signed comparison.
6428 if (isSignedCmp && isSignedExt)
6429 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6430
6431 // The other three cases all fold into an unsigned comparison.
6432 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006433 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006434
Reid Spencere4d87aa2006-12-23 06:05:41 +00006435 // If we aren't dealing with a constant on the RHS, exit early
6436 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6437 if (!CI)
6438 return 0;
6439
6440 // Compute the constant that would happen if we truncated to SrcTy then
6441 // reextended to DestTy.
6442 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6443 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6444
6445 // If the re-extended constant didn't change...
6446 if (Res2 == CI) {
6447 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6448 // For example, we might have:
6449 // %A = sext short %X to uint
6450 // %B = icmp ugt uint %A, 1330
6451 // It is incorrect to transform this into
6452 // %B = icmp ugt short %X, 1330
6453 // because %A may have negative value.
6454 //
Chris Lattnerf2991842008-07-11 04:09:09 +00006455 // However, we allow this when the compare is EQ/NE, because they are
6456 // signless.
6457 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006458 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00006459 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006460 }
6461
6462 // The re-extended constant changed so the constant cannot be represented
6463 // in the shorter type. Consequently, we cannot emit a simple comparison.
6464
6465 // First, handle some easy cases. We know the result cannot be equal at this
6466 // point so handle the ICI.isEquality() cases
6467 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006468 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006469 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006470 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006471
6472 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6473 // should have been folded away previously and not enter in here.
6474 Value *Result;
6475 if (isSignedCmp) {
6476 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006477 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006478 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006479 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006480 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006481 } else {
6482 // We're performing an unsigned comparison.
6483 if (isSignedExt) {
6484 // We're performing an unsigned comp with a sign extended value.
6485 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006486 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006487 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6488 NegOne, ICI.getName()), ICI);
6489 } else {
6490 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006491 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006492 }
6493 }
6494
6495 // Finally, return the value computed.
6496 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00006497 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006498 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00006499
6500 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6501 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6502 "ICmp should be folded!");
6503 if (Constant *CI = dyn_cast<Constant>(Result))
6504 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6505 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00006506}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006507
Reid Spencer832254e2007-02-02 02:16:23 +00006508Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6509 return commonShiftTransforms(I);
6510}
6511
6512Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6513 return commonShiftTransforms(I);
6514}
6515
6516Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006517 if (Instruction *R = commonShiftTransforms(I))
6518 return R;
6519
6520 Value *Op0 = I.getOperand(0);
6521
6522 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6523 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6524 if (CSI->isAllOnesValue())
6525 return ReplaceInstUsesWith(I, CSI);
6526
6527 // See if we can turn a signed shr into an unsigned shr.
Nate Begeman5bc1ea02008-07-29 15:49:41 +00006528 if (!isa<VectorType>(I.getType()) &&
6529 MaskedValueIsZero(Op0,
Chris Lattner348f6652007-12-06 01:59:46 +00006530 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006531 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006532
6533 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006534}
6535
6536Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6537 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006538 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006539
6540 // shl X, 0 == X and shr X, 0 == X
6541 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006542 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006543 Op0 == Constant::getNullValue(Op0->getType()))
6544 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006545
Reid Spencere4d87aa2006-12-23 06:05:41 +00006546 if (isa<UndefValue>(Op0)) {
6547 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006548 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006549 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006550 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6551 }
6552 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006553 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6554 return ReplaceInstUsesWith(I, Op0);
6555 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006556 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006557 }
6558
Chris Lattner2eefe512004-04-09 19:05:30 +00006559 // Try to fold constant and into select arguments.
6560 if (isa<Constant>(Op0))
6561 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006562 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006563 return R;
6564
Reid Spencerb83eb642006-10-20 07:07:24 +00006565 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006566 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6567 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006568 return 0;
6569}
6570
Reid Spencerb83eb642006-10-20 07:07:24 +00006571Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006572 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006573 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006574
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006575 // See if we can simplify any instructions used by the instruction whose sole
6576 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006577 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6578 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6579 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006580 KnownZero, KnownOne))
6581 return &I;
6582
Chris Lattner4d5542c2006-01-06 07:12:35 +00006583 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6584 // of a signed value.
6585 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006586 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006587 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006588 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6589 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006590 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006591 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006592 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006593 }
6594
6595 // ((X*C1) << C2) == (X * (C1 << C2))
6596 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6597 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6598 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006599 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006600 ConstantExpr::getShl(BOOp, Op1));
6601
6602 // Try to fold constant and into select arguments.
6603 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6604 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6605 return R;
6606 if (isa<PHINode>(Op0))
6607 if (Instruction *NV = FoldOpIntoPhi(I))
6608 return NV;
6609
Chris Lattner8999dd32007-12-22 09:07:47 +00006610 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6611 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6612 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6613 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6614 // place. Don't try to do this transformation in this case. Also, we
6615 // require that the input operand is a shift-by-constant so that we have
6616 // confidence that the shifts will get folded together. We could do this
6617 // xform in more cases, but it is unlikely to be profitable.
6618 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6619 isa<ConstantInt>(TrOp->getOperand(1))) {
6620 // Okay, we'll do this xform. Make the shift of shift.
6621 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006622 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006623 I.getName());
6624 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6625
6626 // For logical shifts, the truncation has the effect of making the high
6627 // part of the register be zeros. Emulate this by inserting an AND to
6628 // clear the top bits as needed. This 'and' will usually be zapped by
6629 // other xforms later if dead.
6630 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6631 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6632 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6633
6634 // The mask we constructed says what the trunc would do if occurring
6635 // between the shifts. We want to know the effect *after* the second
6636 // shift. We know that it is a logical shift by a constant, so adjust the
6637 // mask as appropriate.
6638 if (I.getOpcode() == Instruction::Shl)
6639 MaskV <<= Op1->getZExtValue();
6640 else {
6641 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6642 MaskV = MaskV.lshr(Op1->getZExtValue());
6643 }
6644
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006645 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006646 TI->getName());
6647 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6648
6649 // Return the value truncated to the interesting size.
6650 return new TruncInst(And, I.getType());
6651 }
6652 }
6653
Chris Lattner4d5542c2006-01-06 07:12:35 +00006654 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006655 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6656 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6657 Value *V1, *V2;
6658 ConstantInt *CC;
6659 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006660 default: break;
6661 case Instruction::Add:
6662 case Instruction::And:
6663 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006664 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006665 // These operators commute.
6666 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006667 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6668 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006669 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006670 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006671 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006672 Op0BO->getName());
6673 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006674 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006675 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006676 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006677 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006678 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006679 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006680 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006681 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006682
Chris Lattner150f12a2005-09-18 06:30:59 +00006683 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006684 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006685 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006686 match(Op0BOOp1,
6687 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006688 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6689 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006690 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006691 Op0BO->getOperand(0), Op1,
6692 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006693 InsertNewInstBefore(YS, I); // (Y << C)
6694 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006695 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006696 V1->getName()+".mask");
6697 InsertNewInstBefore(XM, I); // X & (CC << C)
6698
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006699 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006700 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006701 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006702
Reid Spencera07cb7d2007-02-02 14:41:37 +00006703 // FALL THROUGH.
6704 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006705 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006706 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6707 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006708 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006709 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006710 Op0BO->getOperand(1), Op1,
6711 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006712 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006713 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006714 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006715 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006716 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006717 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006718 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006719 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006720 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006721
Chris Lattner13d4ab42006-05-31 21:14:00 +00006722 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006723 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6724 match(Op0BO->getOperand(0),
6725 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006726 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006727 cast<BinaryOperator>(Op0BO->getOperand(0))
6728 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006729 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006730 Op0BO->getOperand(1), Op1,
6731 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006732 InsertNewInstBefore(YS, I); // (Y << C)
6733 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006734 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006735 V1->getName()+".mask");
6736 InsertNewInstBefore(XM, I); // X & (CC << C)
6737
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006738 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006739 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006740
Chris Lattner11021cb2005-09-18 05:12:10 +00006741 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006742 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006743 }
6744
6745
6746 // If the operand is an bitwise operator with a constant RHS, and the
6747 // shift is the only use, we can pull it out of the shift.
6748 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6749 bool isValid = true; // Valid only for And, Or, Xor
6750 bool highBitSet = false; // Transform if high bit of constant set?
6751
6752 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006753 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006754 case Instruction::Add:
6755 isValid = isLeftShift;
6756 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006757 case Instruction::Or:
6758 case Instruction::Xor:
6759 highBitSet = false;
6760 break;
6761 case Instruction::And:
6762 highBitSet = true;
6763 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006764 }
6765
6766 // If this is a signed shift right, and the high bit is modified
6767 // by the logical operation, do not perform the transformation.
6768 // The highBitSet boolean indicates the value of the high bit of
6769 // the constant which would cause it to be modified for this
6770 // operation.
6771 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006772 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006773 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006774
6775 if (isValid) {
6776 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6777
6778 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006779 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006780 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006781 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006782
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006783 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006784 NewRHS);
6785 }
6786 }
6787 }
6788 }
6789
Chris Lattnerad0124c2006-01-06 07:52:12 +00006790 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006791 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6792 if (ShiftOp && !ShiftOp->isShift())
6793 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006794
Reid Spencerb83eb642006-10-20 07:07:24 +00006795 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006796 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006797 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6798 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006799 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6800 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6801 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006802
Zhou Sheng4351c642007-04-02 08:20:41 +00006803 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006804 if (AmtSum > TypeBits)
6805 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006806
6807 const IntegerType *Ty = cast<IntegerType>(I.getType());
6808
6809 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006810 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006811 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006812 ConstantInt::get(Ty, AmtSum));
6813 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6814 I.getOpcode() == Instruction::AShr) {
6815 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006816 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006817 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6818 I.getOpcode() == Instruction::LShr) {
6819 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6820 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006821 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006822 InsertNewInstBefore(Shift, I);
6823
Zhou Shenge9e03f62007-03-28 15:02:20 +00006824 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006825 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006826 }
6827
Chris Lattnerb87056f2007-02-05 00:57:54 +00006828 // Okay, if we get here, one shift must be left, and the other shift must be
6829 // right. See if the amounts are equal.
6830 if (ShiftAmt1 == ShiftAmt2) {
6831 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6832 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006833 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006834 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006835 }
6836 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6837 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006838 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006839 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006840 }
6841 // We can simplify ((X << C) >>s C) into a trunc + sext.
6842 // NOTE: we could do this for any C, but that would make 'unusual' integer
6843 // types. For now, just stick to ones well-supported by the code
6844 // generators.
6845 const Type *SExtType = 0;
6846 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006847 case 1 :
6848 case 8 :
6849 case 16 :
6850 case 32 :
6851 case 64 :
6852 case 128:
6853 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6854 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006855 default: break;
6856 }
6857 if (SExtType) {
6858 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6859 InsertNewInstBefore(NewTrunc, I);
6860 return new SExtInst(NewTrunc, Ty);
6861 }
6862 // Otherwise, we can't handle it yet.
6863 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006864 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006865
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006866 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006867 if (I.getOpcode() == Instruction::Shl) {
6868 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6869 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006870 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006871 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006872 InsertNewInstBefore(Shift, I);
6873
Reid Spencer55702aa2007-03-25 21:11:44 +00006874 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006875 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006876 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006877
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006878 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006879 if (I.getOpcode() == Instruction::LShr) {
6880 assert(ShiftOp->getOpcode() == Instruction::Shl);
6881 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006882 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006883 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006884
Reid Spencerd5e30f02007-03-26 17:18:58 +00006885 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006886 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006887 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006888
6889 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6890 } else {
6891 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006892 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006893
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006894 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006895 if (I.getOpcode() == Instruction::Shl) {
6896 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6897 ShiftOp->getOpcode() == Instruction::AShr);
6898 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006899 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006900 ConstantInt::get(Ty, ShiftDiff));
6901 InsertNewInstBefore(Shift, I);
6902
Reid Spencer55702aa2007-03-25 21:11:44 +00006903 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006904 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006905 }
6906
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006907 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006908 if (I.getOpcode() == Instruction::LShr) {
6909 assert(ShiftOp->getOpcode() == Instruction::Shl);
6910 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006911 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006912 InsertNewInstBefore(Shift, I);
6913
Reid Spencer68d27cf2007-03-26 23:45:51 +00006914 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006915 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006916 }
6917
6918 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006919 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006920 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006921 return 0;
6922}
6923
Chris Lattnera1be5662002-05-02 17:06:02 +00006924
Chris Lattnercfd65102005-10-29 04:36:15 +00006925/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6926/// expression. If so, decompose it, returning some value X, such that Val is
6927/// X*Scale+Offset.
6928///
6929static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006930 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006931 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006932 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006933 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006934 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006935 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006936 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6937 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6938 if (I->getOpcode() == Instruction::Shl) {
6939 // This is a value scaled by '1 << the shift amt'.
6940 Scale = 1U << RHS->getZExtValue();
6941 Offset = 0;
6942 return I->getOperand(0);
6943 } else if (I->getOpcode() == Instruction::Mul) {
6944 // This value is scaled by 'RHS'.
6945 Scale = RHS->getZExtValue();
6946 Offset = 0;
6947 return I->getOperand(0);
6948 } else if (I->getOpcode() == Instruction::Add) {
6949 // We have X+C. Check to see if we really have (X*C2)+C1,
6950 // where C1 is divisible by C2.
6951 unsigned SubScale;
6952 Value *SubVal =
6953 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6954 Offset += RHS->getZExtValue();
6955 Scale = SubScale;
6956 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006957 }
6958 }
6959 }
6960
6961 // Otherwise, we can't look past this.
6962 Scale = 1;
6963 Offset = 0;
6964 return Val;
6965}
6966
6967
Chris Lattnerb3f83972005-10-24 06:03:58 +00006968/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6969/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006970Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006971 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006972 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006973
Chris Lattnerb53c2382005-10-24 06:22:12 +00006974 // Remove any uses of AI that are dead.
6975 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006976
Chris Lattnerb53c2382005-10-24 06:22:12 +00006977 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6978 Instruction *User = cast<Instruction>(*UI++);
6979 if (isInstructionTriviallyDead(User)) {
6980 while (UI != E && *UI == User)
6981 ++UI; // If this instruction uses AI more than once, don't break UI.
6982
Chris Lattnerb53c2382005-10-24 06:22:12 +00006983 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006984 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006985 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006986 }
6987 }
6988
Chris Lattnerb3f83972005-10-24 06:03:58 +00006989 // Get the type really allocated and the type casted to.
6990 const Type *AllocElTy = AI.getAllocatedType();
6991 const Type *CastElTy = PTy->getElementType();
6992 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006993
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006994 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6995 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006996 if (CastElTyAlign < AllocElTyAlign) return 0;
6997
Chris Lattner39387a52005-10-24 06:35:18 +00006998 // If the allocation has multiple uses, only promote it if we are strictly
6999 // increasing the alignment of the resultant allocation. If we keep it the
7000 // same, we open the door to infinite loops of various kinds.
7001 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7002
Duncan Sands514ab342007-11-01 20:53:16 +00007003 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7004 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007005 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007006
Chris Lattner455fcc82005-10-29 03:19:53 +00007007 // See if we can satisfy the modulus by pulling a scale out of the array
7008 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007009 unsigned ArraySizeScale;
7010 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007011 Value *NumElements = // See if the array size is a decomposable linear expr.
7012 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7013
Chris Lattner455fcc82005-10-29 03:19:53 +00007014 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7015 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007016 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7017 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007018
Chris Lattner455fcc82005-10-29 03:19:53 +00007019 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7020 Value *Amt = 0;
7021 if (Scale == 1) {
7022 Amt = NumElements;
7023 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007024 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007025 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7026 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007027 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007028 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007029 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007030 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007031 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007032 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007033 }
7034
Jeff Cohen86796be2007-04-04 16:58:57 +00007035 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7036 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007037 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007038 Amt = InsertNewInstBefore(Tmp, AI);
7039 }
7040
Chris Lattnerb3f83972005-10-24 06:03:58 +00007041 AllocationInst *New;
7042 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007043 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007044 else
Chris Lattner6934a042007-02-11 01:23:03 +00007045 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007046 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007047 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007048
7049 // If the allocation has multiple uses, insert a cast and change all things
7050 // that used it to use the new cast. This will also hack on CI, but it will
7051 // die soon.
7052 if (!AI.hasOneUse()) {
7053 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007054 // New is the allocation instruction, pointer typed. AI is the original
7055 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7056 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007057 InsertNewInstBefore(NewCast, AI);
7058 AI.replaceAllUsesWith(NewCast);
7059 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007060 return ReplaceInstUsesWith(CI, New);
7061}
7062
Chris Lattner70074e02006-05-13 02:06:03 +00007063/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007064/// and return it as type Ty without inserting any new casts and without
7065/// changing the computed value. This is used by code that tries to decide
7066/// whether promoting or shrinking integer operations to wider or smaller types
7067/// will allow us to eliminate a truncate or extend.
7068///
7069/// This is a truncation operation if Ty is smaller than V->getType(), or an
7070/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007071///
7072/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7073/// should return true if trunc(V) can be computed by computing V in the smaller
7074/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7075/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7076/// efficiently truncated.
7077///
7078/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7079/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7080/// the final result.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007081bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7082 unsigned CastOpc,
7083 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007084 // We can always evaluate constants in another type.
7085 if (isa<ConstantInt>(V))
7086 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007087
7088 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007089 if (!I) return false;
7090
7091 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007092
Chris Lattner951626b2007-08-02 06:11:14 +00007093 // If this is an extension or truncate, we can often eliminate it.
7094 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7095 // If this is a cast from the destination type, we can trivially eliminate
7096 // it, and this will remove a cast overall.
7097 if (I->getOperand(0)->getType() == Ty) {
7098 // If the first operand is itself a cast, and is eliminable, do not count
7099 // this as an eliminable cast. We would prefer to eliminate those two
7100 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007101 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007102 ++NumCastsRemoved;
7103 return true;
7104 }
7105 }
7106
7107 // We can't extend or shrink something that has multiple uses: doing so would
7108 // require duplicating the instruction in general, which isn't profitable.
7109 if (!I->hasOneUse()) return false;
7110
Chris Lattner70074e02006-05-13 02:06:03 +00007111 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007112 case Instruction::Add:
7113 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007114 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007115 case Instruction::And:
7116 case Instruction::Or:
7117 case Instruction::Xor:
7118 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007119 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7120 NumCastsRemoved) &&
7121 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7122 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007123
Chris Lattner46b96052006-11-29 07:18:39 +00007124 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007125 // If we are truncating the result of this SHL, and if it's a shift of a
7126 // constant amount, we can always perform a SHL in a smaller type.
7127 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007128 uint32_t BitWidth = Ty->getBitWidth();
7129 if (BitWidth < OrigTy->getBitWidth() &&
7130 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007131 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7132 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007133 }
7134 break;
7135 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007136 // If this is a truncate of a logical shr, we can truncate it to a smaller
7137 // lshr iff we know that the bits we would otherwise be shifting in are
7138 // already zeros.
7139 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007140 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7141 uint32_t BitWidth = Ty->getBitWidth();
7142 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007143 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007144 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7145 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007146 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7147 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007148 }
7149 }
Chris Lattner46b96052006-11-29 07:18:39 +00007150 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007151 case Instruction::ZExt:
7152 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007153 case Instruction::Trunc:
7154 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007155 // can safely replace it. Note that replacing it does not reduce the number
7156 // of casts in the input.
7157 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007158 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007159 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007160 case Instruction::Select: {
7161 SelectInst *SI = cast<SelectInst>(I);
7162 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7163 NumCastsRemoved) &&
7164 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7165 NumCastsRemoved);
7166 }
Chris Lattner8114b712008-06-18 04:00:49 +00007167 case Instruction::PHI: {
7168 // We can change a phi if we can change all operands.
7169 PHINode *PN = cast<PHINode>(I);
7170 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7171 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7172 NumCastsRemoved))
7173 return false;
7174 return true;
7175 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007176 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007177 // TODO: Can handle more cases here.
7178 break;
7179 }
7180
7181 return false;
7182}
7183
7184/// EvaluateInDifferentType - Given an expression that
7185/// CanEvaluateInDifferentType returns true for, actually insert the code to
7186/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007187Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007188 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007189 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007190 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007191
7192 // Otherwise, it must be an instruction.
7193 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007194 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007195 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007196 case Instruction::Add:
7197 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007198 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007199 case Instruction::And:
7200 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007201 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007202 case Instruction::AShr:
7203 case Instruction::LShr:
7204 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007205 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007206 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007207 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattner8114b712008-06-18 04:00:49 +00007208 LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007209 break;
7210 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007211 case Instruction::Trunc:
7212 case Instruction::ZExt:
7213 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007214 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007215 // just return the source. There's no need to insert it because it is not
7216 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007217 if (I->getOperand(0)->getType() == Ty)
7218 return I->getOperand(0);
7219
Chris Lattner8114b712008-06-18 04:00:49 +00007220 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007221 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007222 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007223 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007224 case Instruction::Select: {
7225 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7226 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7227 Res = SelectInst::Create(I->getOperand(0), True, False);
7228 break;
7229 }
Chris Lattner8114b712008-06-18 04:00:49 +00007230 case Instruction::PHI: {
7231 PHINode *OPN = cast<PHINode>(I);
7232 PHINode *NPN = PHINode::Create(Ty);
7233 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7234 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7235 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7236 }
7237 Res = NPN;
7238 break;
7239 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007240 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007241 // TODO: Can handle more cases here.
7242 assert(0 && "Unreachable!");
7243 break;
7244 }
7245
Chris Lattner8114b712008-06-18 04:00:49 +00007246 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007247 return InsertNewInstBefore(Res, *I);
7248}
7249
Reid Spencer3da59db2006-11-27 01:05:10 +00007250/// @brief Implement the transforms common to all CastInst visitors.
7251Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007252 Value *Src = CI.getOperand(0);
7253
Dan Gohman23d9d272007-05-11 21:10:54 +00007254 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007255 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007256 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007257 if (Instruction::CastOps opc =
7258 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7259 // The first cast (CSrc) is eliminable so we need to fix up or replace
7260 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007261 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007262 }
7263 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007264
Reid Spencer3da59db2006-11-27 01:05:10 +00007265 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007266 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7267 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7268 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007269
7270 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007271 if (isa<PHINode>(Src))
7272 if (Instruction *NV = FoldOpIntoPhi(CI))
7273 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007274
Reid Spencer3da59db2006-11-27 01:05:10 +00007275 return 0;
7276}
7277
Chris Lattnerd3e28342007-04-27 17:44:50 +00007278/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7279Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7280 Value *Src = CI.getOperand(0);
7281
Chris Lattnerd3e28342007-04-27 17:44:50 +00007282 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007283 // If casting the result of a getelementptr instruction with no offset, turn
7284 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007285 if (GEP->hasAllZeroIndices()) {
7286 // Changing the cast operand is usually not a good idea but it is safe
7287 // here because the pointer operand is being replaced with another
7288 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007289 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007290 CI.setOperand(0, GEP->getOperand(0));
7291 return &CI;
7292 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007293
7294 // If the GEP has a single use, and the base pointer is a bitcast, and the
7295 // GEP computes a constant offset, see if we can convert these three
7296 // instructions into fewer. This typically happens with unions and other
7297 // non-type-safe code.
7298 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7299 if (GEP->hasAllConstantIndices()) {
7300 // We are guaranteed to get a constant from EmitGEPOffset.
7301 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7302 int64_t Offset = OffsetV->getSExtValue();
7303
7304 // Get the base pointer input of the bitcast, and the type it points to.
7305 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7306 const Type *GEPIdxTy =
7307 cast<PointerType>(OrigBase->getType())->getElementType();
7308 if (GEPIdxTy->isSized()) {
7309 SmallVector<Value*, 8> NewIndices;
7310
Chris Lattnerc42e2262007-05-05 01:59:31 +00007311 // Start with the index over the outer type. Note that the type size
7312 // might be zero (even if the offset isn't zero) if the indexed type
7313 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007314 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007315 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007316 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007317 FirstIdx = Offset/TySize;
7318 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007319
Chris Lattnerc42e2262007-05-05 01:59:31 +00007320 // Handle silly modulus not returning values values [0..TySize).
7321 if (Offset < 0) {
7322 --FirstIdx;
7323 Offset += TySize;
7324 assert(Offset >= 0);
7325 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007326 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007327 }
7328
7329 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007330
7331 // Index into the types. If we fail, set OrigBase to null.
7332 while (Offset) {
7333 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7334 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007335 if (Offset < (int64_t)SL->getSizeInBytes()) {
7336 unsigned Elt = SL->getElementContainingOffset(Offset);
7337 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007338
Chris Lattner6b6aef82007-05-15 00:16:00 +00007339 Offset -= SL->getElementOffset(Elt);
7340 GEPIdxTy = STy->getElementType(Elt);
7341 } else {
7342 // Otherwise, we can't index into this, bail out.
7343 Offset = 0;
7344 OrigBase = 0;
7345 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007346 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7347 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007348 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007349 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7350 Offset %= EltSize;
7351 } else {
7352 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7353 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007354 GEPIdxTy = STy->getElementType();
7355 } else {
7356 // Otherwise, we can't index into this, bail out.
7357 Offset = 0;
7358 OrigBase = 0;
7359 }
7360 }
7361 if (OrigBase) {
7362 // If we were able to index down into an element, create the GEP
7363 // and bitcast the result. This eliminates one bitcast, potentially
7364 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007365 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7366 NewIndices.begin(),
7367 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007368 InsertNewInstBefore(NGEP, CI);
7369 NGEP->takeName(GEP);
7370
Chris Lattner9bc14642007-04-28 00:57:34 +00007371 if (isa<BitCastInst>(CI))
7372 return new BitCastInst(NGEP, CI.getType());
7373 assert(isa<PtrToIntInst>(CI));
7374 return new PtrToIntInst(NGEP, CI.getType());
7375 }
7376 }
7377 }
7378 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007379 }
7380
7381 return commonCastTransforms(CI);
7382}
7383
7384
7385
Chris Lattnerc739cd62007-03-03 05:27:34 +00007386/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7387/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007388/// cases.
7389/// @brief Implement the transforms common to CastInst with integer operands
7390Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7391 if (Instruction *Result = commonCastTransforms(CI))
7392 return Result;
7393
7394 Value *Src = CI.getOperand(0);
7395 const Type *SrcTy = Src->getType();
7396 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007397 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7398 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007399
Reid Spencer3da59db2006-11-27 01:05:10 +00007400 // See if we can simplify any instructions used by the LHS whose sole
7401 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007402 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7403 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007404 KnownZero, KnownOne))
7405 return &CI;
7406
7407 // If the source isn't an instruction or has more than one use then we
7408 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007409 Instruction *SrcI = dyn_cast<Instruction>(Src);
7410 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007411 return 0;
7412
Chris Lattnerc739cd62007-03-03 05:27:34 +00007413 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007414 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007415 if (!isa<BitCastInst>(CI) &&
7416 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007417 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007418 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007419 // eliminates the cast, so it is always a win. If this is a zero-extension,
7420 // we need to do an AND to maintain the clear top-part of the computation,
7421 // so we require that the input have eliminated at least one cast. If this
7422 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007423 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007424 bool DoXForm;
7425 switch (CI.getOpcode()) {
7426 default:
7427 // All the others use floating point so we shouldn't actually
7428 // get here because of the check above.
7429 assert(0 && "Unknown cast type");
7430 case Instruction::Trunc:
7431 DoXForm = true;
7432 break;
7433 case Instruction::ZExt:
7434 DoXForm = NumCastsRemoved >= 1;
7435 break;
7436 case Instruction::SExt:
7437 DoXForm = NumCastsRemoved >= 2;
7438 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007439 }
7440
7441 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007442 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7443 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007444 assert(Res->getType() == DestTy);
7445 switch (CI.getOpcode()) {
7446 default: assert(0 && "Unknown cast type!");
7447 case Instruction::Trunc:
7448 case Instruction::BitCast:
7449 // Just replace this cast with the result.
7450 return ReplaceInstUsesWith(CI, Res);
7451 case Instruction::ZExt: {
7452 // We need to emit an AND to clear the high bits.
7453 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007454 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7455 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007456 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007457 }
7458 case Instruction::SExt:
7459 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007460 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007461 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7462 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007463 }
7464 }
7465 }
7466
7467 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7468 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7469
7470 switch (SrcI->getOpcode()) {
7471 case Instruction::Add:
7472 case Instruction::Mul:
7473 case Instruction::And:
7474 case Instruction::Or:
7475 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007476 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007477 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7478 // Don't insert two casts if they cannot be eliminated. We allow
7479 // two casts to be inserted if the sizes are the same. This could
7480 // only be converting signedness, which is a noop.
7481 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007482 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7483 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007484 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007485 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7486 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007487 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007488 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007489 }
7490 }
7491
7492 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7493 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7494 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007495 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007496 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007497 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007498 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007499 }
7500 break;
7501 case Instruction::SDiv:
7502 case Instruction::UDiv:
7503 case Instruction::SRem:
7504 case Instruction::URem:
7505 // If we are just changing the sign, rewrite.
7506 if (DestBitSize == SrcBitSize) {
7507 // Don't insert two casts if they cannot be eliminated. We allow
7508 // two casts to be inserted if the sizes are the same. This could
7509 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007510 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7511 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007512 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7513 Op0, DestTy, SrcI);
7514 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7515 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007516 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007517 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7518 }
7519 }
7520 break;
7521
7522 case Instruction::Shl:
7523 // Allow changing the sign of the source operand. Do not allow
7524 // changing the size of the shift, UNLESS the shift amount is a
7525 // constant. We must not change variable sized shifts to a smaller
7526 // size, because it is undefined to shift more bits out than exist
7527 // in the value.
7528 if (DestBitSize == SrcBitSize ||
7529 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007530 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7531 Instruction::BitCast : Instruction::Trunc);
7532 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007533 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007534 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007535 }
7536 break;
7537 case Instruction::AShr:
7538 // If this is a signed shr, and if all bits shifted in are about to be
7539 // truncated off, turn it into an unsigned shr to allow greater
7540 // simplifications.
7541 if (DestBitSize < SrcBitSize &&
7542 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007543 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007544 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7545 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007546 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007547 }
7548 }
7549 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007550 }
7551 return 0;
7552}
7553
Chris Lattner8a9f5712007-04-11 06:57:46 +00007554Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007555 if (Instruction *Result = commonIntCastTransforms(CI))
7556 return Result;
7557
7558 Value *Src = CI.getOperand(0);
7559 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007560 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7561 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007562
7563 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7564 switch (SrcI->getOpcode()) {
7565 default: break;
7566 case Instruction::LShr:
7567 // We can shrink lshr to something smaller if we know the bits shifted in
7568 // are already zeros.
7569 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007570 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007571
7572 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007573 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007574 Value* SrcIOp0 = SrcI->getOperand(0);
7575 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007576 if (ShAmt >= DestBitWidth) // All zeros.
7577 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7578
7579 // Okay, we can shrink this. Truncate the input, then return a new
7580 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007581 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7582 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7583 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007584 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007585 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007586 } else { // This is a variable shr.
7587
7588 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7589 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7590 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007591 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007592 Value *One = ConstantInt::get(SrcI->getType(), 1);
7593
Reid Spencer832254e2007-02-02 02:16:23 +00007594 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007595 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007596 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007597 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007598 SrcI->getOperand(0),
7599 "tmp"), CI);
7600 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007601 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007602 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007603 }
7604 break;
7605 }
7606 }
7607
7608 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007609}
7610
Evan Chengb98a10e2008-03-24 00:21:34 +00007611/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7612/// in order to eliminate the icmp.
7613Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7614 bool DoXform) {
7615 // If we are just checking for a icmp eq of a single bit and zext'ing it
7616 // to an integer, then shift the bit to the appropriate place and then
7617 // cast to integer to avoid the comparison.
7618 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7619 const APInt &Op1CV = Op1C->getValue();
7620
7621 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7622 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7623 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7624 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7625 if (!DoXform) return ICI;
7626
7627 Value *In = ICI->getOperand(0);
7628 Value *Sh = ConstantInt::get(In->getType(),
7629 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007630 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007631 In->getName()+".lobit"),
7632 CI);
7633 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007634 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007635 false/*ZExt*/, "tmp", &CI);
7636
7637 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7638 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007639 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007640 In->getName()+".not"),
7641 CI);
7642 }
7643
7644 return ReplaceInstUsesWith(CI, In);
7645 }
7646
7647
7648
7649 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7650 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7651 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7652 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7653 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7654 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7655 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7656 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7657 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7658 // This only works for EQ and NE
7659 ICI->isEquality()) {
7660 // If Op1C some other power of two, convert:
7661 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7662 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7663 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7664 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7665
7666 APInt KnownZeroMask(~KnownZero);
7667 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7668 if (!DoXform) return ICI;
7669
7670 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7671 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7672 // (X&4) == 2 --> false
7673 // (X&4) != 2 --> true
7674 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7675 Res = ConstantExpr::getZExt(Res, CI.getType());
7676 return ReplaceInstUsesWith(CI, Res);
7677 }
7678
7679 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7680 Value *In = ICI->getOperand(0);
7681 if (ShiftAmt) {
7682 // Perform a logical shr by shiftamt.
7683 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007684 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007685 ConstantInt::get(In->getType(), ShiftAmt),
7686 In->getName()+".lobit"), CI);
7687 }
7688
7689 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7690 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007691 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007692 InsertNewInstBefore(cast<Instruction>(In), CI);
7693 }
7694
7695 if (CI.getType() == In->getType())
7696 return ReplaceInstUsesWith(CI, In);
7697 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007698 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007699 }
7700 }
7701 }
7702
7703 return 0;
7704}
7705
Chris Lattner8a9f5712007-04-11 06:57:46 +00007706Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007707 // If one of the common conversion will work ..
7708 if (Instruction *Result = commonIntCastTransforms(CI))
7709 return Result;
7710
7711 Value *Src = CI.getOperand(0);
7712
7713 // If this is a cast of a cast
7714 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007715 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7716 // types and if the sizes are just right we can convert this into a logical
7717 // 'and' which will be much cheaper than the pair of casts.
7718 if (isa<TruncInst>(CSrc)) {
7719 // Get the sizes of the types involved
7720 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007721 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7722 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7723 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007724 // If we're actually extending zero bits and the trunc is a no-op
7725 if (MidSize < DstSize && SrcSize == DstSize) {
7726 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007727 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007728 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007729 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007730 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007731 // Unfortunately, if the type changed, we need to cast it back.
7732 if (And->getType() != CI.getType()) {
7733 And->setName(CSrc->getName()+".mask");
7734 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007735 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007736 }
7737 return And;
7738 }
7739 }
7740 }
7741
Evan Chengb98a10e2008-03-24 00:21:34 +00007742 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7743 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007744
Evan Chengb98a10e2008-03-24 00:21:34 +00007745 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7746 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7747 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7748 // of the (zext icmp) will be transformed.
7749 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7750 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7751 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7752 (transformZExtICmp(LHS, CI, false) ||
7753 transformZExtICmp(RHS, CI, false))) {
7754 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7755 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007756 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007757 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007758 }
7759
Reid Spencer3da59db2006-11-27 01:05:10 +00007760 return 0;
7761}
7762
Chris Lattner8a9f5712007-04-11 06:57:46 +00007763Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007764 if (Instruction *I = commonIntCastTransforms(CI))
7765 return I;
7766
Chris Lattner8a9f5712007-04-11 06:57:46 +00007767 Value *Src = CI.getOperand(0);
7768
7769 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7770 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7771 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7772 // If we are just checking for a icmp eq of a single bit and zext'ing it
7773 // to an integer, then shift the bit to the appropriate place and then
7774 // cast to integer to avoid the comparison.
7775 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7776 const APInt &Op1CV = Op1C->getValue();
7777
7778 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7779 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7780 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7781 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7782 Value *In = ICI->getOperand(0);
7783 Value *Sh = ConstantInt::get(In->getType(),
7784 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007785 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007786 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007787 CI);
7788 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007789 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007790 true/*SExt*/, "tmp", &CI);
7791
7792 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007793 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007794 In->getName()+".not"), CI);
7795
7796 return ReplaceInstUsesWith(CI, In);
7797 }
7798 }
7799 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00007800
7801 // See if the value being truncated is already sign extended. If so, just
7802 // eliminate the trunc/sext pair.
7803 if (getOpcode(Src) == Instruction::Trunc) {
7804 Value *Op = cast<User>(Src)->getOperand(0);
7805 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7806 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7807 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7808 unsigned NumSignBits = ComputeNumSignBits(Op);
7809
7810 if (OpBits == DestBits) {
7811 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7812 // bits, it is already ready.
7813 if (NumSignBits > DestBits-MidBits)
7814 return ReplaceInstUsesWith(CI, Op);
7815 } else if (OpBits < DestBits) {
7816 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7817 // bits, just sext from i32.
7818 if (NumSignBits > OpBits-MidBits)
7819 return new SExtInst(Op, CI.getType(), "tmp");
7820 } else {
7821 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7822 // bits, just truncate to i32.
7823 if (NumSignBits > OpBits-MidBits)
7824 return new TruncInst(Op, CI.getType(), "tmp");
7825 }
7826 }
Chris Lattner46bbad22008-08-06 07:35:52 +00007827
7828 // If the input is a shl/ashr pair of a same constant, then this is a sign
7829 // extension from a smaller value. If we could trust arbitrary bitwidth
7830 // integers, we could turn this into a truncate to the smaller bit and then
7831 // use a sext for the whole extension. Since we don't, look deeper and check
7832 // for a truncate. If the source and dest are the same type, eliminate the
7833 // trunc and extend and just do shifts. For example, turn:
7834 // %a = trunc i32 %i to i8
7835 // %b = shl i8 %a, 6
7836 // %c = ashr i8 %b, 6
7837 // %d = sext i8 %c to i32
7838 // into:
7839 // %a = shl i32 %i, 30
7840 // %d = ashr i32 %a, 30
7841 Value *A = 0;
7842 ConstantInt *BA = 0, *CA = 0;
7843 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
7844 m_ConstantInt(CA))) &&
7845 BA == CA && isa<TruncInst>(A)) {
7846 Value *I = cast<TruncInst>(A)->getOperand(0);
7847 if (I->getType() == CI.getType()) {
7848 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
7849 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
7850 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
7851 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
7852 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
7853 CI.getName()), CI);
7854 return BinaryOperator::CreateAShr(I, ShAmtV);
7855 }
7856 }
7857
Chris Lattnerba417832007-04-11 06:12:58 +00007858 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007859}
7860
Chris Lattnerb7530652008-01-27 05:29:54 +00007861/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7862/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007863static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00007864 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00007865 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00007866 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
7867 if (!losesInfo)
Chris Lattner02a260a2008-04-20 00:41:09 +00007868 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007869 return 0;
7870}
7871
7872/// LookThroughFPExtensions - If this is an fp extension instruction, look
7873/// through it until we get the source value.
7874static Value *LookThroughFPExtensions(Value *V) {
7875 if (Instruction *I = dyn_cast<Instruction>(V))
7876 if (I->getOpcode() == Instruction::FPExt)
7877 return LookThroughFPExtensions(I->getOperand(0));
7878
7879 // If this value is a constant, return the constant in the smallest FP type
7880 // that can accurately represent it. This allows us to turn
7881 // (float)((double)X+2.0) into x+2.0f.
7882 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7883 if (CFP->getType() == Type::PPC_FP128Ty)
7884 return V; // No constant folding of this.
7885 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007886 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007887 return V;
7888 if (CFP->getType() == Type::DoubleTy)
7889 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007890 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007891 return V;
7892 // Don't try to shrink to various long double types.
7893 }
7894
7895 return V;
7896}
7897
7898Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7899 if (Instruction *I = commonCastTransforms(CI))
7900 return I;
7901
7902 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7903 // smaller than the destination type, we can eliminate the truncate by doing
7904 // the add as the smaller type. This applies to add/sub/mul/div as well as
7905 // many builtins (sqrt, etc).
7906 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7907 if (OpI && OpI->hasOneUse()) {
7908 switch (OpI->getOpcode()) {
7909 default: break;
7910 case Instruction::Add:
7911 case Instruction::Sub:
7912 case Instruction::Mul:
7913 case Instruction::FDiv:
7914 case Instruction::FRem:
7915 const Type *SrcTy = OpI->getType();
7916 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7917 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7918 if (LHSTrunc->getType() != SrcTy &&
7919 RHSTrunc->getType() != SrcTy) {
7920 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7921 // If the source types were both smaller than the destination type of
7922 // the cast, do this xform.
7923 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7924 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7925 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7926 CI.getType(), CI);
7927 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7928 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007929 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007930 }
7931 }
7932 break;
7933 }
7934 }
7935 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007936}
7937
7938Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7939 return commonCastTransforms(CI);
7940}
7941
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007942Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00007943 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7944 if (OpI == 0)
7945 return commonCastTransforms(FI);
7946
7947 // fptoui(uitofp(X)) --> X
7948 // fptoui(sitofp(X)) --> X
7949 // This is safe if the intermediate type has enough bits in its mantissa to
7950 // accurately represent all values of X. For example, do not do this with
7951 // i64->float->i64. This is also safe for sitofp case, because any negative
7952 // 'X' value would cause an undefined result for the fptoui.
7953 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7954 OpI->getOperand(0)->getType() == FI.getType() &&
7955 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7956 OpI->getType()->getFPMantissaWidth())
7957 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007958
7959 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007960}
7961
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007962Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00007963 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7964 if (OpI == 0)
7965 return commonCastTransforms(FI);
7966
7967 // fptosi(sitofp(X)) --> X
7968 // fptosi(uitofp(X)) --> X
7969 // This is safe if the intermediate type has enough bits in its mantissa to
7970 // accurately represent all values of X. For example, do not do this with
7971 // i64->float->i64. This is also safe for sitofp case, because any negative
7972 // 'X' value would cause an undefined result for the fptoui.
7973 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7974 OpI->getOperand(0)->getType() == FI.getType() &&
7975 (int)FI.getType()->getPrimitiveSizeInBits() <=
7976 OpI->getType()->getFPMantissaWidth())
7977 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007978
7979 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007980}
7981
7982Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7983 return commonCastTransforms(CI);
7984}
7985
7986Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7987 return commonCastTransforms(CI);
7988}
7989
7990Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007991 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007992}
7993
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007994Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7995 if (Instruction *I = commonCastTransforms(CI))
7996 return I;
7997
7998 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7999 if (!DestPointee->isSized()) return 0;
8000
8001 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8002 ConstantInt *Cst;
8003 Value *X;
8004 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8005 m_ConstantInt(Cst)))) {
8006 // If the source and destination operands have the same type, see if this
8007 // is a single-index GEP.
8008 if (X->getType() == CI.getType()) {
8009 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00008010 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008011
8012 // Convert the constant to intptr type.
8013 APInt Offset = Cst->getValue();
8014 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8015
8016 // If Offset is evenly divisible by Size, we can do this xform.
8017 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8018 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008019 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008020 }
8021 }
8022 // TODO: Could handle other cases, e.g. where add is indexing into field of
8023 // struct etc.
8024 } else if (CI.getOperand(0)->hasOneUse() &&
8025 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8026 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8027 // "inttoptr+GEP" instead of "add+intptr".
8028
8029 // Get the size of the pointee type.
8030 uint64_t Size = TD->getABITypeSize(DestPointee);
8031
8032 // Convert the constant to intptr type.
8033 APInt Offset = Cst->getValue();
8034 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8035
8036 // If Offset is evenly divisible by Size, we can do this xform.
8037 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8038 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8039
8040 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8041 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008042 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008043 }
8044 }
8045 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008046}
8047
Chris Lattnerd3e28342007-04-27 17:44:50 +00008048Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008049 // If the operands are integer typed then apply the integer transforms,
8050 // otherwise just apply the common ones.
8051 Value *Src = CI.getOperand(0);
8052 const Type *SrcTy = Src->getType();
8053 const Type *DestTy = CI.getType();
8054
Chris Lattner42a75512007-01-15 02:27:26 +00008055 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008056 if (Instruction *Result = commonIntCastTransforms(CI))
8057 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008058 } else if (isa<PointerType>(SrcTy)) {
8059 if (Instruction *I = commonPointerCastTransforms(CI))
8060 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008061 } else {
8062 if (Instruction *Result = commonCastTransforms(CI))
8063 return Result;
8064 }
8065
8066
8067 // Get rid of casts from one type to the same type. These are useless and can
8068 // be replaced by the operand.
8069 if (DestTy == Src->getType())
8070 return ReplaceInstUsesWith(CI, Src);
8071
Reid Spencer3da59db2006-11-27 01:05:10 +00008072 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008073 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8074 const Type *DstElTy = DstPTy->getElementType();
8075 const Type *SrcElTy = SrcPTy->getElementType();
8076
Nate Begeman83ad90a2008-03-31 00:22:16 +00008077 // If the address spaces don't match, don't eliminate the bitcast, which is
8078 // required for changing types.
8079 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8080 return 0;
8081
Chris Lattnerd3e28342007-04-27 17:44:50 +00008082 // If we are casting a malloc or alloca to a pointer to a type of the same
8083 // size, rewrite the allocation instruction to allocate the "right" type.
8084 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8085 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8086 return V;
8087
Chris Lattnerd717c182007-05-05 22:32:24 +00008088 // If the source and destination are pointers, and this cast is equivalent
8089 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008090 // This can enhance SROA and other transforms that want type-safe pointers.
8091 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8092 unsigned NumZeros = 0;
8093 while (SrcElTy != DstElTy &&
8094 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8095 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8096 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8097 ++NumZeros;
8098 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008099
Chris Lattnerd3e28342007-04-27 17:44:50 +00008100 // If we found a path from the src to dest, create the getelementptr now.
8101 if (SrcElTy == DstElTy) {
8102 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008103 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8104 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008105 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008106 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008107
Reid Spencer3da59db2006-11-27 01:05:10 +00008108 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8109 if (SVI->hasOneUse()) {
8110 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8111 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008112 if (isa<VectorType>(DestTy) &&
8113 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00008114 SVI->getType()->getNumElements()) {
8115 CastInst *Tmp;
8116 // If either of the operands is a cast from CI.getType(), then
8117 // evaluating the shuffle in the casted destination's type will allow
8118 // us to eliminate at least one cast.
8119 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8120 Tmp->getOperand(0)->getType() == DestTy) ||
8121 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8122 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008123 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8124 SVI->getOperand(0), DestTy, &CI);
8125 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8126 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008127 // Return a new shuffle vector. Use the same element ID's, as we
8128 // know the vector types match #elts.
8129 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008130 }
8131 }
8132 }
8133 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008134 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008135}
8136
Chris Lattnere576b912004-04-09 23:46:01 +00008137/// GetSelectFoldableOperands - We want to turn code that looks like this:
8138/// %C = or %A, %B
8139/// %D = select %cond, %C, %A
8140/// into:
8141/// %C = select %cond, %B, 0
8142/// %D = or %A, %C
8143///
8144/// Assuming that the specified instruction is an operand to the select, return
8145/// a bitmask indicating which operands of this instruction are foldable if they
8146/// equal the other incoming value of the select.
8147///
8148static unsigned GetSelectFoldableOperands(Instruction *I) {
8149 switch (I->getOpcode()) {
8150 case Instruction::Add:
8151 case Instruction::Mul:
8152 case Instruction::And:
8153 case Instruction::Or:
8154 case Instruction::Xor:
8155 return 3; // Can fold through either operand.
8156 case Instruction::Sub: // Can only fold on the amount subtracted.
8157 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008158 case Instruction::LShr:
8159 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008160 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008161 default:
8162 return 0; // Cannot fold
8163 }
8164}
8165
8166/// GetSelectFoldableConstant - For the same transformation as the previous
8167/// function, return the identity constant that goes into the select.
8168static Constant *GetSelectFoldableConstant(Instruction *I) {
8169 switch (I->getOpcode()) {
8170 default: assert(0 && "This cannot happen!"); abort();
8171 case Instruction::Add:
8172 case Instruction::Sub:
8173 case Instruction::Or:
8174 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008175 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008176 case Instruction::LShr:
8177 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008178 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008179 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008180 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008181 case Instruction::Mul:
8182 return ConstantInt::get(I->getType(), 1);
8183 }
8184}
8185
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008186/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8187/// have the same opcode and only one use each. Try to simplify this.
8188Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8189 Instruction *FI) {
8190 if (TI->getNumOperands() == 1) {
8191 // If this is a non-volatile load or a cast from the same type,
8192 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008193 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008194 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8195 return 0;
8196 } else {
8197 return 0; // unknown unary op.
8198 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008199
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008200 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008201 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8202 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008203 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008204 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008205 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008206 }
8207
Reid Spencer832254e2007-02-02 02:16:23 +00008208 // Only handle binary operators here.
8209 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008210 return 0;
8211
8212 // Figure out if the operations have any operands in common.
8213 Value *MatchOp, *OtherOpT, *OtherOpF;
8214 bool MatchIsOpZero;
8215 if (TI->getOperand(0) == FI->getOperand(0)) {
8216 MatchOp = TI->getOperand(0);
8217 OtherOpT = TI->getOperand(1);
8218 OtherOpF = FI->getOperand(1);
8219 MatchIsOpZero = true;
8220 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8221 MatchOp = TI->getOperand(1);
8222 OtherOpT = TI->getOperand(0);
8223 OtherOpF = FI->getOperand(0);
8224 MatchIsOpZero = false;
8225 } else if (!TI->isCommutative()) {
8226 return 0;
8227 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8228 MatchOp = TI->getOperand(0);
8229 OtherOpT = TI->getOperand(1);
8230 OtherOpF = FI->getOperand(0);
8231 MatchIsOpZero = true;
8232 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8233 MatchOp = TI->getOperand(1);
8234 OtherOpT = TI->getOperand(0);
8235 OtherOpF = FI->getOperand(1);
8236 MatchIsOpZero = true;
8237 } else {
8238 return 0;
8239 }
8240
8241 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008242 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8243 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008244 InsertNewInstBefore(NewSI, SI);
8245
8246 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8247 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008248 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008249 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008250 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008251 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008252 assert(0 && "Shouldn't get here");
8253 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008254}
8255
Dan Gohman81b28ce2008-09-16 18:46:06 +00008256/// visitSelectInstWithICmp - Visit a SelectInst that has an
8257/// ICmpInst as its first operand.
8258///
8259Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8260 ICmpInst *ICI) {
8261 bool Changed = false;
8262 ICmpInst::Predicate Pred = ICI->getPredicate();
8263 Value *CmpLHS = ICI->getOperand(0);
8264 Value *CmpRHS = ICI->getOperand(1);
8265 Value *TrueVal = SI.getTrueValue();
8266 Value *FalseVal = SI.getFalseValue();
8267
8268 // Check cases where the comparison is with a constant that
8269 // can be adjusted to fit the min/max idiom. We may edit ICI in
8270 // place here, so make sure the select is the only user.
8271 if (ICI->hasOneUse())
8272 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
8273 switch (Pred) {
8274 default: break;
8275 case ICmpInst::ICMP_ULT:
8276 case ICmpInst::ICMP_SLT: {
8277 // X < MIN ? T : F --> F
8278 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8279 return ReplaceInstUsesWith(SI, FalseVal);
8280 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8281 Constant *AdjustedRHS = SubOne(CI);
8282 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8283 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8284 Pred = ICmpInst::getSwappedPredicate(Pred);
8285 CmpRHS = AdjustedRHS;
8286 std::swap(FalseVal, TrueVal);
8287 ICI->setPredicate(Pred);
8288 ICI->setOperand(1, CmpRHS);
8289 SI.setOperand(1, TrueVal);
8290 SI.setOperand(2, FalseVal);
8291 Changed = true;
8292 }
8293 break;
8294 }
8295 case ICmpInst::ICMP_UGT:
8296 case ICmpInst::ICMP_SGT: {
8297 // X > MAX ? T : F --> F
8298 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8299 return ReplaceInstUsesWith(SI, FalseVal);
8300 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8301 Constant *AdjustedRHS = AddOne(CI);
8302 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8303 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8304 Pred = ICmpInst::getSwappedPredicate(Pred);
8305 CmpRHS = AdjustedRHS;
8306 std::swap(FalseVal, TrueVal);
8307 ICI->setPredicate(Pred);
8308 ICI->setOperand(1, CmpRHS);
8309 SI.setOperand(1, TrueVal);
8310 SI.setOperand(2, FalseVal);
8311 Changed = true;
8312 }
8313 break;
8314 }
8315 }
8316
8317 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8318 // Transform (X == Y) ? X : Y -> Y
8319 if (Pred == ICmpInst::ICMP_EQ)
8320 return ReplaceInstUsesWith(SI, FalseVal);
8321 // Transform (X != Y) ? X : Y -> X
8322 if (Pred == ICmpInst::ICMP_NE)
8323 return ReplaceInstUsesWith(SI, TrueVal);
8324 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8325
8326 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8327 // Transform (X == Y) ? Y : X -> X
8328 if (Pred == ICmpInst::ICMP_EQ)
8329 return ReplaceInstUsesWith(SI, FalseVal);
8330 // Transform (X != Y) ? Y : X -> Y
8331 if (Pred == ICmpInst::ICMP_NE)
8332 return ReplaceInstUsesWith(SI, TrueVal);
8333 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8334 }
8335
8336 /// NOTE: if we wanted to, this is where to detect integer ABS
8337
8338 return Changed ? &SI : 0;
8339}
8340
Chris Lattner3d69f462004-03-12 05:52:32 +00008341Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008342 Value *CondVal = SI.getCondition();
8343 Value *TrueVal = SI.getTrueValue();
8344 Value *FalseVal = SI.getFalseValue();
8345
8346 // select true, X, Y -> X
8347 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008348 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008349 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008350
8351 // select C, X, X -> X
8352 if (TrueVal == FalseVal)
8353 return ReplaceInstUsesWith(SI, TrueVal);
8354
Chris Lattnere87597f2004-10-16 18:11:37 +00008355 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8356 return ReplaceInstUsesWith(SI, FalseVal);
8357 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8358 return ReplaceInstUsesWith(SI, TrueVal);
8359 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8360 if (isa<Constant>(TrueVal))
8361 return ReplaceInstUsesWith(SI, TrueVal);
8362 else
8363 return ReplaceInstUsesWith(SI, FalseVal);
8364 }
8365
Reid Spencer4fe16d62007-01-11 18:21:29 +00008366 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008367 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008368 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008369 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008370 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008371 } else {
8372 // Change: A = select B, false, C --> A = and !B, C
8373 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008374 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008375 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008376 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008377 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008378 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008379 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008380 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008381 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008382 } else {
8383 // Change: A = select B, C, true --> A = or !B, C
8384 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008385 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008386 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008387 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008388 }
8389 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008390
8391 // select a, b, a -> a&b
8392 // select a, a, b -> a|b
8393 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008394 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008395 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008396 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008397 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008398
Chris Lattner2eefe512004-04-09 19:05:30 +00008399 // Selecting between two integer constants?
8400 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8401 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008402 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008403 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008404 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008405 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008406 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008407 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008408 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008409 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008410 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008411 }
Chris Lattnerba417832007-04-11 06:12:58 +00008412
8413 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008414
Reid Spencere4d87aa2006-12-23 06:05:41 +00008415 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008416
Reid Spencere4d87aa2006-12-23 06:05:41 +00008417 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008418 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008419 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008420 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008421 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008422 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008423 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008424 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008425 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008426 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008427 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008428 InsertNewInstBefore(SRA, SI);
8429
Reid Spencer3da59db2006-11-27 01:05:10 +00008430 // Finally, convert to the type of the select RHS. We figure out
8431 // if this requires a SExt, Trunc or BitCast based on the sizes.
8432 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008433 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8434 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008435 if (SRASize < SISize)
8436 opc = Instruction::SExt;
8437 else if (SRASize > SISize)
8438 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008439 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008440 }
8441 }
8442
8443
8444 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008445 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008446 // non-constant value, eliminate this whole mess. This corresponds to
8447 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008448 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008449 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008450 cast<Constant>(IC->getOperand(1))->isNullValue())
8451 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8452 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008453 isa<ConstantInt>(ICA->getOperand(1)) &&
8454 (ICA->getOperand(1) == TrueValC ||
8455 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008456 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8457 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008458 // know whether we have a icmp_ne or icmp_eq and whether the
8459 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008460 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008461 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008462 Value *V = ICA;
8463 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008464 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008465 Instruction::Xor, V, ICA->getOperand(1)), SI);
8466 return ReplaceInstUsesWith(SI, V);
8467 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008468 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008469 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008470
8471 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008472 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8473 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008474 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008475 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8476 // This is not safe in general for floating point:
8477 // consider X== -0, Y== +0.
8478 // It becomes safe if either operand is a nonzero constant.
8479 ConstantFP *CFPt, *CFPf;
8480 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8481 !CFPt->getValueAPF().isZero()) ||
8482 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8483 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008484 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008485 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008486 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008487 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008488 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00008489 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00008490
Reid Spencere4d87aa2006-12-23 06:05:41 +00008491 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008492 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008493 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8494 // This is not safe in general for floating point:
8495 // consider X== -0, Y== +0.
8496 // It becomes safe if either operand is a nonzero constant.
8497 ConstantFP *CFPt, *CFPf;
8498 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8499 !CFPt->getValueAPF().isZero()) ||
8500 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8501 !CFPf->getValueAPF().isZero()))
8502 return ReplaceInstUsesWith(SI, FalseVal);
8503 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008504 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008505 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8506 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00008507 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00008508 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00008509 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00008510 }
8511
8512 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00008513 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8514 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8515 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00008516
Chris Lattner87875da2005-01-13 22:52:24 +00008517 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8518 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8519 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008520 Instruction *AddOp = 0, *SubOp = 0;
8521
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008522 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8523 if (TI->getOpcode() == FI->getOpcode())
8524 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8525 return IV;
8526
8527 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8528 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008529 if (TI->getOpcode() == Instruction::Sub &&
8530 FI->getOpcode() == Instruction::Add) {
8531 AddOp = FI; SubOp = TI;
8532 } else if (FI->getOpcode() == Instruction::Sub &&
8533 TI->getOpcode() == Instruction::Add) {
8534 AddOp = TI; SubOp = FI;
8535 }
8536
8537 if (AddOp) {
8538 Value *OtherAddOp = 0;
8539 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8540 OtherAddOp = AddOp->getOperand(1);
8541 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8542 OtherAddOp = AddOp->getOperand(0);
8543 }
8544
8545 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008546 // So at this point we know we have (Y -> OtherAddOp):
8547 // select C, (add X, Y), (sub X, Z)
8548 Value *NegVal; // Compute -Z
8549 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8550 NegVal = ConstantExpr::getNeg(C);
8551 } else {
8552 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008553 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008554 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008555
8556 Value *NewTrueOp = OtherAddOp;
8557 Value *NewFalseOp = NegVal;
8558 if (AddOp != TI)
8559 std::swap(NewTrueOp, NewFalseOp);
8560 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008561 SelectInst::Create(CondVal, NewTrueOp,
8562 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008563
8564 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008565 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008566 }
8567 }
8568 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008569
Chris Lattnere576b912004-04-09 23:46:01 +00008570 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008571 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008572 // See the comment above GetSelectFoldableOperands for a description of the
8573 // transformation we are doing here.
8574 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8575 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8576 !isa<Constant>(FalseVal))
8577 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8578 unsigned OpToFold = 0;
8579 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8580 OpToFold = 1;
8581 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8582 OpToFold = 2;
8583 }
8584
8585 if (OpToFold) {
8586 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008587 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008588 SelectInst::Create(SI.getCondition(),
8589 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008590 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008591 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008592 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008593 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008594 else {
8595 assert(0 && "Unknown instruction!!");
8596 }
8597 }
8598 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008599
Chris Lattnere576b912004-04-09 23:46:01 +00008600 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8601 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8602 !isa<Constant>(TrueVal))
8603 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8604 unsigned OpToFold = 0;
8605 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8606 OpToFold = 1;
8607 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8608 OpToFold = 2;
8609 }
8610
8611 if (OpToFold) {
8612 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008613 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008614 SelectInst::Create(SI.getCondition(), C,
8615 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008616 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008617 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008618 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008619 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008620 else
Chris Lattnere576b912004-04-09 23:46:01 +00008621 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008622 }
8623 }
8624 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008625
8626 if (BinaryOperator::isNot(CondVal)) {
8627 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8628 SI.setOperand(1, FalseVal);
8629 SI.setOperand(2, TrueVal);
8630 return &SI;
8631 }
8632
Chris Lattner3d69f462004-03-12 05:52:32 +00008633 return 0;
8634}
8635
Dan Gohmaneee962e2008-04-10 18:43:06 +00008636/// EnforceKnownAlignment - If the specified pointer points to an object that
8637/// we control, modify the object's alignment to PrefAlign. This isn't
8638/// often possible though. If alignment is important, a more reliable approach
8639/// is to simply align all global variables and allocation instructions to
8640/// their preferred alignment from the beginning.
8641///
8642static unsigned EnforceKnownAlignment(Value *V,
8643 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008644
Dan Gohmaneee962e2008-04-10 18:43:06 +00008645 User *U = dyn_cast<User>(V);
8646 if (!U) return Align;
8647
8648 switch (getOpcode(U)) {
8649 default: break;
8650 case Instruction::BitCast:
8651 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8652 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008653 // If all indexes are zero, it is just the alignment of the base pointer.
8654 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00008655 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00008656 if (!isa<Constant>(*i) ||
8657 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008658 AllZeroOperands = false;
8659 break;
8660 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008661
8662 if (AllZeroOperands) {
8663 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008664 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008665 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008666 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008667 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008668 }
8669
8670 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8671 // If there is a large requested alignment and we can, bump up the alignment
8672 // of the global.
8673 if (!GV->isDeclaration()) {
8674 GV->setAlignment(PrefAlign);
8675 Align = PrefAlign;
8676 }
8677 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8678 // If there is a requested alignment and if this is an alloca, round up. We
8679 // don't do this for malloc, because some systems can't respect the request.
8680 if (isa<AllocaInst>(AI)) {
8681 AI->setAlignment(PrefAlign);
8682 Align = PrefAlign;
8683 }
8684 }
8685
8686 return Align;
8687}
8688
8689/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8690/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8691/// and it is more than the alignment of the ultimate object, see if we can
8692/// increase the alignment of the ultimate object, making this check succeed.
8693unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8694 unsigned PrefAlign) {
8695 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8696 sizeof(PrefAlign) * CHAR_BIT;
8697 APInt Mask = APInt::getAllOnesValue(BitWidth);
8698 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8699 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8700 unsigned TrailZ = KnownZero.countTrailingOnes();
8701 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8702
8703 if (PrefAlign > Align)
8704 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8705
8706 // We don't need to make any adjustment.
8707 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008708}
8709
Chris Lattnerf497b022008-01-13 23:50:23 +00008710Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008711 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8712 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008713 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8714 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8715
8716 if (CopyAlign < MinAlign) {
8717 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8718 return MI;
8719 }
8720
8721 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8722 // load/store.
8723 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8724 if (MemOpLength == 0) return 0;
8725
Chris Lattner37ac6082008-01-14 00:28:35 +00008726 // Source and destination pointer types are always "i8*" for intrinsic. See
8727 // if the size is something we can handle with a single primitive load/store.
8728 // A single load+store correctly handles overlapping memory in the memmove
8729 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008730 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008731 if (Size == 0) return MI; // Delete this mem transfer.
8732
8733 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008734 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008735
Chris Lattner37ac6082008-01-14 00:28:35 +00008736 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008737 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008738
8739 // Memcpy forces the use of i8* for the source and destination. That means
8740 // that if you're using memcpy to move one double around, you'll get a cast
8741 // from double* to i8*. We'd much rather use a double load+store rather than
8742 // an i64 load+store, here because this improves the odds that the source or
8743 // dest address will be promotable. See if we can find a better type than the
8744 // integer datatype.
8745 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8746 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8747 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8748 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8749 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00008750 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00008751 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8752 if (STy->getNumElements() == 1)
8753 SrcETy = STy->getElementType(0);
8754 else
8755 break;
8756 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8757 if (ATy->getNumElements() == 1)
8758 SrcETy = ATy->getElementType();
8759 else
8760 break;
8761 } else
8762 break;
8763 }
8764
Dan Gohman8f8e2692008-05-23 01:52:21 +00008765 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00008766 NewPtrTy = PointerType::getUnqual(SrcETy);
8767 }
8768 }
8769
8770
Chris Lattnerf497b022008-01-13 23:50:23 +00008771 // If the memcpy/memmove provides better alignment info than we can
8772 // infer, use it.
8773 SrcAlign = std::max(SrcAlign, CopyAlign);
8774 DstAlign = std::max(DstAlign, CopyAlign);
8775
8776 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8777 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008778 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8779 InsertNewInstBefore(L, *MI);
8780 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8781
8782 // Set the size of the copy to 0, it will be deleted on the next iteration.
8783 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8784 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008785}
Chris Lattner3d69f462004-03-12 05:52:32 +00008786
Chris Lattner69ea9d22008-04-30 06:39:11 +00008787Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8788 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8789 if (MI->getAlignment()->getZExtValue() < Alignment) {
8790 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8791 return MI;
8792 }
8793
8794 // Extract the length and alignment and fill if they are constant.
8795 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8796 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8797 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8798 return 0;
8799 uint64_t Len = LenC->getZExtValue();
8800 Alignment = MI->getAlignment()->getZExtValue();
8801
8802 // If the length is zero, this is a no-op
8803 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8804
8805 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8806 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8807 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8808
8809 Value *Dest = MI->getDest();
8810 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8811
8812 // Alignment 0 is identity for alignment 1 for memset, but not store.
8813 if (Alignment == 0) Alignment = 1;
8814
8815 // Extract the fill value and store.
8816 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8817 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8818 Alignment), *MI);
8819
8820 // Set the size of the copy to 0, it will be deleted on the next iteration.
8821 MI->setLength(Constant::getNullValue(LenC->getType()));
8822 return MI;
8823 }
8824
8825 return 0;
8826}
8827
8828
Chris Lattner8b0ea312006-01-13 20:11:04 +00008829/// visitCallInst - CallInst simplification. This mostly only handles folding
8830/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8831/// the heavy lifting.
8832///
Chris Lattner9fe38862003-06-19 17:00:31 +00008833Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008834 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8835 if (!II) return visitCallSite(&CI);
8836
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008837 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8838 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008839 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008840 bool Changed = false;
8841
8842 // memmove/cpy/set of zero bytes is a noop.
8843 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8844 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8845
Chris Lattner35b9e482004-10-12 04:52:52 +00008846 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008847 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008848 // Replace the instruction with just byte operations. We would
8849 // transform other cases to loads/stores, but we don't know if
8850 // alignment is sufficient.
8851 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008852 }
8853
Chris Lattner35b9e482004-10-12 04:52:52 +00008854 // If we have a memmove and the source operation is a constant global,
8855 // then the source and dest pointers can't alias, so we can change this
8856 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008857 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008858 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8859 if (GVSrc->isConstant()) {
8860 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008861 Intrinsic::ID MemCpyID;
8862 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8863 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008864 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008865 MemCpyID = Intrinsic::memcpy_i64;
8866 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008867 Changed = true;
8868 }
Chris Lattnera935db82008-05-28 05:30:41 +00008869
8870 // memmove(x,x,size) -> noop.
8871 if (MMI->getSource() == MMI->getDest())
8872 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00008873 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008874
Chris Lattner95a959d2006-03-06 20:18:44 +00008875 // If we can determine a pointer alignment that is bigger than currently
8876 // set, update the alignment.
8877 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008878 if (Instruction *I = SimplifyMemTransfer(MI))
8879 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008880 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8881 if (Instruction *I = SimplifyMemSet(MSI))
8882 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008883 }
8884
Chris Lattner8b0ea312006-01-13 20:11:04 +00008885 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00008886 }
8887
8888 switch (II->getIntrinsicID()) {
8889 default: break;
8890 case Intrinsic::bswap:
8891 // bswap(bswap(x)) -> x
8892 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8893 if (Operand->getIntrinsicID() == Intrinsic::bswap)
8894 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8895 break;
8896 case Intrinsic::ppc_altivec_lvx:
8897 case Intrinsic::ppc_altivec_lvxl:
8898 case Intrinsic::x86_sse_loadu_ps:
8899 case Intrinsic::x86_sse2_loadu_pd:
8900 case Intrinsic::x86_sse2_loadu_dq:
8901 // Turn PPC lvx -> load if the pointer is known aligned.
8902 // Turn X86 loadups -> load if the pointer is known aligned.
8903 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8904 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8905 PointerType::getUnqual(II->getType()),
8906 CI);
8907 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00008908 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008909 break;
8910 case Intrinsic::ppc_altivec_stvx:
8911 case Intrinsic::ppc_altivec_stvxl:
8912 // Turn stvx -> store if the pointer is known aligned.
8913 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8914 const Type *OpPtrTy =
8915 PointerType::getUnqual(II->getOperand(1)->getType());
8916 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8917 return new StoreInst(II->getOperand(1), Ptr);
8918 }
8919 break;
8920 case Intrinsic::x86_sse_storeu_ps:
8921 case Intrinsic::x86_sse2_storeu_pd:
8922 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00008923 // Turn X86 storeu -> store if the pointer is known aligned.
8924 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8925 const Type *OpPtrTy =
8926 PointerType::getUnqual(II->getOperand(2)->getType());
8927 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8928 return new StoreInst(II->getOperand(2), Ptr);
8929 }
8930 break;
8931
8932 case Intrinsic::x86_sse_cvttss2si: {
8933 // These intrinsics only demands the 0th element of its input vector. If
8934 // we can simplify the input based on that, do so now.
8935 uint64_t UndefElts;
8936 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8937 UndefElts)) {
8938 II->setOperand(1, V);
8939 return II;
8940 }
8941 break;
8942 }
8943
8944 case Intrinsic::ppc_altivec_vperm:
8945 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8946 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8947 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00008948
Chris Lattner0521e3c2008-06-18 04:33:20 +00008949 // Check that all of the elements are integer constants or undefs.
8950 bool AllEltsOk = true;
8951 for (unsigned i = 0; i != 16; ++i) {
8952 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8953 !isa<UndefValue>(Mask->getOperand(i))) {
8954 AllEltsOk = false;
8955 break;
8956 }
8957 }
8958
8959 if (AllEltsOk) {
8960 // Cast the input vectors to byte vectors.
8961 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8962 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8963 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008964
Chris Lattner0521e3c2008-06-18 04:33:20 +00008965 // Only extract each element once.
8966 Value *ExtractedElts[32];
8967 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8968
Chris Lattnere2ed0572006-04-06 19:19:17 +00008969 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00008970 if (isa<UndefValue>(Mask->getOperand(i)))
8971 continue;
8972 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8973 Idx &= 31; // Match the hardware behavior.
8974
8975 if (ExtractedElts[Idx] == 0) {
8976 Instruction *Elt =
8977 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8978 InsertNewInstBefore(Elt, CI);
8979 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00008980 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00008981
Chris Lattner0521e3c2008-06-18 04:33:20 +00008982 // Insert this value into the result vector.
8983 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8984 i, "tmp");
8985 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008986 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008987 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008988 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008989 }
8990 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00008991
Chris Lattner0521e3c2008-06-18 04:33:20 +00008992 case Intrinsic::stackrestore: {
8993 // If the save is right next to the restore, remove the restore. This can
8994 // happen when variable allocas are DCE'd.
8995 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8996 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8997 BasicBlock::iterator BI = SS;
8998 if (&*++BI == II)
8999 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009000 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009001 }
9002
9003 // Scan down this block to see if there is another stack restore in the
9004 // same block without an intervening call/alloca.
9005 BasicBlock::iterator BI = II;
9006 TerminatorInst *TI = II->getParent()->getTerminator();
9007 bool CannotRemove = false;
9008 for (++BI; &*BI != TI; ++BI) {
9009 if (isa<AllocaInst>(BI)) {
9010 CannotRemove = true;
9011 break;
9012 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009013 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9014 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9015 // If there is a stackrestore below this one, remove this one.
9016 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9017 return EraseInstFromFunction(CI);
9018 // Otherwise, ignore the intrinsic.
9019 } else {
9020 // If we found a non-intrinsic call, we can't remove the stack
9021 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009022 CannotRemove = true;
9023 break;
9024 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009025 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009026 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009027
9028 // If the stack restore is in a return/unwind block and if there are no
9029 // allocas or calls between the restore and the return, nuke the restore.
9030 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9031 return EraseInstFromFunction(CI);
9032 break;
9033 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009034 }
9035
Chris Lattner8b0ea312006-01-13 20:11:04 +00009036 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009037}
9038
9039// InvokeInst simplification
9040//
9041Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009042 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009043}
9044
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009045/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9046/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009047static bool isSafeToEliminateVarargsCast(const CallSite CS,
9048 const CastInst * const CI,
9049 const TargetData * const TD,
9050 const int ix) {
9051 if (!CI->isLosslessCast())
9052 return false;
9053
9054 // The size of ByVal arguments is derived from the type, so we
9055 // can't change to a type with a different size. If the size were
9056 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009057 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009058 return true;
9059
9060 const Type* SrcTy =
9061 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9062 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9063 if (!SrcTy->isSized() || !DstTy->isSized())
9064 return false;
9065 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9066 return false;
9067 return true;
9068}
9069
Chris Lattnera44d8a22003-10-07 22:32:43 +00009070// visitCallSite - Improvements for call and invoke instructions.
9071//
9072Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009073 bool Changed = false;
9074
9075 // If the callee is a constexpr cast of a function, attempt to move the cast
9076 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009077 if (transformConstExprCastCall(CS)) return 0;
9078
Chris Lattner6c266db2003-10-07 22:54:13 +00009079 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009080
Chris Lattner08b22ec2005-05-13 07:09:09 +00009081 if (Function *CalleeF = dyn_cast<Function>(Callee))
9082 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9083 Instruction *OldCall = CS.getInstruction();
9084 // If the call and callee calling conventions don't match, this call must
9085 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009086 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009087 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9088 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009089 if (!OldCall->use_empty())
9090 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9091 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9092 return EraseInstFromFunction(*OldCall);
9093 return 0;
9094 }
9095
Chris Lattner17be6352004-10-18 02:59:09 +00009096 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9097 // This instruction is not reachable, just remove it. We insert a store to
9098 // undef so that we know that this code is not reachable, despite the fact
9099 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009100 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009101 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009102 CS.getInstruction());
9103
9104 if (!CS.getInstruction()->use_empty())
9105 CS.getInstruction()->
9106 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9107
9108 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9109 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009110 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9111 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009112 }
Chris Lattner17be6352004-10-18 02:59:09 +00009113 return EraseInstFromFunction(*CS.getInstruction());
9114 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009115
Duncan Sandscdb6d922007-09-17 10:26:40 +00009116 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9117 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9118 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9119 return transformCallThroughTrampoline(CS);
9120
Chris Lattner6c266db2003-10-07 22:54:13 +00009121 const PointerType *PTy = cast<PointerType>(Callee->getType());
9122 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9123 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009124 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009125 // See if we can optimize any arguments passed through the varargs area of
9126 // the call.
9127 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009128 E = CS.arg_end(); I != E; ++I, ++ix) {
9129 CastInst *CI = dyn_cast<CastInst>(*I);
9130 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9131 *I = CI->getOperand(0);
9132 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009133 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009134 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009135 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009136
Duncan Sandsf0c33542007-12-19 21:13:37 +00009137 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009138 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009139 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009140 Changed = true;
9141 }
9142
Chris Lattner6c266db2003-10-07 22:54:13 +00009143 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009144}
9145
Chris Lattner9fe38862003-06-19 17:00:31 +00009146// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9147// attempt to move the cast to the arguments of the call/invoke.
9148//
9149bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9150 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9151 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009152 if (CE->getOpcode() != Instruction::BitCast ||
9153 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009154 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009155 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009156 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009157 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009158
9159 // Okay, this is a cast from a function to a different type. Unless doing so
9160 // would cause a type conversion of one of our arguments, change this call to
9161 // be a direct call with arguments casted to the appropriate types.
9162 //
9163 const FunctionType *FT = Callee->getFunctionType();
9164 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009165 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009166
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009167 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009168 return false; // TODO: Handle multiple return values.
9169
Chris Lattnerf78616b2004-01-14 06:06:08 +00009170 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009171 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009172 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009173 // Conversion is ok if changing from one pointer type to another or from
9174 // a pointer to an integer of the same size.
9175 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00009176 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00009177 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009178
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009179 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009180 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009181 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009182 return false; // Cannot transform this return value.
9183
Chris Lattner58d74912008-03-12 17:45:29 +00009184 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009185 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009186 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009187 return false; // Attribute not compatible with transformed value.
9188 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009189
Chris Lattnerf78616b2004-01-14 06:06:08 +00009190 // If the callsite is an invoke instruction, and the return value is used by
9191 // a PHI node in a successor, we cannot change the return type of the call
9192 // because there is no place to put the cast instruction (without breaking
9193 // the critical edge). Bail out in this case.
9194 if (!Caller->use_empty())
9195 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9196 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9197 UI != E; ++UI)
9198 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9199 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009200 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009201 return false;
9202 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009203
9204 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9205 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009206
Chris Lattner9fe38862003-06-19 17:00:31 +00009207 CallSite::arg_iterator AI = CS.arg_begin();
9208 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9209 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009210 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009211
9212 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009213 return false; // Cannot transform this parameter value.
9214
Devang Patel19c87462008-09-26 22:53:05 +00009215 if (CallerPAL.getParamAttributes(i + 1)
9216 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00009217 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009218
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009219 // Converting from one pointer type to another or between a pointer and an
9220 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00009221 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009222 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9223 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00009224 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009225 }
9226
9227 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009228 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009229 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009230
Chris Lattner58d74912008-03-12 17:45:29 +00009231 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9232 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009233 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009234 // won't be dropping them. Check that these extra arguments have attributes
9235 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009236 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9237 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009238 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00009239 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00009240 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00009241 return false;
9242 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009243
Chris Lattner9fe38862003-06-19 17:00:31 +00009244 // Okay, we decided that this is a safe thing to do: go ahead and start
9245 // inserting cast instructions as necessary...
9246 std::vector<Value*> Args;
9247 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00009248 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009249 attrVec.reserve(NumCommonArgs);
9250
9251 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009252 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009253
9254 // If the return value is not being used, the type may not be compatible
9255 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00009256 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009257
9258 // Add the new return attributes.
9259 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00009260 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009261
9262 AI = CS.arg_begin();
9263 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9264 const Type *ParamTy = FT->getParamType(i);
9265 if ((*AI)->getType() == ParamTy) {
9266 Args.push_back(*AI);
9267 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009268 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009269 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009270 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009271 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009272 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009273
9274 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009275 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009276 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009277 }
9278
9279 // If the function takes more arguments than the call was taking, add them
9280 // now...
9281 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9282 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9283
9284 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009285 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009286 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009287 cerr << "WARNING: While resolving call to function '"
9288 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009289 } else {
9290 // Add all of the arguments in their promoted form to the arg list...
9291 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9292 const Type *PTy = getPromotedType((*AI)->getType());
9293 if (PTy != (*AI)->getType()) {
9294 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009295 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9296 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009297 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009298 InsertNewInstBefore(Cast, *Caller);
9299 Args.push_back(Cast);
9300 } else {
9301 Args.push_back(*AI);
9302 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009303
Duncan Sandse1e520f2008-01-13 08:02:44 +00009304 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009305 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009306 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00009307 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009308 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009309 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009310
Devang Patel19c87462008-09-26 22:53:05 +00009311 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9312 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9313
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009314 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009315 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009316
Devang Patel05988662008-09-25 21:00:45 +00009317 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009318
Chris Lattner9fe38862003-06-19 17:00:31 +00009319 Instruction *NC;
9320 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009321 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009322 Args.begin(), Args.end(),
9323 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009324 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009325 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009326 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009327 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9328 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009329 CallInst *CI = cast<CallInst>(Caller);
9330 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009331 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009332 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009333 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009334 }
9335
Chris Lattner6934a042007-02-11 01:23:03 +00009336 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009337 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009338 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009339 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009340 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009341 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009342 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009343
9344 // If this is an invoke instruction, we should insert it after the first
9345 // non-phi, instruction in the normal successor block.
9346 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009347 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009348 InsertNewInstBefore(NC, *I);
9349 } else {
9350 // Otherwise, it's a call, just insert cast right after the call instr
9351 InsertNewInstBefore(NC, *Caller);
9352 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009353 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009354 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009355 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009356 }
9357 }
9358
9359 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9360 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009361 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009362 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009363 return true;
9364}
9365
Duncan Sandscdb6d922007-09-17 10:26:40 +00009366// transformCallThroughTrampoline - Turn a call to a function created by the
9367// init_trampoline intrinsic into a direct call to the underlying function.
9368//
9369Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9370 Value *Callee = CS.getCalledValue();
9371 const PointerType *PTy = cast<PointerType>(Callee->getType());
9372 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00009373 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009374
9375 // If the call already has the 'nest' attribute somewhere then give up -
9376 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00009377 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009378 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009379
9380 IntrinsicInst *Tramp =
9381 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9382
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009383 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009384 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9385 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9386
Devang Patel05988662008-09-25 21:00:45 +00009387 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00009388 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009389 unsigned NestIdx = 1;
9390 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00009391 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009392
9393 // Look for a parameter marked with the 'nest' attribute.
9394 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9395 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00009396 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009397 // Record the parameter type and any other attributes.
9398 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00009399 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009400 break;
9401 }
9402
9403 if (NestTy) {
9404 Instruction *Caller = CS.getInstruction();
9405 std::vector<Value*> NewArgs;
9406 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9407
Devang Patel05988662008-09-25 21:00:45 +00009408 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00009409 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009410
Duncan Sandscdb6d922007-09-17 10:26:40 +00009411 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009412 // mean appending it. Likewise for attributes.
9413
Devang Patel19c87462008-09-26 22:53:05 +00009414 // Add any result attributes.
9415 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00009416 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009417
Duncan Sandscdb6d922007-09-17 10:26:40 +00009418 {
9419 unsigned Idx = 1;
9420 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9421 do {
9422 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009423 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009424 Value *NestVal = Tramp->getOperand(3);
9425 if (NestVal->getType() != NestTy)
9426 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9427 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00009428 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009429 }
9430
9431 if (I == E)
9432 break;
9433
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009434 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009435 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +00009436 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009437 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +00009438 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009439
9440 ++Idx, ++I;
9441 } while (1);
9442 }
9443
Devang Patel19c87462008-09-26 22:53:05 +00009444 // Add any function attributes.
9445 if (Attributes Attr = Attrs.getFnAttributes())
9446 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9447
Duncan Sandscdb6d922007-09-17 10:26:40 +00009448 // The trampoline may have been bitcast to a bogus type (FTy).
9449 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009450 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009451
Duncan Sandscdb6d922007-09-17 10:26:40 +00009452 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009453 NewTypes.reserve(FTy->getNumParams()+1);
9454
Duncan Sandscdb6d922007-09-17 10:26:40 +00009455 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009456 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009457 {
9458 unsigned Idx = 1;
9459 FunctionType::param_iterator I = FTy->param_begin(),
9460 E = FTy->param_end();
9461
9462 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009463 if (Idx == NestIdx)
9464 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009465 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009466
9467 if (I == E)
9468 break;
9469
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009470 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009471 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009472
9473 ++Idx, ++I;
9474 } while (1);
9475 }
9476
9477 // Replace the trampoline call with a direct call. Let the generic
9478 // code sort out any function type mismatches.
9479 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009480 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009481 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9482 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +00009483 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009484
9485 Instruction *NewCaller;
9486 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009487 NewCaller = InvokeInst::Create(NewCallee,
9488 II->getNormalDest(), II->getUnwindDest(),
9489 NewArgs.begin(), NewArgs.end(),
9490 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009491 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009492 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009493 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009494 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9495 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009496 if (cast<CallInst>(Caller)->isTailCall())
9497 cast<CallInst>(NewCaller)->setTailCall();
9498 cast<CallInst>(NewCaller)->
9499 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009500 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009501 }
9502 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9503 Caller->replaceAllUsesWith(NewCaller);
9504 Caller->eraseFromParent();
9505 RemoveFromWorkList(Caller);
9506 return 0;
9507 }
9508 }
9509
9510 // Replace the trampoline call with a direct call. Since there is no 'nest'
9511 // parameter, there is no need to adjust the argument list. Let the generic
9512 // code sort out any function type mismatches.
9513 Constant *NewCallee =
9514 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9515 CS.setCalledFunction(NewCallee);
9516 return CS.getInstruction();
9517}
9518
Chris Lattner7da52b22006-11-01 04:51:18 +00009519/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9520/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9521/// and a single binop.
9522Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9523 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009524 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9525 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009526 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009527 Value *LHSVal = FirstInst->getOperand(0);
9528 Value *RHSVal = FirstInst->getOperand(1);
9529
9530 const Type *LHSType = LHSVal->getType();
9531 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009532
9533 // Scan to see if all operands are the same opcode, all have one use, and all
9534 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009535 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009536 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009537 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009538 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009539 // types or GEP's with different index types.
9540 I->getOperand(0)->getType() != LHSType ||
9541 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009542 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009543
9544 // If they are CmpInst instructions, check their predicates
9545 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9546 if (cast<CmpInst>(I)->getPredicate() !=
9547 cast<CmpInst>(FirstInst)->getPredicate())
9548 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009549
9550 // Keep track of which operand needs a phi node.
9551 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9552 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009553 }
9554
Chris Lattner53738a42006-11-08 19:42:28 +00009555 // Otherwise, this is safe to transform, determine if it is profitable.
9556
9557 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9558 // Indexes are often folded into load/store instructions, so we don't want to
9559 // hide them behind a phi.
9560 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9561 return 0;
9562
Chris Lattner7da52b22006-11-01 04:51:18 +00009563 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009564 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009565 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009566 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009567 NewLHS = PHINode::Create(LHSType,
9568 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009569 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9570 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009571 InsertNewInstBefore(NewLHS, PN);
9572 LHSVal = NewLHS;
9573 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009574
9575 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009576 NewRHS = PHINode::Create(RHSType,
9577 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009578 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9579 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009580 InsertNewInstBefore(NewRHS, PN);
9581 RHSVal = NewRHS;
9582 }
9583
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009584 // Add all operands to the new PHIs.
9585 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9586 if (NewLHS) {
9587 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9588 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9589 }
9590 if (NewRHS) {
9591 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9592 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9593 }
9594 }
9595
Chris Lattner7da52b22006-11-01 04:51:18 +00009596 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009597 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009598 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009599 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009600 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009601 else {
9602 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009603 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009604 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009605}
9606
Chris Lattner76c73142006-11-01 07:13:54 +00009607/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9608/// of the block that defines it. This means that it must be obvious the value
9609/// of the load is not changed from the point of the load to the end of the
9610/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009611///
9612/// Finally, it is safe, but not profitable, to sink a load targetting a
9613/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9614/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009615static bool isSafeToSinkLoad(LoadInst *L) {
9616 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9617
9618 for (++BBI; BBI != E; ++BBI)
9619 if (BBI->mayWriteToMemory())
9620 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009621
9622 // Check for non-address taken alloca. If not address-taken already, it isn't
9623 // profitable to do this xform.
9624 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9625 bool isAddressTaken = false;
9626 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9627 UI != E; ++UI) {
9628 if (isa<LoadInst>(UI)) continue;
9629 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9630 // If storing TO the alloca, then the address isn't taken.
9631 if (SI->getOperand(1) == AI) continue;
9632 }
9633 isAddressTaken = true;
9634 break;
9635 }
9636
9637 if (!isAddressTaken)
9638 return false;
9639 }
9640
Chris Lattner76c73142006-11-01 07:13:54 +00009641 return true;
9642}
9643
Chris Lattner9fe38862003-06-19 17:00:31 +00009644
Chris Lattnerbac32862004-11-14 19:13:23 +00009645// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9646// operator and they all are only used by the PHI, PHI together their
9647// inputs, and do the operation once, to the result of the PHI.
9648Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9649 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9650
9651 // Scan the instruction, looking for input operations that can be folded away.
9652 // If all input operands to the phi are the same instruction (e.g. a cast from
9653 // the same type or "+42") we can pull the operation through the PHI, reducing
9654 // code size and simplifying code.
9655 Constant *ConstantOp = 0;
9656 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009657 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009658 if (isa<CastInst>(FirstInst)) {
9659 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009660 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009661 // Can fold binop, compare or shift here if the RHS is a constant,
9662 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009663 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009664 if (ConstantOp == 0)
9665 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009666 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9667 isVolatile = LI->isVolatile();
9668 // We can't sink the load if the loaded value could be modified between the
9669 // load and the PHI.
9670 if (LI->getParent() != PN.getIncomingBlock(0) ||
9671 !isSafeToSinkLoad(LI))
9672 return 0;
Chris Lattner71042962008-07-08 17:18:32 +00009673
9674 // If the PHI is of volatile loads and the load block has multiple
9675 // successors, sinking it would remove a load of the volatile value from
9676 // the path through the other successor.
9677 if (isVolatile &&
9678 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9679 return 0;
9680
Chris Lattner9c080502006-11-01 07:43:41 +00009681 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009682 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009683 return FoldPHIArgBinOpIntoPHI(PN);
9684 // Can't handle general GEPs yet.
9685 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009686 } else {
9687 return 0; // Cannot fold this operation.
9688 }
9689
9690 // Check to see if all arguments are the same operation.
9691 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9692 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9693 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009694 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009695 return 0;
9696 if (CastSrcTy) {
9697 if (I->getOperand(0)->getType() != CastSrcTy)
9698 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009699 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009700 // We can't sink the load if the loaded value could be modified between
9701 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009702 if (LI->isVolatile() != isVolatile ||
9703 LI->getParent() != PN.getIncomingBlock(i) ||
9704 !isSafeToSinkLoad(LI))
9705 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009706
Chris Lattner71042962008-07-08 17:18:32 +00009707 // If the PHI is of volatile loads and the load block has multiple
9708 // successors, sinking it would remove a load of the volatile value from
9709 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +00009710 if (isVolatile &&
9711 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9712 return 0;
9713
9714
Chris Lattnerbac32862004-11-14 19:13:23 +00009715 } else if (I->getOperand(1) != ConstantOp) {
9716 return 0;
9717 }
9718 }
9719
9720 // Okay, they are all the same operation. Create a new PHI node of the
9721 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009722 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9723 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009724 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009725
9726 Value *InVal = FirstInst->getOperand(0);
9727 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009728
9729 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009730 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9731 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9732 if (NewInVal != InVal)
9733 InVal = 0;
9734 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9735 }
9736
9737 Value *PhiVal;
9738 if (InVal) {
9739 // The new PHI unions all of the same values together. This is really
9740 // common, so we handle it intelligently here for compile-time speed.
9741 PhiVal = InVal;
9742 delete NewPN;
9743 } else {
9744 InsertNewInstBefore(NewPN, PN);
9745 PhiVal = NewPN;
9746 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009747
Chris Lattnerbac32862004-11-14 19:13:23 +00009748 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009749 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009750 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009751 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009752 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009753 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009754 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009755 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009756 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9757
9758 // If this was a volatile load that we are merging, make sure to loop through
9759 // and mark all the input loads as non-volatile. If we don't do this, we will
9760 // insert a new volatile load and the old ones will not be deletable.
9761 if (isVolatile)
9762 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9763 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9764
9765 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009766}
Chris Lattnera1be5662002-05-02 17:06:02 +00009767
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009768/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9769/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009770static bool DeadPHICycle(PHINode *PN,
9771 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009772 if (PN->use_empty()) return true;
9773 if (!PN->hasOneUse()) return false;
9774
9775 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009776 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009777 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009778
9779 // Don't scan crazily complex things.
9780 if (PotentiallyDeadPHIs.size() == 16)
9781 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009782
9783 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9784 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009785
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009786 return false;
9787}
9788
Chris Lattnercf5008a2007-11-06 21:52:06 +00009789/// PHIsEqualValue - Return true if this phi node is always equal to
9790/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9791/// z = some value; x = phi (y, z); y = phi (x, z)
9792static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9793 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9794 // See if we already saw this PHI node.
9795 if (!ValueEqualPHIs.insert(PN))
9796 return true;
9797
9798 // Don't scan crazily complex things.
9799 if (ValueEqualPHIs.size() == 16)
9800 return false;
9801
9802 // Scan the operands to see if they are either phi nodes or are equal to
9803 // the value.
9804 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9805 Value *Op = PN->getIncomingValue(i);
9806 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9807 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9808 return false;
9809 } else if (Op != NonPhiInVal)
9810 return false;
9811 }
9812
9813 return true;
9814}
9815
9816
Chris Lattner473945d2002-05-06 18:06:38 +00009817// PHINode simplification
9818//
Chris Lattner7e708292002-06-25 16:13:24 +00009819Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009820 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009821 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009822
Owen Anderson7e057142006-07-10 22:03:18 +00009823 if (Value *V = PN.hasConstantValue())
9824 return ReplaceInstUsesWith(PN, V);
9825
Owen Anderson7e057142006-07-10 22:03:18 +00009826 // If all PHI operands are the same operation, pull them through the PHI,
9827 // reducing code size.
9828 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9829 PN.getIncomingValue(0)->hasOneUse())
9830 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9831 return Result;
9832
9833 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9834 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9835 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009836 if (PN.hasOneUse()) {
9837 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9838 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009839 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009840 PotentiallyDeadPHIs.insert(&PN);
9841 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9842 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9843 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009844
9845 // If this phi has a single use, and if that use just computes a value for
9846 // the next iteration of a loop, delete the phi. This occurs with unused
9847 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9848 // common case here is good because the only other things that catch this
9849 // are induction variable analysis (sometimes) and ADCE, which is only run
9850 // late.
9851 if (PHIUser->hasOneUse() &&
9852 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9853 PHIUser->use_back() == &PN) {
9854 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9855 }
9856 }
Owen Anderson7e057142006-07-10 22:03:18 +00009857
Chris Lattnercf5008a2007-11-06 21:52:06 +00009858 // We sometimes end up with phi cycles that non-obviously end up being the
9859 // same value, for example:
9860 // z = some value; x = phi (y, z); y = phi (x, z)
9861 // where the phi nodes don't necessarily need to be in the same block. Do a
9862 // quick check to see if the PHI node only contains a single non-phi value, if
9863 // so, scan to see if the phi cycle is actually equal to that value.
9864 {
9865 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9866 // Scan for the first non-phi operand.
9867 while (InValNo != NumOperandVals &&
9868 isa<PHINode>(PN.getIncomingValue(InValNo)))
9869 ++InValNo;
9870
9871 if (InValNo != NumOperandVals) {
9872 Value *NonPhiInVal = PN.getOperand(InValNo);
9873
9874 // Scan the rest of the operands to see if there are any conflicts, if so
9875 // there is no need to recursively scan other phis.
9876 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9877 Value *OpVal = PN.getIncomingValue(InValNo);
9878 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9879 break;
9880 }
9881
9882 // If we scanned over all operands, then we have one unique value plus
9883 // phi values. Scan PHI nodes to see if they all merge in each other or
9884 // the value.
9885 if (InValNo == NumOperandVals) {
9886 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9887 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9888 return ReplaceInstUsesWith(PN, NonPhiInVal);
9889 }
9890 }
9891 }
Chris Lattner60921c92003-12-19 05:58:40 +00009892 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009893}
9894
Reid Spencer17212df2006-12-12 09:18:51 +00009895static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9896 Instruction *InsertPoint,
9897 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009898 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9899 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009900 // We must cast correctly to the pointer type. Ensure that we
9901 // sign extend the integer value if it is smaller as this is
9902 // used for address computation.
9903 Instruction::CastOps opcode =
9904 (VTySize < PtrSize ? Instruction::SExt :
9905 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9906 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009907}
9908
Chris Lattnera1be5662002-05-02 17:06:02 +00009909
Chris Lattner7e708292002-06-25 16:13:24 +00009910Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009911 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009912 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009913 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009914 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009915 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009916
Chris Lattnere87597f2004-10-16 18:11:37 +00009917 if (isa<UndefValue>(GEP.getOperand(0)))
9918 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9919
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009920 bool HasZeroPointerIndex = false;
9921 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9922 HasZeroPointerIndex = C->isNullValue();
9923
9924 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009925 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009926
Chris Lattner28977af2004-04-05 01:30:19 +00009927 // Eliminate unneeded casts for indices.
9928 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009929
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009930 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009931 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9932 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009933 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009934 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009935 if (CI->getOpcode() == Instruction::ZExt ||
9936 CI->getOpcode() == Instruction::SExt) {
9937 const Type *SrcTy = CI->getOperand(0)->getType();
9938 // We can eliminate a cast from i32 to i64 iff the target
9939 // is a 32-bit pointer target.
9940 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9941 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +00009942 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +00009943 }
9944 }
9945 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009946 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +00009947 // to what we need. If narrower, sign-extend it to what we need.
9948 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009949 // insert it. This explicit cast can make subsequent optimizations more
9950 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +00009951 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009952 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009953 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009954 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +00009955 MadeChange = true;
9956 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009957 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9958 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009959 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009960 MadeChange = true;
9961 }
Dan Gohman4f833d42008-09-11 23:06:38 +00009962 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
9963 if (Constant *C = dyn_cast<Constant>(Op)) {
9964 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
9965 MadeChange = true;
9966 } else {
9967 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
9968 GEP);
9969 *i = Op;
9970 MadeChange = true;
9971 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009972 }
Chris Lattner28977af2004-04-05 01:30:19 +00009973 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009974 }
Chris Lattner28977af2004-04-05 01:30:19 +00009975 if (MadeChange) return &GEP;
9976
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009977 // If this GEP instruction doesn't move the pointer, and if the input operand
9978 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9979 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009980 if (GEP.hasAllZeroIndices()) {
9981 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9982 // If the bitcast is of an allocation, and the allocation will be
9983 // converted to match the type of the cast, don't touch this.
9984 if (isa<AllocationInst>(BCI->getOperand(0))) {
9985 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009986 if (Instruction *I = visitBitCast(*BCI)) {
9987 if (I != BCI) {
9988 I->takeName(BCI);
9989 BCI->getParent()->getInstList().insert(BCI, I);
9990 ReplaceInstUsesWith(*BCI, I);
9991 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009992 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009993 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009994 }
9995 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9996 }
9997 }
9998
Chris Lattner90ac28c2002-08-02 19:29:35 +00009999 // Combine Indices - If the source pointer to this getelementptr instruction
10000 // is a getelementptr instruction, combine the indices of the two
10001 // getelementptr instructions into a single instruction.
10002 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010003 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010004 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010005 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010006
10007 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010008 // Note that if our source is a gep chain itself that we wait for that
10009 // chain to be resolved before we perform this transformation. This
10010 // avoids us creating a TON of code in some cases.
10011 //
10012 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10013 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10014 return 0; // Wait until our source is folded to completion.
10015
Chris Lattner72588fc2007-02-15 22:48:32 +000010016 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010017
10018 // Find out whether the last index in the source GEP is a sequential idx.
10019 bool EndsWithSequential = false;
10020 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10021 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010022 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010023
Chris Lattner90ac28c2002-08-02 19:29:35 +000010024 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010025 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010026 // Replace: gep (gep %P, long B), long A, ...
10027 // With: T = long A+B; gep %P, T, ...
10028 //
Chris Lattner620ce142004-05-07 22:09:22 +000010029 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010030 if (SO1 == Constant::getNullValue(SO1->getType())) {
10031 Sum = GO1;
10032 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10033 Sum = SO1;
10034 } else {
10035 // If they aren't the same type, convert both to an integer of the
10036 // target's pointer size.
10037 if (SO1->getType() != GO1->getType()) {
10038 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010039 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010040 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010041 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010042 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010043 unsigned PS = TD->getPointerSizeInBits();
10044 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010045 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010046 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010047
Duncan Sands514ab342007-11-01 20:53:16 +000010048 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010049 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010050 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010051 } else {
10052 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010053 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10054 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010055 }
10056 }
10057 }
Chris Lattner620ce142004-05-07 22:09:22 +000010058 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10059 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10060 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010061 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010062 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010063 }
Chris Lattner28977af2004-04-05 01:30:19 +000010064 }
Chris Lattner620ce142004-05-07 22:09:22 +000010065
10066 // Recycle the GEP we already have if possible.
10067 if (SrcGEPOperands.size() == 2) {
10068 GEP.setOperand(0, SrcGEPOperands[0]);
10069 GEP.setOperand(1, Sum);
10070 return &GEP;
10071 } else {
10072 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10073 SrcGEPOperands.end()-1);
10074 Indices.push_back(Sum);
10075 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10076 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010077 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010078 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010079 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010080 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010081 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10082 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010083 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10084 }
10085
10086 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010087 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10088 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010089
Chris Lattner620ce142004-05-07 22:09:22 +000010090 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010091 // GEP of global variable. If all of the indices for this GEP are
10092 // constants, we can promote this to a constexpr instead of an instruction.
10093
10094 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010095 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010096 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10097 for (; I != E && isa<Constant>(*I); ++I)
10098 Indices.push_back(cast<Constant>(*I));
10099
10100 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010101 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10102 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010103
10104 // Replace all uses of the GEP with the new constexpr...
10105 return ReplaceInstUsesWith(GEP, CE);
10106 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010107 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010108 if (!isa<PointerType>(X->getType())) {
10109 // Not interesting. Source pointer must be a cast from pointer.
10110 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010111 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10112 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010113 //
10114 // This occurs when the program declares an array extern like "int X[];"
10115 //
10116 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10117 const PointerType *XTy = cast<PointerType>(X->getType());
10118 if (const ArrayType *XATy =
10119 dyn_cast<ArrayType>(XTy->getElementType()))
10120 if (const ArrayType *CATy =
10121 dyn_cast<ArrayType>(CPTy->getElementType()))
10122 if (CATy->getElementType() == XATy->getElementType()) {
10123 // At this point, we know that the cast source type is a pointer
10124 // to an array of the same type as the destination pointer
10125 // array. Because the array type is never stepped over (there
10126 // is a leading zero) we can fold the cast into this GEP.
10127 GEP.setOperand(0, X);
10128 return &GEP;
10129 }
10130 } else if (GEP.getNumOperands() == 2) {
10131 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010132 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10133 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010134 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10135 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10136 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +000010137 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10138 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010139 Value *Idx[2];
10140 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10141 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010142 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010143 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010144 // V and GEP are both pointer types --> BitCast
10145 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010146 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010147
10148 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010149 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010150 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010151 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010152
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010153 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010154 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +000010155 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010156
10157 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10158 // allow either a mul, shift, or constant here.
10159 Value *NewIdx = 0;
10160 ConstantInt *Scale = 0;
10161 if (ArrayEltSize == 1) {
10162 NewIdx = GEP.getOperand(1);
10163 Scale = ConstantInt::get(NewIdx->getType(), 1);
10164 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010165 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010166 Scale = CI;
10167 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10168 if (Inst->getOpcode() == Instruction::Shl &&
10169 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010170 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10171 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10172 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010173 NewIdx = Inst->getOperand(0);
10174 } else if (Inst->getOpcode() == Instruction::Mul &&
10175 isa<ConstantInt>(Inst->getOperand(1))) {
10176 Scale = cast<ConstantInt>(Inst->getOperand(1));
10177 NewIdx = Inst->getOperand(0);
10178 }
10179 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010180
Chris Lattner7835cdd2005-09-13 18:36:04 +000010181 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010182 // out, perform the transformation. Note, we don't know whether Scale is
10183 // signed or not. We'll use unsigned version of division/modulo
10184 // operation after making sure Scale doesn't have the sign bit set.
10185 if (Scale && Scale->getSExtValue() >= 0LL &&
10186 Scale->getZExtValue() % ArrayEltSize == 0) {
10187 Scale = ConstantInt::get(Scale->getType(),
10188 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010189 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010190 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010191 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010192 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010193 NewIdx = InsertNewInstBefore(Sc, GEP);
10194 }
10195
10196 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010197 Value *Idx[2];
10198 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10199 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010200 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010201 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010202 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10203 // The NewGEP must be pointer typed, so must the old one -> BitCast
10204 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010205 }
10206 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010207 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010208 }
10209
Chris Lattner8a2a3112001-12-14 16:52:21 +000010210 return 0;
10211}
10212
Chris Lattner0864acf2002-11-04 16:18:53 +000010213Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10214 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010215 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010216 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10217 const Type *NewTy =
10218 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010219 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010220
10221 // Create and insert the replacement instruction...
10222 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010223 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010224 else {
10225 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010226 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010227 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010228
10229 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010230
Chris Lattner0864acf2002-11-04 16:18:53 +000010231 // Scan to the end of the allocation instructions, to skip over a block of
10232 // allocas if possible...
10233 //
10234 BasicBlock::iterator It = New;
10235 while (isa<AllocationInst>(*It)) ++It;
10236
10237 // Now that I is pointing to the first non-allocation-inst in the block,
10238 // insert our getelementptr instruction...
10239 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010240 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010241 Value *Idx[2];
10242 Idx[0] = NullIdx;
10243 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010244 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10245 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010246
10247 // Now make everything use the getelementptr instead of the original
10248 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010249 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010250 } else if (isa<UndefValue>(AI.getArraySize())) {
10251 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010252 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010253 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010254
10255 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10256 // Note that we only do this for alloca's, because malloc should allocate and
10257 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010258 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010259 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010260 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10261
Chris Lattner0864acf2002-11-04 16:18:53 +000010262 return 0;
10263}
10264
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010265Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10266 Value *Op = FI.getOperand(0);
10267
Chris Lattner17be6352004-10-18 02:59:09 +000010268 // free undef -> unreachable.
10269 if (isa<UndefValue>(Op)) {
10270 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010271 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010272 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010273 return EraseInstFromFunction(FI);
10274 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010275
Chris Lattner6160e852004-02-28 04:57:37 +000010276 // If we have 'free null' delete the instruction. This can happen in stl code
10277 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010278 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010279 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010280
10281 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10282 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10283 FI.setOperand(0, CI->getOperand(0));
10284 return &FI;
10285 }
10286
10287 // Change free (gep X, 0,0,0,0) into free(X)
10288 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10289 if (GEPI->hasAllZeroIndices()) {
10290 AddToWorkList(GEPI);
10291 FI.setOperand(0, GEPI->getOperand(0));
10292 return &FI;
10293 }
10294 }
10295
10296 // Change free(malloc) into nothing, if the malloc has a single use.
10297 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10298 if (MI->hasOneUse()) {
10299 EraseInstFromFunction(FI);
10300 return EraseInstFromFunction(*MI);
10301 }
Chris Lattner6160e852004-02-28 04:57:37 +000010302
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010303 return 0;
10304}
10305
10306
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010307/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010308static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010309 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010310 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010311 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010312
Devang Patel99db6ad2007-10-18 19:52:32 +000010313 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10314 // Instead of loading constant c string, use corresponding integer value
10315 // directly if string length is small enough.
Evan Cheng0ff39b32008-06-30 07:31:25 +000010316 std::string Str;
10317 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010318 unsigned len = Str.length();
10319 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10320 unsigned numBits = Ty->getPrimitiveSizeInBits();
10321 // Replace LI with immediate integer store.
10322 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010323 APInt StrVal(numBits, 0);
10324 APInt SingleChar(numBits, 0);
10325 if (TD->isLittleEndian()) {
10326 for (signed i = len-1; i >= 0; i--) {
10327 SingleChar = (uint64_t) Str[i];
10328 StrVal = (StrVal << 8) | SingleChar;
10329 }
10330 } else {
10331 for (unsigned i = 0; i < len; i++) {
10332 SingleChar = (uint64_t) Str[i];
10333 StrVal = (StrVal << 8) | SingleChar;
10334 }
10335 // Append NULL at the end.
10336 SingleChar = 0;
10337 StrVal = (StrVal << 8) | SingleChar;
10338 }
10339 Value *NL = ConstantInt::get(StrVal);
10340 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010341 }
10342 }
10343 }
10344
Chris Lattnerb89e0712004-07-13 01:49:43 +000010345 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010346 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010347 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010348
Reid Spencer42230162007-01-22 05:51:25 +000010349 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010350 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010351 // If the source is an array, the code below will not succeed. Check to
10352 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10353 // constants.
10354 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10355 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10356 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010357 Value *Idxs[2];
10358 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10359 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010360 SrcTy = cast<PointerType>(CastOp->getType());
10361 SrcPTy = SrcTy->getElementType();
10362 }
10363
Reid Spencer42230162007-01-22 05:51:25 +000010364 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010365 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010366 // Do not allow turning this into a load of an integer, which is then
10367 // casted to a pointer, this pessimizes pointer analysis a lot.
10368 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010369 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10370 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010371
Chris Lattnerf9527852005-01-31 04:50:46 +000010372 // Okay, we are casting from one integer or pointer type to another of
10373 // the same size. Instead of casting the pointer before the load, cast
10374 // the result of the loaded value.
10375 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10376 CI->getName(),
10377 LI.isVolatile()),LI);
10378 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010379 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010380 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010381 }
10382 }
10383 return 0;
10384}
10385
Chris Lattnerc10aced2004-09-19 18:43:46 +000010386/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010387/// from this value cannot trap. If it is not obviously safe to load from the
10388/// specified pointer, we do a quick local scan of the basic block containing
10389/// ScanFrom, to determine if the address is already accessed.
10390static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010391 // If it is an alloca it is always safe to load from.
10392 if (isa<AllocaInst>(V)) return true;
10393
Duncan Sands46318cd2007-09-19 10:25:38 +000010394 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010395 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010396 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010397 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010398
10399 // Otherwise, be a little bit agressive by scanning the local block where we
10400 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010401 // from/to. If so, the previous load or store would have already trapped,
10402 // so there is no harm doing an extra load (also, CSE will later eliminate
10403 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010404 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10405
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010406 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010407 --BBI;
10408
Chris Lattner2de3fec2008-06-20 05:12:56 +000010409 // If we see a free or a call (which might do a free) the pointer could be
10410 // marked invalid.
10411 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10412 return false;
10413
Chris Lattner8a375202004-09-19 19:18:10 +000010414 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10415 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000010416 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000010417 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000010418 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010419
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010420 }
Chris Lattner8a375202004-09-19 19:18:10 +000010421 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010422}
10423
Chris Lattner833b8a42003-06-26 05:06:25 +000010424Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10425 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010426
Dan Gohman9941f742007-07-20 16:34:21 +000010427 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010428 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10429 if (KnownAlign >
10430 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10431 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010432 LI.setAlignment(KnownAlign);
10433
Chris Lattner37366c12005-05-01 04:24:53 +000010434 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010435 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010436 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010437 return Res;
10438
10439 // None of the following transforms are legal for volatile loads.
10440 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010441
Chris Lattner62f254d2005-09-12 22:00:15 +000010442 if (&LI.getParent()->front() != &LI) {
10443 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010444 // If the instruction immediately before this is a store to the same
10445 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010446 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10447 if (SI->getOperand(1) == LI.getOperand(0))
10448 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010449 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10450 if (LIB->getOperand(0) == LI.getOperand(0))
10451 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010452 }
Chris Lattner37366c12005-05-01 04:24:53 +000010453
Christopher Lambb15147e2007-12-29 07:56:53 +000010454 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10455 const Value *GEPI0 = GEPI->getOperand(0);
10456 // TODO: Consider a target hook for valid address spaces for this xform.
10457 if (isa<ConstantPointerNull>(GEPI0) &&
10458 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010459 // Insert a new store to null instruction before the load to indicate
10460 // that this code is not reachable. We do this instead of inserting
10461 // an unreachable instruction directly because we cannot modify the
10462 // CFG.
10463 new StoreInst(UndefValue::get(LI.getType()),
10464 Constant::getNullValue(Op->getType()), &LI);
10465 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10466 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010467 }
Chris Lattner37366c12005-05-01 04:24:53 +000010468
Chris Lattnere87597f2004-10-16 18:11:37 +000010469 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010470 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010471 // TODO: Consider a target hook for valid address spaces for this xform.
10472 if (isa<UndefValue>(C) || (C->isNullValue() &&
10473 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010474 // Insert a new store to null instruction before the load to indicate that
10475 // this code is not reachable. We do this instead of inserting an
10476 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010477 new StoreInst(UndefValue::get(LI.getType()),
10478 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010479 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010480 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010481
Chris Lattnere87597f2004-10-16 18:11:37 +000010482 // Instcombine load (constant global) into the value loaded.
10483 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010484 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010485 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010486
Chris Lattnere87597f2004-10-16 18:11:37 +000010487 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010488 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010489 if (CE->getOpcode() == Instruction::GetElementPtr) {
10490 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010491 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010492 if (Constant *V =
10493 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010494 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010495 if (CE->getOperand(0)->isNullValue()) {
10496 // Insert a new store to null instruction before the load to indicate
10497 // that this code is not reachable. We do this instead of inserting
10498 // an unreachable instruction directly because we cannot modify the
10499 // CFG.
10500 new StoreInst(UndefValue::get(LI.getType()),
10501 Constant::getNullValue(Op->getType()), &LI);
10502 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10503 }
10504
Reid Spencer3da59db2006-11-27 01:05:10 +000010505 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010506 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010507 return Res;
10508 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010509 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010510 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010511
10512 // If this load comes from anywhere in a constant global, and if the global
10513 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000010514 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Chris Lattner8d2e8882007-08-11 18:48:48 +000010515 if (GV->isConstant() && GV->hasInitializer()) {
10516 if (GV->getInitializer()->isNullValue())
10517 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10518 else if (isa<UndefValue>(GV->getInitializer()))
10519 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10520 }
10521 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010522
Chris Lattner37366c12005-05-01 04:24:53 +000010523 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010524 // Change select and PHI nodes to select values instead of addresses: this
10525 // helps alias analysis out a lot, allows many others simplifications, and
10526 // exposes redundancy in the code.
10527 //
10528 // Note that we cannot do the transformation unless we know that the
10529 // introduced loads cannot trap! Something like this is valid as long as
10530 // the condition is always false: load (select bool %C, int* null, int* %G),
10531 // but it would not be valid if we transformed it to load from null
10532 // unconditionally.
10533 //
10534 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10535 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010536 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10537 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010538 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010539 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010540 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010541 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010542 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010543 }
10544
Chris Lattner684fe212004-09-23 15:46:00 +000010545 // load (select (cond, null, P)) -> load P
10546 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10547 if (C->isNullValue()) {
10548 LI.setOperand(0, SI->getOperand(2));
10549 return &LI;
10550 }
10551
10552 // load (select (cond, P, null)) -> load P
10553 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10554 if (C->isNullValue()) {
10555 LI.setOperand(0, SI->getOperand(1));
10556 return &LI;
10557 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010558 }
10559 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010560 return 0;
10561}
10562
Reid Spencer55af2b52007-01-19 21:20:31 +000010563/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010564/// when possible.
10565static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10566 User *CI = cast<User>(SI.getOperand(1));
10567 Value *CastOp = CI->getOperand(0);
10568
10569 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10570 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10571 const Type *SrcPTy = SrcTy->getElementType();
10572
Reid Spencer42230162007-01-22 05:51:25 +000010573 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010574 // If the source is an array, the code below will not succeed. Check to
10575 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10576 // constants.
10577 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10578 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10579 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010580 Value* Idxs[2];
10581 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10582 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010583 SrcTy = cast<PointerType>(CastOp->getType());
10584 SrcPTy = SrcTy->getElementType();
10585 }
10586
Reid Spencer67f827c2007-01-20 23:35:48 +000010587 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10588 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10589 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010590
10591 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010592 // the same size. Instead of casting the pointer before
10593 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010594 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010595 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010596 Instruction::CastOps opcode = Instruction::BitCast;
10597 const Type* CastSrcTy = SIOp0->getType();
10598 const Type* CastDstTy = SrcPTy;
10599 if (isa<PointerType>(CastDstTy)) {
10600 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010601 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010602 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010603 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010604 opcode = Instruction::PtrToInt;
10605 }
10606 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010607 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010608 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010609 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010610 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010611 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010612 return new StoreInst(NewCast, CastOp);
10613 }
10614 }
10615 }
10616 return 0;
10617}
10618
Chris Lattner2f503e62005-01-31 05:36:43 +000010619Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10620 Value *Val = SI.getOperand(0);
10621 Value *Ptr = SI.getOperand(1);
10622
10623 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010624 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010625 ++NumCombined;
10626 return 0;
10627 }
Chris Lattner836692d2007-01-15 06:51:56 +000010628
10629 // If the RHS is an alloca with a single use, zapify the store, making the
10630 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010631 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010632 if (isa<AllocaInst>(Ptr)) {
10633 EraseInstFromFunction(SI);
10634 ++NumCombined;
10635 return 0;
10636 }
10637
10638 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10639 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10640 GEP->getOperand(0)->hasOneUse()) {
10641 EraseInstFromFunction(SI);
10642 ++NumCombined;
10643 return 0;
10644 }
10645 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010646
Dan Gohman9941f742007-07-20 16:34:21 +000010647 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010648 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10649 if (KnownAlign >
10650 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10651 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010652 SI.setAlignment(KnownAlign);
10653
Chris Lattner9ca96412006-02-08 03:25:32 +000010654 // Do really simple DSE, to catch cases where there are several consequtive
10655 // stores to the same location, separated by a few arithmetic operations. This
10656 // situation often occurs with bitfield accesses.
10657 BasicBlock::iterator BBI = &SI;
10658 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10659 --ScanInsts) {
10660 --BBI;
10661
10662 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10663 // Prev store isn't volatile, and stores to the same location?
10664 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10665 ++NumDeadStore;
10666 ++BBI;
10667 EraseInstFromFunction(*PrevSI);
10668 continue;
10669 }
10670 break;
10671 }
10672
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010673 // If this is a load, we have to stop. However, if the loaded value is from
10674 // the pointer we're loading and is producing the pointer we're storing,
10675 // then *this* store is dead (X = load P; store X -> P).
10676 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010677 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010678 EraseInstFromFunction(SI);
10679 ++NumCombined;
10680 return 0;
10681 }
10682 // Otherwise, this is a load from some other location. Stores before it
10683 // may not be dead.
10684 break;
10685 }
10686
Chris Lattner9ca96412006-02-08 03:25:32 +000010687 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010688 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010689 break;
10690 }
10691
10692
10693 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010694
10695 // store X, null -> turns into 'unreachable' in SimplifyCFG
10696 if (isa<ConstantPointerNull>(Ptr)) {
10697 if (!isa<UndefValue>(Val)) {
10698 SI.setOperand(0, UndefValue::get(Val->getType()));
10699 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010700 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010701 ++NumCombined;
10702 }
10703 return 0; // Do not modify these!
10704 }
10705
10706 // store undef, Ptr -> noop
10707 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010708 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010709 ++NumCombined;
10710 return 0;
10711 }
10712
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010713 // If the pointer destination is a cast, see if we can fold the cast into the
10714 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010715 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010716 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10717 return Res;
10718 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010719 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010720 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10721 return Res;
10722
Chris Lattner408902b2005-09-12 23:23:25 +000010723
10724 // If this store is the last instruction in the basic block, and if the block
10725 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010726 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010727 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010728 if (BI->isUnconditional())
10729 if (SimplifyStoreAtEndOfBlock(SI))
10730 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010731
Chris Lattner2f503e62005-01-31 05:36:43 +000010732 return 0;
10733}
10734
Chris Lattner3284d1f2007-04-15 00:07:55 +000010735/// SimplifyStoreAtEndOfBlock - Turn things like:
10736/// if () { *P = v1; } else { *P = v2 }
10737/// into a phi node with a store in the successor.
10738///
Chris Lattner31755a02007-04-15 01:02:18 +000010739/// Simplify things like:
10740/// *P = v1; if () { *P = v2; }
10741/// into a phi node with a store in the successor.
10742///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010743bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10744 BasicBlock *StoreBB = SI.getParent();
10745
10746 // Check to see if the successor block has exactly two incoming edges. If
10747 // so, see if the other predecessor contains a store to the same location.
10748 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010749 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010750
10751 // Determine whether Dest has exactly two predecessors and, if so, compute
10752 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010753 pred_iterator PI = pred_begin(DestBB);
10754 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010755 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010756 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010757 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010758 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010759 return false;
10760
10761 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010762 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010763 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010764 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010765 }
Chris Lattner31755a02007-04-15 01:02:18 +000010766 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010767 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000010768
10769 // Bail out if all the relevant blocks aren't distinct (this can happen,
10770 // for example, if SI is in an infinite loop)
10771 if (StoreBB == DestBB || OtherBB == DestBB)
10772 return false;
10773
Chris Lattner31755a02007-04-15 01:02:18 +000010774 // Verify that the other block ends in a branch and is not otherwise empty.
10775 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010776 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010777 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010778 return false;
10779
Chris Lattner31755a02007-04-15 01:02:18 +000010780 // If the other block ends in an unconditional branch, check for the 'if then
10781 // else' case. there is an instruction before the branch.
10782 StoreInst *OtherStore = 0;
10783 if (OtherBr->isUnconditional()) {
10784 // If this isn't a store, or isn't a store to the same location, bail out.
10785 --BBI;
10786 OtherStore = dyn_cast<StoreInst>(BBI);
10787 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10788 return false;
10789 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010790 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010791 // destinations is StoreBB, then we have the if/then case.
10792 if (OtherBr->getSuccessor(0) != StoreBB &&
10793 OtherBr->getSuccessor(1) != StoreBB)
10794 return false;
10795
10796 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010797 // if/then triangle. See if there is a store to the same ptr as SI that
10798 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010799 for (;; --BBI) {
10800 // Check to see if we find the matching store.
10801 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10802 if (OtherStore->getOperand(1) != SI.getOperand(1))
10803 return false;
10804 break;
10805 }
Eli Friedman6903a242008-06-13 22:02:12 +000010806 // If we find something that may be using or overwriting the stored
10807 // value, or if we run out of instructions, we can't do the xform.
10808 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000010809 BBI == OtherBB->begin())
10810 return false;
10811 }
10812
10813 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000010814 // make sure nothing reads or overwrites the stored value in
10815 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010816 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10817 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000010818 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000010819 return false;
10820 }
10821 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010822
Chris Lattner31755a02007-04-15 01:02:18 +000010823 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010824 Value *MergedVal = OtherStore->getOperand(0);
10825 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010826 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010827 PN->reserveOperandSpace(2);
10828 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010829 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10830 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010831 }
10832
10833 // Advance to a place where it is safe to insert the new store and
10834 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000010835 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010836 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10837 OtherStore->isVolatile()), *BBI);
10838
10839 // Nuke the old stores.
10840 EraseInstFromFunction(SI);
10841 EraseInstFromFunction(*OtherStore);
10842 ++NumCombined;
10843 return true;
10844}
10845
Chris Lattner2f503e62005-01-31 05:36:43 +000010846
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010847Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10848 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010849 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010850 BasicBlock *TrueDest;
10851 BasicBlock *FalseDest;
10852 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10853 !isa<Constant>(X)) {
10854 // Swap Destinations and condition...
10855 BI.setCondition(X);
10856 BI.setSuccessor(0, FalseDest);
10857 BI.setSuccessor(1, TrueDest);
10858 return &BI;
10859 }
10860
Reid Spencere4d87aa2006-12-23 06:05:41 +000010861 // Cannonicalize fcmp_one -> fcmp_oeq
10862 FCmpInst::Predicate FPred; Value *Y;
10863 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10864 TrueDest, FalseDest)))
10865 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10866 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10867 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010868 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010869 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10870 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010871 // Swap Destinations and condition...
10872 BI.setCondition(NewSCC);
10873 BI.setSuccessor(0, FalseDest);
10874 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010875 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010876 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010877 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010878 return &BI;
10879 }
10880
10881 // Cannonicalize icmp_ne -> icmp_eq
10882 ICmpInst::Predicate IPred;
10883 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10884 TrueDest, FalseDest)))
10885 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10886 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10887 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10888 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010889 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010890 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10891 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010892 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010893 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010894 BI.setSuccessor(0, FalseDest);
10895 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010896 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010897 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010898 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010899 return &BI;
10900 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010901
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010902 return 0;
10903}
Chris Lattner0864acf2002-11-04 16:18:53 +000010904
Chris Lattner46238a62004-07-03 00:26:11 +000010905Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10906 Value *Cond = SI.getCondition();
10907 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10908 if (I->getOpcode() == Instruction::Add)
10909 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10910 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10911 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010912 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010913 AddRHS));
10914 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010915 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010916 return &SI;
10917 }
10918 }
10919 return 0;
10920}
10921
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010922Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000010923 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010924
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000010925 if (!EV.hasIndices())
10926 return ReplaceInstUsesWith(EV, Agg);
10927
10928 if (Constant *C = dyn_cast<Constant>(Agg)) {
10929 if (isa<UndefValue>(C))
10930 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
10931
10932 if (isa<ConstantAggregateZero>(C))
10933 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
10934
10935 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
10936 // Extract the element indexed by the first index out of the constant
10937 Value *V = C->getOperand(*EV.idx_begin());
10938 if (EV.getNumIndices() > 1)
10939 // Extract the remaining indices out of the constant indexed by the
10940 // first index
10941 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
10942 else
10943 return ReplaceInstUsesWith(EV, V);
10944 }
10945 return 0; // Can't handle other constants
10946 }
10947 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
10948 // We're extracting from an insertvalue instruction, compare the indices
10949 const unsigned *exti, *exte, *insi, *inse;
10950 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
10951 exte = EV.idx_end(), inse = IV->idx_end();
10952 exti != exte && insi != inse;
10953 ++exti, ++insi) {
10954 if (*insi != *exti)
10955 // The insert and extract both reference distinctly different elements.
10956 // This means the extract is not influenced by the insert, and we can
10957 // replace the aggregate operand of the extract with the aggregate
10958 // operand of the insert. i.e., replace
10959 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10960 // %E = extractvalue { i32, { i32 } } %I, 0
10961 // with
10962 // %E = extractvalue { i32, { i32 } } %A, 0
10963 return ExtractValueInst::Create(IV->getAggregateOperand(),
10964 EV.idx_begin(), EV.idx_end());
10965 }
10966 if (exti == exte && insi == inse)
10967 // Both iterators are at the end: Index lists are identical. Replace
10968 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10969 // %C = extractvalue { i32, { i32 } } %B, 1, 0
10970 // with "i32 42"
10971 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
10972 if (exti == exte) {
10973 // The extract list is a prefix of the insert list. i.e. replace
10974 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10975 // %E = extractvalue { i32, { i32 } } %I, 1
10976 // with
10977 // %X = extractvalue { i32, { i32 } } %A, 1
10978 // %E = insertvalue { i32 } %X, i32 42, 0
10979 // by switching the order of the insert and extract (though the
10980 // insertvalue should be left in, since it may have other uses).
10981 Value *NewEV = InsertNewInstBefore(
10982 ExtractValueInst::Create(IV->getAggregateOperand(),
10983 EV.idx_begin(), EV.idx_end()),
10984 EV);
10985 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
10986 insi, inse);
10987 }
10988 if (insi == inse)
10989 // The insert list is a prefix of the extract list
10990 // We can simply remove the common indices from the extract and make it
10991 // operate on the inserted value instead of the insertvalue result.
10992 // i.e., replace
10993 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10994 // %E = extractvalue { i32, { i32 } } %I, 1, 0
10995 // with
10996 // %E extractvalue { i32 } { i32 42 }, 0
10997 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
10998 exti, exte);
10999 }
11000 // Can't simplify extracts from other values. Note that nested extracts are
11001 // already simplified implicitely by the above (extract ( extract (insert) )
11002 // will be translated into extract ( insert ( extract ) ) first and then just
11003 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011004 return 0;
11005}
11006
Chris Lattner220b0cf2006-03-05 00:22:33 +000011007/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11008/// is to leave as a vector operation.
11009static bool CheapToScalarize(Value *V, bool isConstant) {
11010 if (isa<ConstantAggregateZero>(V))
11011 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011012 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011013 if (isConstant) return true;
11014 // If all elts are the same, we can extract.
11015 Constant *Op0 = C->getOperand(0);
11016 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11017 if (C->getOperand(i) != Op0)
11018 return false;
11019 return true;
11020 }
11021 Instruction *I = dyn_cast<Instruction>(V);
11022 if (!I) return false;
11023
11024 // Insert element gets simplified to the inserted element or is deleted if
11025 // this is constant idx extract element and its a constant idx insertelt.
11026 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11027 isa<ConstantInt>(I->getOperand(2)))
11028 return true;
11029 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11030 return true;
11031 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11032 if (BO->hasOneUse() &&
11033 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11034 CheapToScalarize(BO->getOperand(1), isConstant)))
11035 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011036 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11037 if (CI->hasOneUse() &&
11038 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11039 CheapToScalarize(CI->getOperand(1), isConstant)))
11040 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011041
11042 return false;
11043}
11044
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011045/// Read and decode a shufflevector mask.
11046///
11047/// It turns undef elements into values that are larger than the number of
11048/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011049static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11050 unsigned NElts = SVI->getType()->getNumElements();
11051 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11052 return std::vector<unsigned>(NElts, 0);
11053 if (isa<UndefValue>(SVI->getOperand(2)))
11054 return std::vector<unsigned>(NElts, 2*NElts);
11055
11056 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011057 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000011058 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11059 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000011060 Result.push_back(NElts*2); // undef -> 8
11061 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000011062 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011063 return Result;
11064}
11065
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011066/// FindScalarElement - Given a vector and an element number, see if the scalar
11067/// value is already around as a register, for example if it were inserted then
11068/// extracted from the vector.
11069static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011070 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11071 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011072 unsigned Width = PTy->getNumElements();
11073 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011074 return UndefValue::get(PTy->getElementType());
11075
11076 if (isa<UndefValue>(V))
11077 return UndefValue::get(PTy->getElementType());
11078 else if (isa<ConstantAggregateZero>(V))
11079 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011080 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011081 return CP->getOperand(EltNo);
11082 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11083 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011084 if (!isa<ConstantInt>(III->getOperand(2)))
11085 return 0;
11086 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011087
11088 // If this is an insert to the element we are looking for, return the
11089 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011090 if (EltNo == IIElt)
11091 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011092
11093 // Otherwise, the insertelement doesn't modify the value, recurse on its
11094 // vector input.
11095 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011096 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000011097 unsigned InEl = getShuffleMask(SVI)[EltNo];
11098 if (InEl < Width)
11099 return FindScalarElement(SVI->getOperand(0), InEl);
11100 else if (InEl < Width*2)
11101 return FindScalarElement(SVI->getOperand(1), InEl - Width);
11102 else
11103 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011104 }
11105
11106 // Otherwise, we don't know.
11107 return 0;
11108}
11109
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011110Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000011111 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011112 if (isa<UndefValue>(EI.getOperand(0)))
11113 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11114
Dan Gohman07a96762007-07-16 14:29:03 +000011115 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011116 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11117 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11118
Reid Spencer9d6565a2007-02-15 02:26:10 +000011119 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000011120 // If vector val is constant with all elements the same, replace EI with
11121 // that element. When the elements are not identical, we cannot replace yet
11122 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000011123 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011124 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011125 if (C->getOperand(i) != op0) {
11126 op0 = 0;
11127 break;
11128 }
11129 if (op0)
11130 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011131 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011132
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011133 // If extracting a specified index from the vector, see if we can recursively
11134 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011135 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011136 unsigned IndexVal = IdxC->getZExtValue();
11137 unsigned VectorWidth =
11138 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11139
11140 // If this is extracting an invalid index, turn this into undef, to avoid
11141 // crashing the code below.
11142 if (IndexVal >= VectorWidth)
11143 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11144
Chris Lattner867b99f2006-10-05 06:55:50 +000011145 // This instruction only demands the single element from the input vector.
11146 // If the input vector has a single use, simplify it based on this use
11147 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011148 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011149 uint64_t UndefElts;
11150 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011151 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011152 UndefElts)) {
11153 EI.setOperand(0, V);
11154 return &EI;
11155 }
11156 }
11157
Reid Spencerb83eb642006-10-20 07:07:24 +000011158 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011159 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011160
11161 // If the this extractelement is directly using a bitcast from a vector of
11162 // the same number of elements, see if we can find the source element from
11163 // it. In this case, we will end up needing to bitcast the scalars.
11164 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11165 if (const VectorType *VT =
11166 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11167 if (VT->getNumElements() == VectorWidth)
11168 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11169 return new BitCastInst(Elt, EI.getType());
11170 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011171 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011172
Chris Lattner73fa49d2006-05-25 22:53:38 +000011173 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011174 if (I->hasOneUse()) {
11175 // Push extractelement into predecessor operation if legal and
11176 // profitable to do so
11177 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011178 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11179 if (CheapToScalarize(BO, isConstantElt)) {
11180 ExtractElementInst *newEI0 =
11181 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11182 EI.getName()+".lhs");
11183 ExtractElementInst *newEI1 =
11184 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11185 EI.getName()+".rhs");
11186 InsertNewInstBefore(newEI0, EI);
11187 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011188 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011189 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011190 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011191 unsigned AS =
11192 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011193 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11194 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011195 GetElementPtrInst *GEP =
11196 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011197 InsertNewInstBefore(GEP, EI);
11198 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011199 }
11200 }
11201 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11202 // Extracting the inserted element?
11203 if (IE->getOperand(2) == EI.getOperand(1))
11204 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11205 // If the inserted and extracted elements are constants, they must not
11206 // be the same value, extract from the pre-inserted value instead.
11207 if (isa<Constant>(IE->getOperand(2)) &&
11208 isa<Constant>(EI.getOperand(1))) {
11209 AddUsesToWorkList(EI);
11210 EI.setOperand(0, IE->getOperand(0));
11211 return &EI;
11212 }
11213 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11214 // If this is extracting an element from a shufflevector, figure out where
11215 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011216 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11217 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011218 Value *Src;
11219 if (SrcIdx < SVI->getType()->getNumElements())
11220 Src = SVI->getOperand(0);
11221 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11222 SrcIdx -= SVI->getType()->getNumElements();
11223 Src = SVI->getOperand(1);
11224 } else {
11225 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011226 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011227 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011228 }
11229 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011230 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011231 return 0;
11232}
11233
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011234/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11235/// elements from either LHS or RHS, return the shuffle mask and true.
11236/// Otherwise, return false.
11237static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11238 std::vector<Constant*> &Mask) {
11239 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11240 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011241 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011242
11243 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011244 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011245 return true;
11246 } else if (V == LHS) {
11247 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011248 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011249 return true;
11250 } else if (V == RHS) {
11251 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011252 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011253 return true;
11254 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11255 // If this is an insert of an extract from some other vector, include it.
11256 Value *VecOp = IEI->getOperand(0);
11257 Value *ScalarOp = IEI->getOperand(1);
11258 Value *IdxOp = IEI->getOperand(2);
11259
Chris Lattnerd929f062006-04-27 21:14:21 +000011260 if (!isa<ConstantInt>(IdxOp))
11261 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011262 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011263
11264 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11265 // Okay, we can handle this if the vector we are insertinting into is
11266 // transitively ok.
11267 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11268 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011269 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011270 return true;
11271 }
11272 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11273 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011274 EI->getOperand(0)->getType() == V->getType()) {
11275 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011276 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011277
11278 // This must be extracting from either LHS or RHS.
11279 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11280 // Okay, we can handle this if the vector we are insertinting into is
11281 // transitively ok.
11282 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11283 // If so, update the mask to reflect the inserted value.
11284 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011285 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011286 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011287 } else {
11288 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011289 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011290 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011291
11292 }
11293 return true;
11294 }
11295 }
11296 }
11297 }
11298 }
11299 // TODO: Handle shufflevector here!
11300
11301 return false;
11302}
11303
11304/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11305/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11306/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011307static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011308 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011309 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011310 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011311 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011312 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011313
11314 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011315 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011316 return V;
11317 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011318 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011319 return V;
11320 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11321 // If this is an insert of an extract from some other vector, include it.
11322 Value *VecOp = IEI->getOperand(0);
11323 Value *ScalarOp = IEI->getOperand(1);
11324 Value *IdxOp = IEI->getOperand(2);
11325
11326 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11327 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11328 EI->getOperand(0)->getType() == V->getType()) {
11329 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011330 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11331 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011332
11333 // Either the extracted from or inserted into vector must be RHSVec,
11334 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011335 if (EI->getOperand(0) == RHS || RHS == 0) {
11336 RHS = EI->getOperand(0);
11337 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011338 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011339 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011340 return V;
11341 }
11342
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011343 if (VecOp == RHS) {
11344 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011345 // Everything but the extracted element is replaced with the RHS.
11346 for (unsigned i = 0; i != NumElts; ++i) {
11347 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011348 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011349 }
11350 return V;
11351 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011352
11353 // If this insertelement is a chain that comes from exactly these two
11354 // vectors, return the vector and the effective shuffle.
11355 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11356 return EI->getOperand(0);
11357
Chris Lattnerefb47352006-04-15 01:39:45 +000011358 }
11359 }
11360 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011361 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011362
11363 // Otherwise, can't do anything fancy. Return an identity vector.
11364 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011365 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011366 return V;
11367}
11368
11369Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11370 Value *VecOp = IE.getOperand(0);
11371 Value *ScalarOp = IE.getOperand(1);
11372 Value *IdxOp = IE.getOperand(2);
11373
Chris Lattner599ded12007-04-09 01:11:16 +000011374 // Inserting an undef or into an undefined place, remove this.
11375 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11376 ReplaceInstUsesWith(IE, VecOp);
11377
Chris Lattnerefb47352006-04-15 01:39:45 +000011378 // If the inserted element was extracted from some other vector, and if the
11379 // indexes are constant, try to turn this into a shufflevector operation.
11380 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11381 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11382 EI->getOperand(0)->getType() == IE.getType()) {
11383 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011384 unsigned ExtractedIdx =
11385 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011386 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011387
11388 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11389 return ReplaceInstUsesWith(IE, VecOp);
11390
11391 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11392 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11393
11394 // If we are extracting a value from a vector, then inserting it right
11395 // back into the same place, just use the input vector.
11396 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11397 return ReplaceInstUsesWith(IE, VecOp);
11398
11399 // We could theoretically do this for ANY input. However, doing so could
11400 // turn chains of insertelement instructions into a chain of shufflevector
11401 // instructions, and right now we do not merge shufflevectors. As such,
11402 // only do this in a situation where it is clear that there is benefit.
11403 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11404 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11405 // the values of VecOp, except then one read from EIOp0.
11406 // Build a new shuffle mask.
11407 std::vector<Constant*> Mask;
11408 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011409 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011410 else {
11411 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011412 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011413 NumVectorElts));
11414 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011415 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011416 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011417 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011418 }
11419
11420 // If this insertelement isn't used by some other insertelement, turn it
11421 // (and any insertelements it points to), into one big shuffle.
11422 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11423 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011424 Value *RHS = 0;
11425 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11426 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11427 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011428 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011429 }
11430 }
11431 }
11432
11433 return 0;
11434}
11435
11436
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011437Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11438 Value *LHS = SVI.getOperand(0);
11439 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011440 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011441
11442 bool MadeChange = false;
11443
Chris Lattner867b99f2006-10-05 06:55:50 +000011444 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011445 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011446 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000011447
11448 uint64_t UndefElts;
11449 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
11450 uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
11451 if (VWidth <= 64 &&
Dan Gohman3139ff82008-09-11 22:47:57 +000011452 SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
11453 LHS = SVI.getOperand(0);
11454 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000011455 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000011456 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011457
Chris Lattner863bcff2006-05-25 23:48:38 +000011458 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11459 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11460 if (LHS == RHS || isa<UndefValue>(LHS)) {
11461 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011462 // shuffle(undef,undef,mask) -> undef.
11463 return ReplaceInstUsesWith(SVI, LHS);
11464 }
11465
Chris Lattner863bcff2006-05-25 23:48:38 +000011466 // Remap any references to RHS to use LHS.
11467 std::vector<Constant*> Elts;
11468 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011469 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011470 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011471 else {
11472 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000011473 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011474 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000011475 Elts.push_back(UndefValue::get(Type::Int32Ty));
11476 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011477 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000011478 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11479 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000011480 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011481 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011482 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011483 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011484 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011485 LHS = SVI.getOperand(0);
11486 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011487 MadeChange = true;
11488 }
11489
Chris Lattner7b2e27922006-05-26 00:29:06 +000011490 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011491 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011492
Chris Lattner863bcff2006-05-25 23:48:38 +000011493 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11494 if (Mask[i] >= e*2) continue; // Ignore undef values.
11495 // Is this an identity shuffle of the LHS value?
11496 isLHSID &= (Mask[i] == i);
11497
11498 // Is this an identity shuffle of the RHS value?
11499 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011500 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011501
Chris Lattner863bcff2006-05-25 23:48:38 +000011502 // Eliminate identity shuffles.
11503 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11504 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011505
Chris Lattner7b2e27922006-05-26 00:29:06 +000011506 // If the LHS is a shufflevector itself, see if we can combine it with this
11507 // one without producing an unusual shuffle. Here we are really conservative:
11508 // we are absolutely afraid of producing a shuffle mask not in the input
11509 // program, because the code gen may not be smart enough to turn a merged
11510 // shuffle into two specific shuffles: it may produce worse code. As such,
11511 // we only merge two shuffles if the result is one of the two input shuffle
11512 // masks. In this case, merging the shuffles just removes one instruction,
11513 // which we know is safe. This is good for things like turning:
11514 // (splat(splat)) -> splat.
11515 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11516 if (isa<UndefValue>(RHS)) {
11517 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11518
11519 std::vector<unsigned> NewMask;
11520 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11521 if (Mask[i] >= 2*e)
11522 NewMask.push_back(2*e);
11523 else
11524 NewMask.push_back(LHSMask[Mask[i]]);
11525
11526 // If the result mask is equal to the src shuffle or this shuffle mask, do
11527 // the replacement.
11528 if (NewMask == LHSMask || NewMask == Mask) {
11529 std::vector<Constant*> Elts;
11530 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11531 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011532 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011533 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011534 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011535 }
11536 }
11537 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11538 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011539 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011540 }
11541 }
11542 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011543
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011544 return MadeChange ? &SVI : 0;
11545}
11546
11547
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011548
Chris Lattnerea1c4542004-12-08 23:43:58 +000011549
11550/// TryToSinkInstruction - Try to move the specified instruction from its
11551/// current block into the beginning of DestBlock, which can only happen if it's
11552/// safe to move the instruction past all of the instructions between it and the
11553/// end of its block.
11554static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11555 assert(I->hasOneUse() && "Invariants didn't hold!");
11556
Chris Lattner108e9022005-10-27 17:13:11 +000011557 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011558 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11559 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011560
Chris Lattnerea1c4542004-12-08 23:43:58 +000011561 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011562 if (isa<AllocaInst>(I) && I->getParent() ==
11563 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011564 return false;
11565
Chris Lattner96a52a62004-12-09 07:14:34 +000011566 // We can only sink load instructions if there is nothing between the load and
11567 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011568 if (I->mayReadFromMemory()) {
11569 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011570 Scan != E; ++Scan)
11571 if (Scan->mayWriteToMemory())
11572 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011573 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011574
Dan Gohman02dea8b2008-05-23 21:05:58 +000011575 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000011576
Chris Lattner4bc5f802005-08-08 19:11:57 +000011577 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011578 ++NumSunkInst;
11579 return true;
11580}
11581
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011582
11583/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11584/// all reachable code to the worklist.
11585///
11586/// This has a couple of tricks to make the code faster and more powerful. In
11587/// particular, we constant fold and DCE instructions as we go, to avoid adding
11588/// them to the worklist (this significantly speeds up instcombine on code where
11589/// many instructions are dead or constant). Additionally, if we find a branch
11590/// whose condition is a known constant, we only visit the reachable successors.
11591///
11592static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011593 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011594 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011595 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000011596 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000011597 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011598
Chris Lattner2c7718a2007-03-23 19:17:18 +000011599 while (!Worklist.empty()) {
11600 BB = Worklist.back();
11601 Worklist.pop_back();
11602
11603 // We have now visited this block! If we've already been here, ignore it.
11604 if (!Visited.insert(BB)) continue;
11605
11606 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11607 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011608
Chris Lattner2c7718a2007-03-23 19:17:18 +000011609 // DCE instruction if trivially dead.
11610 if (isInstructionTriviallyDead(Inst)) {
11611 ++NumDeadInst;
11612 DOUT << "IC: DCE: " << *Inst;
11613 Inst->eraseFromParent();
11614 continue;
11615 }
11616
11617 // ConstantProp instruction if trivially constant.
11618 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11619 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11620 Inst->replaceAllUsesWith(C);
11621 ++NumConstProp;
11622 Inst->eraseFromParent();
11623 continue;
11624 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011625
Chris Lattner2c7718a2007-03-23 19:17:18 +000011626 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011627 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011628
11629 // Recursively visit successors. If this is a branch or switch on a
11630 // constant, only visit the reachable successor.
11631 TerminatorInst *TI = BB->getTerminator();
11632 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11633 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11634 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011635 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011636 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011637 continue;
11638 }
11639 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11640 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11641 // See if this is an explicit destination.
11642 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11643 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011644 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011645 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011646 continue;
11647 }
11648
11649 // Otherwise it is the default destination.
11650 Worklist.push_back(SI->getSuccessor(0));
11651 continue;
11652 }
11653 }
11654
11655 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11656 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011657 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011658}
11659
Chris Lattnerec9c3582007-03-03 02:04:50 +000011660bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011661 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011662 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011663
11664 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11665 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011666
Chris Lattnerb3d59702005-07-07 20:40:38 +000011667 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011668 // Do a depth-first traversal of the function, populate the worklist with
11669 // the reachable instructions. Ignore blocks that are not reachable. Keep
11670 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011671 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011672 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011673
Chris Lattnerb3d59702005-07-07 20:40:38 +000011674 // Do a quick scan over the function. If we find any blocks that are
11675 // unreachable, remove any instructions inside of them. This prevents
11676 // the instcombine code from having to deal with some bad special cases.
11677 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11678 if (!Visited.count(BB)) {
11679 Instruction *Term = BB->getTerminator();
11680 while (Term != BB->begin()) { // Remove instrs bottom-up
11681 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011682
Bill Wendlingb7427032006-11-26 09:46:52 +000011683 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011684 ++NumDeadInst;
11685
11686 if (!I->use_empty())
11687 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11688 I->eraseFromParent();
11689 }
11690 }
11691 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011692
Chris Lattnerdbab3862007-03-02 21:28:56 +000011693 while (!Worklist.empty()) {
11694 Instruction *I = RemoveOneFromWorkList();
11695 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011696
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011697 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011698 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011699 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011700 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011701 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011702 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011703
Bill Wendlingb7427032006-11-26 09:46:52 +000011704 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011705
11706 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011707 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011708 continue;
11709 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011710
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011711 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011712 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011713 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011714
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011715 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011716 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011717 ReplaceInstUsesWith(*I, C);
11718
Chris Lattner62b14df2002-09-02 04:59:56 +000011719 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011720 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011721 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011722 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011723 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011724
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000011725 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11726 // See if we can constant fold its operands.
11727 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11728 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11729 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11730 i->set(NewC);
11731 }
11732 }
11733 }
11734
Chris Lattnerea1c4542004-12-08 23:43:58 +000011735 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000011736 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011737 BasicBlock *BB = I->getParent();
11738 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11739 if (UserParent != BB) {
11740 bool UserIsSuccessor = false;
11741 // See if the user is one of our successors.
11742 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11743 if (*SI == UserParent) {
11744 UserIsSuccessor = true;
11745 break;
11746 }
11747
11748 // If the user is one of our immediate successors, and if that successor
11749 // only has us as a predecessors (we'd have to split the critical edge
11750 // otherwise), we can keep going.
11751 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11752 next(pred_begin(UserParent)) == pred_end(UserParent))
11753 // Okay, the CFG is simple enough, try to sink this instruction.
11754 Changed |= TryToSinkInstruction(I, UserParent);
11755 }
11756 }
11757
Chris Lattner8a2a3112001-12-14 16:52:21 +000011758 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011759#ifndef NDEBUG
11760 std::string OrigI;
11761#endif
11762 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011763 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011764 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011765 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011766 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011767 DOUT << "IC: Old = " << *I
11768 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011769
Chris Lattnerf523d062004-06-09 05:08:07 +000011770 // Everything uses the new instruction now.
11771 I->replaceAllUsesWith(Result);
11772
11773 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011774 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011775 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011776
Chris Lattner6934a042007-02-11 01:23:03 +000011777 // Move the name to the new instruction first.
11778 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011779
11780 // Insert the new instruction into the basic block...
11781 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011782 BasicBlock::iterator InsertPos = I;
11783
11784 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11785 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11786 ++InsertPos;
11787
11788 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011789
Chris Lattner00d51312004-05-01 23:27:23 +000011790 // Make sure that we reprocess all operands now that we reduced their
11791 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011792 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011793
Chris Lattnerf523d062004-06-09 05:08:07 +000011794 // Instructions can end up on the worklist more than once. Make sure
11795 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011796 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011797
11798 // Erase the old instruction.
11799 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011800 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011801#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011802 DOUT << "IC: Mod = " << OrigI
11803 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011804#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011805
Chris Lattner90ac28c2002-08-02 19:29:35 +000011806 // If the instruction was modified, it's possible that it is now dead.
11807 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011808 if (isInstructionTriviallyDead(I)) {
11809 // Make sure we process all operands now that we are reducing their
11810 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011811 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011812
Chris Lattner00d51312004-05-01 23:27:23 +000011813 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011814 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011815 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011816 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011817 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011818 AddToWorkList(I);
11819 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011820 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011821 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011822 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011823 }
11824 }
11825
Chris Lattnerec9c3582007-03-03 02:04:50 +000011826 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011827
11828 // Do an explicit clear, this shrinks the map if needed.
11829 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011830 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011831}
11832
Chris Lattnerec9c3582007-03-03 02:04:50 +000011833
11834bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011835 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11836
Chris Lattnerec9c3582007-03-03 02:04:50 +000011837 bool EverMadeChange = false;
11838
11839 // Iterate while there is work to do.
11840 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011841 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011842 EverMadeChange = true;
11843 return EverMadeChange;
11844}
11845
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011846FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011847 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011848}
Brian Gaeked0fde302003-11-11 22:41:34 +000011849
Chris Lattnerb8cd4d32008-08-11 22:06:05 +000011850