blob: 97bd34c771c206ed6e3ec04feb8fe4a59281709d [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000049#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000051#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000052#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000053#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000054#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000055#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000056#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000059#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000060#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000061#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000062#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000063using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000064using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000065
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000073 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000077 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000078 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000079 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000080 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000081 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000082 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000083 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000084
Chris Lattnerdbab3862007-03-02 21:28:56 +000085 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000089 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000109
Chris Lattnerdbab3862007-03-02 21:28:56 +0000110
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000115 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000118 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000119 }
120
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000127 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000128 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greif177dd3f2008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000141 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000142 // Set the operand to undef to drop the use.
Gabor Greif177dd3f2008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000144 }
145
146 return R;
147 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000148
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000149 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000150 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000151
152 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000153
Chris Lattner97e52e42002-04-28 21:27:06 +0000154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000155 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000156 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000157 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000158 }
159
Chris Lattner28977af2004-04-05 01:30:19 +0000160 TargetData &getTargetData() const { return *TD; }
161
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000166 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000168 //
Chris Lattner7e708292002-06-25 16:13:24 +0000169 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000170 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000171 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000172 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000173 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000174 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000175 Instruction *visitURem(BinaryOperator &I);
176 Instruction *visitSRem(BinaryOperator &I);
177 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000178 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000179 Instruction *commonRemTransforms(BinaryOperator &I);
180 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000181 Instruction *commonDivTransforms(BinaryOperator &I);
182 Instruction *commonIDivTransforms(BinaryOperator &I);
183 Instruction *visitUDiv(BinaryOperator &I);
184 Instruction *visitSDiv(BinaryOperator &I);
185 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000186 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000187 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000188 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000189 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000190 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000191 Instruction *visitOr (BinaryOperator &I);
192 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000193 Instruction *visitShl(BinaryOperator &I);
194 Instruction *visitAShr(BinaryOperator &I);
195 Instruction *visitLShr(BinaryOperator &I);
196 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000197 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
198 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000199 Instruction *visitFCmpInst(FCmpInst &I);
200 Instruction *visitICmpInst(ICmpInst &I);
201 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000202 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
203 Instruction *LHS,
204 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000205 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
206 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000207
Reid Spencere4d87aa2006-12-23 06:05:41 +0000208 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
209 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000210 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000211 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000212 Instruction *commonCastTransforms(CastInst &CI);
213 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000214 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000215 Instruction *visitTrunc(TruncInst &CI);
216 Instruction *visitZExt(ZExtInst &CI);
217 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000218 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000219 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000220 Instruction *visitFPToUI(FPToUIInst &FI);
221 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000222 Instruction *visitUIToFP(CastInst &CI);
223 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000224 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000225 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000226 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000227 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
228 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000229 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000230 Instruction *visitSelectInst(SelectInst &SI);
231 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000232 Instruction *visitCallInst(CallInst &CI);
233 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000234 Instruction *visitPHINode(PHINode &PN);
235 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000236 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000237 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000238 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000239 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000240 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000241 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000242 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000243 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000244 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000245 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000246
247 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000248 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000249
Chris Lattner9fe38862003-06-19 17:00:31 +0000250 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000251 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000252 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000253 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000254 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
255 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000256 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000257 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
258
Chris Lattner9fe38862003-06-19 17:00:31 +0000259
Chris Lattner28977af2004-04-05 01:30:19 +0000260 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000261 // InsertNewInstBefore - insert an instruction New before instruction Old
262 // in the program. Add the new instruction to the worklist.
263 //
Chris Lattner955f3312004-09-28 21:48:02 +0000264 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000265 assert(New && New->getParent() == 0 &&
266 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000267 BasicBlock *BB = Old.getParent();
268 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000269 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000270 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000271 }
272
Chris Lattner0c967662004-09-24 15:21:34 +0000273 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
274 /// This also adds the cast to the worklist. Finally, this returns the
275 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000276 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
277 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000278 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000279
Chris Lattnere2ed0572006-04-06 19:19:17 +0000280 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000281 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000282
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000283 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000284 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000285 return C;
286 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000287
288 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
289 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
290 }
291
Chris Lattner0c967662004-09-24 15:21:34 +0000292
Chris Lattner8b170942002-08-09 23:47:40 +0000293 // ReplaceInstUsesWith - This method is to be used when an instruction is
294 // found to be dead, replacable with another preexisting expression. Here
295 // we add all uses of I to the worklist, replace all uses of I with the new
296 // value, then return I, so that the inst combiner will know that I was
297 // modified.
298 //
299 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000300 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000301 if (&I != V) {
302 I.replaceAllUsesWith(V);
303 return &I;
304 } else {
305 // If we are replacing the instruction with itself, this must be in a
306 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000307 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000308 return &I;
309 }
Chris Lattner8b170942002-08-09 23:47:40 +0000310 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000311
312 // EraseInstFromFunction - When dealing with an instruction that has side
313 // effects or produces a void value, we can't rely on DCE to delete the
314 // instruction. Instead, visit methods should return the value returned by
315 // this function.
316 Instruction *EraseInstFromFunction(Instruction &I) {
317 assert(I.use_empty() && "Cannot erase instruction that is used!");
318 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000319 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000320 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000321 return 0; // Don't do anything with FI
322 }
Chris Lattner173234a2008-06-02 01:18:21 +0000323
324 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
325 APInt &KnownOne, unsigned Depth = 0) const {
326 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
327 }
328
329 bool MaskedValueIsZero(Value *V, const APInt &Mask,
330 unsigned Depth = 0) const {
331 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
332 }
333 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
334 return llvm::ComputeNumSignBits(Op, TD, Depth);
335 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000336
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000337 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000338
Reid Spencere4d87aa2006-12-23 06:05:41 +0000339 /// SimplifyCommutative - This performs a few simplifications for
340 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000341 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000342
Reid Spencere4d87aa2006-12-23 06:05:41 +0000343 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
344 /// most-complex to least-complex order.
345 bool SimplifyCompare(CmpInst &I);
346
Chris Lattner886ab6c2009-01-31 08:15:18 +0000347 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
348 /// based on the demanded bits.
349 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
350 APInt& KnownZero, APInt& KnownOne,
351 unsigned Depth);
352 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000353 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000354 unsigned Depth=0);
355
356 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
357 /// SimplifyDemandedBits knows about. See if the instruction has any
358 /// properties that allow us to simplify its operands.
359 bool SimplifyDemandedInstructionBits(Instruction &Inst);
360
Evan Cheng388df622009-02-03 10:05:09 +0000361 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
362 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000363
Chris Lattner4e998b22004-09-29 05:07:12 +0000364 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
365 // PHI node as operand #0, see if we can fold the instruction into the PHI
366 // (which is only possible if all operands to the PHI are constants).
367 Instruction *FoldOpIntoPhi(Instruction &I);
368
Chris Lattnerbac32862004-11-14 19:13:23 +0000369 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
370 // operator and they all are only used by the PHI, PHI together their
371 // inputs, and do the operation once, to the result of the PHI.
372 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000373 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000374 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
375
Chris Lattner7da52b22006-11-01 04:51:18 +0000376
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000377 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
378 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000379
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000380 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000381 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000382 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000383 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000384 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000385 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000386 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000387 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000388 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000389
Chris Lattnerafe91a52006-06-15 19:07:26 +0000390
Reid Spencerc55b2432006-12-13 18:21:21 +0000391 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000392
Dan Gohmaneee962e2008-04-10 18:43:06 +0000393 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000394 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000395 unsigned GetOrEnforceKnownAlignment(Value *V,
396 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000397
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000398 };
399}
400
Dan Gohman844731a2008-05-13 00:00:25 +0000401char InstCombiner::ID = 0;
402static RegisterPass<InstCombiner>
403X("instcombine", "Combine redundant instructions");
404
Chris Lattner4f98c562003-03-10 21:43:22 +0000405// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000406// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000407static unsigned getComplexity(Value *V) {
408 if (isa<Instruction>(V)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000409 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
410 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000411 return 3;
412 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000413 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000414 if (isa<Argument>(V)) return 3;
415 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000416}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000417
Chris Lattnerc8802d22003-03-11 00:12:48 +0000418// isOnlyUse - Return true if this instruction will be deleted if we stop using
419// it.
420static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000421 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000422}
423
Chris Lattner4cb170c2004-02-23 06:38:22 +0000424// getPromotedType - Return the specified type promoted as it would be to pass
425// though a va_arg area...
426static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000427 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
428 if (ITy->getBitWidth() < 32)
429 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000430 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000431 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000432}
433
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000434/// getBitCastOperand - If the specified operand is a CastInst, a constant
435/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
436/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000437static Value *getBitCastOperand(Value *V) {
438 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000439 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000440 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000441 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
442 // GetElementPtrInst?
443 if (GEP->hasAllZeroIndices())
444 return GEP->getOperand(0);
445 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000446 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000447 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000448 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000449 else if (CE->getOpcode() == Instruction::GetElementPtr) {
450 // GetElementPtr ConstantExp?
451 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
452 I != E; ++I) {
453 ConstantInt *CI = dyn_cast<ConstantInt>(I);
454 if (!CI || !CI->isZero())
455 // Any non-zero indices? Not cast-like.
456 return 0;
457 }
458 // All-zero indices? This is just like casting.
459 return CE->getOperand(0);
460 }
461 }
Chris Lattnereed48272005-09-13 00:40:14 +0000462 return 0;
463}
464
Reid Spencer3da59db2006-11-27 01:05:10 +0000465/// This function is a wrapper around CastInst::isEliminableCastPair. It
466/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000467static Instruction::CastOps
468isEliminableCastPair(
469 const CastInst *CI, ///< The first cast instruction
470 unsigned opcode, ///< The opcode of the second cast instruction
471 const Type *DstTy, ///< The target type for the second cast instruction
472 TargetData *TD ///< The target data for pointer size
473) {
474
475 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
476 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000477
Reid Spencer3da59db2006-11-27 01:05:10 +0000478 // Get the opcodes of the two Cast instructions
479 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
480 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000481
Chris Lattnera0e69692009-03-24 18:35:40 +0000482 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
483 DstTy, TD->getIntPtrType());
484
485 // We don't want to form an inttoptr or ptrtoint that converts to an integer
486 // type that differs from the pointer size.
487 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
488 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
489 Res = 0;
490
491 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000492}
493
494/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
495/// in any code being generated. It does not require codegen if V is simple
496/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000497static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
498 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000499 if (V->getType() == Ty || isa<Constant>(V)) return false;
500
Chris Lattner01575b72006-05-25 23:24:33 +0000501 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000502 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000503 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000504 return false;
505 return true;
506}
507
Chris Lattner4f98c562003-03-10 21:43:22 +0000508// SimplifyCommutative - This performs a few simplifications for commutative
509// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000510//
Chris Lattner4f98c562003-03-10 21:43:22 +0000511// 1. Order operands such that they are listed from right (least complex) to
512// left (most complex). This puts constants before unary operators before
513// binary operators.
514//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000515// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
516// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000517//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000518bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000519 bool Changed = false;
520 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
521 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000522
Chris Lattner4f98c562003-03-10 21:43:22 +0000523 if (!I.isAssociative()) return Changed;
524 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000525 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
526 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
527 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000528 Constant *Folded = ConstantExpr::get(I.getOpcode(),
529 cast<Constant>(I.getOperand(1)),
530 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000531 I.setOperand(0, Op->getOperand(0));
532 I.setOperand(1, Folded);
533 return true;
534 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
535 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
536 isOnlyUse(Op) && isOnlyUse(Op1)) {
537 Constant *C1 = cast<Constant>(Op->getOperand(1));
538 Constant *C2 = cast<Constant>(Op1->getOperand(1));
539
540 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000541 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000542 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000543 Op1->getOperand(0),
544 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000545 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000546 I.setOperand(0, New);
547 I.setOperand(1, Folded);
548 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000549 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000550 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000551 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000552}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000553
Reid Spencere4d87aa2006-12-23 06:05:41 +0000554/// SimplifyCompare - For a CmpInst this function just orders the operands
555/// so that theyare listed from right (least complex) to left (most complex).
556/// This puts constants before unary operators before binary operators.
557bool InstCombiner::SimplifyCompare(CmpInst &I) {
558 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
559 return false;
560 I.swapOperands();
561 // Compare instructions are not associative so there's nothing else we can do.
562 return true;
563}
564
Chris Lattner8d969642003-03-10 23:06:50 +0000565// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
566// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000567//
Chris Lattner8d969642003-03-10 23:06:50 +0000568static inline Value *dyn_castNegVal(Value *V) {
569 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000570 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000571
Chris Lattner0ce85802004-12-14 20:08:06 +0000572 // Constants can be considered to be negated values if they can be folded.
573 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
574 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000575
576 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
577 if (C->getType()->getElementType()->isInteger())
578 return ConstantExpr::getNeg(C);
579
Chris Lattner8d969642003-03-10 23:06:50 +0000580 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000581}
582
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000583// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
584// instruction if the LHS is a constant negative zero (which is the 'negate'
585// form).
586//
587static inline Value *dyn_castFNegVal(Value *V) {
588 if (BinaryOperator::isFNeg(V))
589 return BinaryOperator::getFNegArgument(V);
590
591 // Constants can be considered to be negated values if they can be folded.
592 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
593 return ConstantExpr::getFNeg(C);
594
595 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
596 if (C->getType()->getElementType()->isFloatingPoint())
597 return ConstantExpr::getFNeg(C);
598
599 return 0;
600}
601
Chris Lattner8d969642003-03-10 23:06:50 +0000602static inline Value *dyn_castNotVal(Value *V) {
603 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000604 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000605
606 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000607 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000608 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000609 return 0;
610}
611
Chris Lattnerc8802d22003-03-11 00:12:48 +0000612// dyn_castFoldableMul - If this value is a multiply that can be folded into
613// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000614// non-constant operand of the multiply, and set CST to point to the multiplier.
615// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000616//
Chris Lattner50af16a2004-11-13 19:50:12 +0000617static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000618 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000619 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000620 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000621 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000622 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000623 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000624 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000625 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000626 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000627 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000628 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000629 return I->getOperand(0);
630 }
631 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000632 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000633}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000634
Chris Lattner574da9b2005-01-13 20:14:25 +0000635/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
636/// expression, return it.
637static User *dyn_castGetElementPtr(Value *V) {
638 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
639 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
640 if (CE->getOpcode() == Instruction::GetElementPtr)
641 return cast<User>(V);
642 return false;
643}
644
Dan Gohmaneee962e2008-04-10 18:43:06 +0000645/// getOpcode - If this is an Instruction or a ConstantExpr, return the
646/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000647static unsigned getOpcode(const Value *V) {
648 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000649 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000650 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000651 return CE->getOpcode();
652 // Use UserOp1 to mean there's no opcode.
653 return Instruction::UserOp1;
654}
655
Reid Spencer7177c3a2007-03-25 05:33:51 +0000656/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000657static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000658 APInt Val(C->getValue());
659 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000660}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000661/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000662static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000663 APInt Val(C->getValue());
664 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000665}
666/// Add - Add two ConstantInts together
667static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
668 return ConstantInt::get(C1->getValue() + C2->getValue());
669}
670/// And - Bitwise AND two ConstantInts together
671static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
672 return ConstantInt::get(C1->getValue() & C2->getValue());
673}
674/// Subtract - Subtract one ConstantInt from another
675static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
676 return ConstantInt::get(C1->getValue() - C2->getValue());
677}
678/// Multiply - Multiply two ConstantInts together
679static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
680 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000681}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000682/// MultiplyOverflows - True if the multiply can not be expressed in an int
683/// this size.
684static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
685 uint32_t W = C1->getBitWidth();
686 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
687 if (sign) {
688 LHSExt.sext(W * 2);
689 RHSExt.sext(W * 2);
690 } else {
691 LHSExt.zext(W * 2);
692 RHSExt.zext(W * 2);
693 }
694
695 APInt MulExt = LHSExt * RHSExt;
696
697 if (sign) {
698 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
699 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
700 return MulExt.slt(Min) || MulExt.sgt(Max);
701 } else
702 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
703}
Chris Lattner955f3312004-09-28 21:48:02 +0000704
Reid Spencere7816b52007-03-08 01:52:58 +0000705
Chris Lattner255d8912006-02-11 09:31:47 +0000706/// ShrinkDemandedConstant - Check to see if the specified operand of the
707/// specified instruction is a constant integer. If so, check to see if there
708/// are any bits set in the constant that are not demanded. If so, shrink the
709/// constant and return true.
710static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000711 APInt Demanded) {
712 assert(I && "No instruction?");
713 assert(OpNo < I->getNumOperands() && "Operand index too large");
714
715 // If the operand is not a constant integer, nothing to do.
716 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
717 if (!OpC) return false;
718
719 // If there are no bits set that aren't demanded, nothing to do.
720 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
721 if ((~Demanded & OpC->getValue()) == 0)
722 return false;
723
724 // This instruction is producing bits that are not demanded. Shrink the RHS.
725 Demanded &= OpC->getValue();
726 I->setOperand(OpNo, ConstantInt::get(Demanded));
727 return true;
728}
729
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000730// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
731// set of known zero and one bits, compute the maximum and minimum values that
732// could have the specified known zero and known one bits, returning them in
733// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000734static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000735 const APInt& KnownOne,
736 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000737 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
738 KnownZero.getBitWidth() == Min.getBitWidth() &&
739 KnownZero.getBitWidth() == Max.getBitWidth() &&
740 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000741 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000742
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000743 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
744 // bit if it is unknown.
745 Min = KnownOne;
746 Max = KnownOne|UnknownBits;
747
Dan Gohman1c8491e2009-04-25 17:12:48 +0000748 if (UnknownBits.isNegative()) { // Sign bit is unknown
749 Min.set(Min.getBitWidth()-1);
750 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000751 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000752}
753
754// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
755// a set of known zero and one bits, compute the maximum and minimum values that
756// could have the specified known zero and known one bits, returning them in
757// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000758static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000759 const APInt &KnownOne,
760 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000761 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
762 KnownZero.getBitWidth() == Min.getBitWidth() &&
763 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000764 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000765 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000766
767 // The minimum value is when the unknown bits are all zeros.
768 Min = KnownOne;
769 // The maximum value is when the unknown bits are all ones.
770 Max = KnownOne|UnknownBits;
771}
Chris Lattner255d8912006-02-11 09:31:47 +0000772
Chris Lattner886ab6c2009-01-31 08:15:18 +0000773/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
774/// SimplifyDemandedBits knows about. See if the instruction has any
775/// properties that allow us to simplify its operands.
776bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
777 unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
778 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
779 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
780
781 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
782 KnownZero, KnownOne, 0);
783 if (V == 0) return false;
784 if (V == &Inst) return true;
785 ReplaceInstUsesWith(Inst, V);
786 return true;
787}
788
789/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
790/// specified instruction operand if possible, updating it in place. It returns
791/// true if it made any change and false otherwise.
792bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
793 APInt &KnownZero, APInt &KnownOne,
794 unsigned Depth) {
795 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
796 KnownZero, KnownOne, Depth);
797 if (NewVal == 0) return false;
798 U.set(NewVal);
799 return true;
800}
801
802
803/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
804/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000805/// that only the bits set in DemandedMask of the result of V are ever used
806/// downstream. Consequently, depending on the mask and V, it may be possible
807/// to replace V with a constant or one of its operands. In such cases, this
808/// function does the replacement and returns true. In all other cases, it
809/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000810/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000811/// to be zero in the expression. These are provided to potentially allow the
812/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
813/// the expression. KnownOne and KnownZero always follow the invariant that
814/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
815/// the bits in KnownOne and KnownZero may only be accurate for those bits set
816/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
817/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000818///
819/// This returns null if it did not change anything and it permits no
820/// simplification. This returns V itself if it did some simplification of V's
821/// operands based on the information about what bits are demanded. This returns
822/// some other non-null value if it found out that V is equal to another value
823/// in the context where the specified bits are demanded, but not for all users.
824Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
825 APInt &KnownZero, APInt &KnownOne,
826 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000827 assert(V != 0 && "Null pointer of Value???");
828 assert(Depth <= 6 && "Limit Search Depth");
829 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000830 const Type *VTy = V->getType();
831 assert((TD || !isa<PointerType>(VTy)) &&
832 "SimplifyDemandedBits needs to know bit widths!");
833 assert((!TD || TD->getTypeSizeInBits(VTy) == BitWidth) &&
834 (!isa<IntegerType>(VTy) ||
835 VTy->getPrimitiveSizeInBits() == BitWidth) &&
836 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000837 KnownOne.getBitWidth() == BitWidth &&
838 "Value *V, DemandedMask, KnownZero and KnownOne \
839 must have same BitWidth");
840 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
841 // We know all of the bits for a constant!
842 KnownOne = CI->getValue() & DemandedMask;
843 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000844 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000845 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000846 if (isa<ConstantPointerNull>(V)) {
847 // We know all of the bits for a constant!
848 KnownOne.clear();
849 KnownZero = DemandedMask;
850 return 0;
851 }
852
Chris Lattner08d2cc72009-01-31 07:26:06 +0000853 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000854 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000855 if (DemandedMask == 0) { // Not demanding any bits from V.
856 if (isa<UndefValue>(V))
857 return 0;
858 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000859 }
860
Chris Lattner4598c942009-01-31 08:24:16 +0000861 if (Depth == 6) // Limit search depth.
862 return 0;
863
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000864 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
865 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
866
Dan Gohman1c8491e2009-04-25 17:12:48 +0000867 Instruction *I = dyn_cast<Instruction>(V);
868 if (!I) {
869 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
870 return 0; // Only analyze instructions.
871 }
872
Chris Lattner4598c942009-01-31 08:24:16 +0000873 // If there are multiple uses of this value and we aren't at the root, then
874 // we can't do any simplifications of the operands, because DemandedMask
875 // only reflects the bits demanded by *one* of the users.
876 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000877 // Despite the fact that we can't simplify this instruction in all User's
878 // context, we can at least compute the knownzero/knownone bits, and we can
879 // do simplifications that apply to *just* the one user if we know that
880 // this instruction has a simpler value in that context.
881 if (I->getOpcode() == Instruction::And) {
882 // If either the LHS or the RHS are Zero, the result is zero.
883 ComputeMaskedBits(I->getOperand(1), DemandedMask,
884 RHSKnownZero, RHSKnownOne, Depth+1);
885 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
886 LHSKnownZero, LHSKnownOne, Depth+1);
887
888 // If all of the demanded bits are known 1 on one side, return the other.
889 // These bits cannot contribute to the result of the 'and' in this
890 // context.
891 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
892 (DemandedMask & ~LHSKnownZero))
893 return I->getOperand(0);
894 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
895 (DemandedMask & ~RHSKnownZero))
896 return I->getOperand(1);
897
898 // If all of the demanded bits in the inputs are known zeros, return zero.
899 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
900 return Constant::getNullValue(VTy);
901
902 } else if (I->getOpcode() == Instruction::Or) {
903 // We can simplify (X|Y) -> X or Y in the user's context if we know that
904 // only bits from X or Y are demanded.
905
906 // If either the LHS or the RHS are One, the result is One.
907 ComputeMaskedBits(I->getOperand(1), DemandedMask,
908 RHSKnownZero, RHSKnownOne, Depth+1);
909 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
910 LHSKnownZero, LHSKnownOne, Depth+1);
911
912 // If all of the demanded bits are known zero on one side, return the
913 // other. These bits cannot contribute to the result of the 'or' in this
914 // context.
915 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
916 (DemandedMask & ~LHSKnownOne))
917 return I->getOperand(0);
918 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
919 (DemandedMask & ~RHSKnownOne))
920 return I->getOperand(1);
921
922 // If all of the potentially set bits on one side are known to be set on
923 // the other side, just use the 'other' side.
924 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
925 (DemandedMask & (~RHSKnownZero)))
926 return I->getOperand(0);
927 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
928 (DemandedMask & (~LHSKnownZero)))
929 return I->getOperand(1);
930 }
931
Chris Lattner4598c942009-01-31 08:24:16 +0000932 // Compute the KnownZero/KnownOne bits to simplify things downstream.
933 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
934 return 0;
935 }
936
937 // If this is the root being simplified, allow it to have multiple uses,
938 // just set the DemandedMask to all bits so that we can try to simplify the
939 // operands. This allows visitTruncInst (for example) to simplify the
940 // operand of a trunc without duplicating all the logic below.
941 if (Depth == 0 && !V->hasOneUse())
942 DemandedMask = APInt::getAllOnesValue(BitWidth);
943
Reid Spencer8cb68342007-03-12 17:25:59 +0000944 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000945 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000946 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000947 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000948 case Instruction::And:
949 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000950 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
951 RHSKnownZero, RHSKnownOne, Depth+1) ||
952 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000953 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000954 return I;
955 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
956 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000957
958 // If all of the demanded bits are known 1 on one side, return the other.
959 // These bits cannot contribute to the result of the 'and'.
960 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
961 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000962 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000963 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
964 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000965 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000966
967 // If all of the demanded bits in the inputs are known zeros, return zero.
968 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000969 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000970
971 // If the RHS is a constant, see if we can simplify it.
972 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000973 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000974
975 // Output known-1 bits are only known if set in both the LHS & RHS.
976 RHSKnownOne &= LHSKnownOne;
977 // Output known-0 are known to be clear if zero in either the LHS | RHS.
978 RHSKnownZero |= LHSKnownZero;
979 break;
980 case Instruction::Or:
981 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000982 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
983 RHSKnownZero, RHSKnownOne, Depth+1) ||
984 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000985 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000986 return I;
987 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
988 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000989
990 // If all of the demanded bits are known zero on one side, return the other.
991 // These bits cannot contribute to the result of the 'or'.
992 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
993 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000994 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000995 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
996 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000997 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000998
999 // If all of the potentially set bits on one side are known to be set on
1000 // the other side, just use the 'other' side.
1001 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1002 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001003 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001004 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1005 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001006 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001007
1008 // If the RHS is a constant, see if we can simplify it.
1009 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001010 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001011
1012 // Output known-0 bits are only known if clear in both the LHS & RHS.
1013 RHSKnownZero &= LHSKnownZero;
1014 // Output known-1 are known to be set if set in either the LHS | RHS.
1015 RHSKnownOne |= LHSKnownOne;
1016 break;
1017 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001018 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1019 RHSKnownZero, RHSKnownOne, Depth+1) ||
1020 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001021 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001022 return I;
1023 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1024 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001025
1026 // If all of the demanded bits are known zero on one side, return the other.
1027 // These bits cannot contribute to the result of the 'xor'.
1028 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001029 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001030 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001031 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001032
1033 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1034 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1035 (RHSKnownOne & LHSKnownOne);
1036 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1037 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1038 (RHSKnownOne & LHSKnownZero);
1039
1040 // If all of the demanded bits are known to be zero on one side or the
1041 // other, turn this into an *inclusive* or.
1042 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1043 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1044 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001045 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001046 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001047 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001048 }
1049
1050 // If all of the demanded bits on one side are known, and all of the set
1051 // bits on that side are also known to be set on the other side, turn this
1052 // into an AND, as we know the bits will be cleared.
1053 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1054 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1055 // all known
1056 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1057 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1058 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001059 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001061 }
1062 }
1063
1064 // If the RHS is a constant, see if we can simplify it.
1065 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1066 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001068
1069 RHSKnownZero = KnownZeroOut;
1070 RHSKnownOne = KnownOneOut;
1071 break;
1072 }
1073 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001074 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1075 RHSKnownZero, RHSKnownOne, Depth+1) ||
1076 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001077 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 return I;
1079 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1080 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001081
1082 // If the operands are constants, see if we can simplify them.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001083 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1084 ShrinkDemandedConstant(I, 2, DemandedMask))
1085 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001086
1087 // Only known if known in both the LHS and RHS.
1088 RHSKnownOne &= LHSKnownOne;
1089 RHSKnownZero &= LHSKnownZero;
1090 break;
1091 case Instruction::Trunc: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001092 unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001093 DemandedMask.zext(truncBf);
1094 RHSKnownZero.zext(truncBf);
1095 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001096 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001097 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001098 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001099 DemandedMask.trunc(BitWidth);
1100 RHSKnownZero.trunc(BitWidth);
1101 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001102 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001103 break;
1104 }
1105 case Instruction::BitCast:
1106 if (!I->getOperand(0)->getType()->isInteger())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 return false; // vector->int or fp->int?
1108 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001109 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001110 return I;
1111 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001112 break;
1113 case Instruction::ZExt: {
1114 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001115 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001116
Zhou Shengd48653a2007-03-29 04:45:55 +00001117 DemandedMask.trunc(SrcBitWidth);
1118 RHSKnownZero.trunc(SrcBitWidth);
1119 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001120 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001121 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001122 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001123 DemandedMask.zext(BitWidth);
1124 RHSKnownZero.zext(BitWidth);
1125 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001126 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001127 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001128 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001129 break;
1130 }
1131 case Instruction::SExt: {
1132 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001133 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001134
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001136 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001137
Zhou Sheng01542f32007-03-29 02:26:30 +00001138 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001139 // If any of the sign extended bits are demanded, we know that the sign
1140 // bit is demanded.
1141 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001142 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001143
Zhou Shengd48653a2007-03-29 04:45:55 +00001144 InputDemandedBits.trunc(SrcBitWidth);
1145 RHSKnownZero.trunc(SrcBitWidth);
1146 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001147 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001148 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001149 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001150 InputDemandedBits.zext(BitWidth);
1151 RHSKnownZero.zext(BitWidth);
1152 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001153 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001154
1155 // If the sign bit of the input is known set or clear, then we know the
1156 // top bits of the result.
1157
1158 // If the input sign bit is known zero, or if the NewBits are not demanded
1159 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001160 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001161 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001162 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1163 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001164 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001165 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001166 }
1167 break;
1168 }
1169 case Instruction::Add: {
1170 // Figure out what the input bits are. If the top bits of the and result
1171 // are not demanded, then the add doesn't demand them from its input
1172 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001173 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001174
1175 // If there is a constant on the RHS, there are a variety of xformations
1176 // we can do.
1177 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1178 // If null, this should be simplified elsewhere. Some of the xforms here
1179 // won't work if the RHS is zero.
1180 if (RHS->isZero())
1181 break;
1182
1183 // If the top bit of the output is demanded, demand everything from the
1184 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001185 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001186
1187 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001188 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001189 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001190 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001191
1192 // If the RHS of the add has bits set that can't affect the input, reduce
1193 // the constant.
1194 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001195 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001196
1197 // Avoid excess work.
1198 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1199 break;
1200
1201 // Turn it into OR if input bits are zero.
1202 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1203 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001204 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001205 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001206 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001207 }
1208
1209 // We can say something about the output known-zero and known-one bits,
1210 // depending on potential carries from the input constant and the
1211 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1212 // bits set and the RHS constant is 0x01001, then we know we have a known
1213 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1214
1215 // To compute this, we first compute the potential carry bits. These are
1216 // the bits which may be modified. I'm not aware of a better way to do
1217 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001218 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001219 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001220
1221 // Now that we know which bits have carries, compute the known-1/0 sets.
1222
1223 // Bits are known one if they are known zero in one operand and one in the
1224 // other, and there is no input carry.
1225 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1226 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1227
1228 // Bits are known zero if they are known zero in both operands and there
1229 // is no input carry.
1230 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1231 } else {
1232 // If the high-bits of this ADD are not demanded, then it does not demand
1233 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001234 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001235 // Right fill the mask of bits for this ADD to demand the most
1236 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001237 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001238 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1239 LHSKnownZero, LHSKnownOne, Depth+1) ||
1240 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001242 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001243 }
1244 }
1245 break;
1246 }
1247 case Instruction::Sub:
1248 // If the high-bits of this SUB are not demanded, then it does not demand
1249 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001250 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001251 // Right fill the mask of bits for this SUB to demand the most
1252 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001253 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001254 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001255 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1256 LHSKnownZero, LHSKnownOne, Depth+1) ||
1257 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001258 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001259 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001260 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001261 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1262 // the known zeros and ones.
1263 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001264 break;
1265 case Instruction::Shl:
1266 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001267 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001268 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001269 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001271 return I;
1272 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 RHSKnownZero <<= ShiftAmt;
1274 RHSKnownOne <<= ShiftAmt;
1275 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001276 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001277 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001278 }
1279 break;
1280 case Instruction::LShr:
1281 // For a logical shift right
1282 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001283 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001284
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001286 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001287 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001289 return I;
1290 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001291 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1292 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001293 if (ShiftAmt) {
1294 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001295 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001296 RHSKnownZero |= HighBits; // high bits known zero.
1297 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 }
1299 break;
1300 case Instruction::AShr:
1301 // If this is an arithmetic shift right and only the low-bit is set, we can
1302 // always convert this into a logical shr, even if the shift amount is
1303 // variable. The low bit of the shift cannot be an input sign bit unless
1304 // the shift amount is >= the size of the datatype, which is undefined.
1305 if (DemandedMask == 1) {
1306 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001307 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001308 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001309 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001311
1312 // If the sign bit is the only bit demanded by this ashr, then there is no
1313 // need to do it, the shift doesn't change the high bit.
1314 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001315 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001316
1317 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001318 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001319
Reid Spencer8cb68342007-03-12 17:25:59 +00001320 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001321 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001322 // If any of the "high bits" are demanded, we should set the sign bit as
1323 // demanded.
1324 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1325 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001326 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001327 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001328 return I;
1329 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001330 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001331 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001332 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1333 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1334
1335 // Handle the sign bits.
1336 APInt SignBit(APInt::getSignBit(BitWidth));
1337 // Adjust to where it is now in the mask.
1338 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1339
1340 // If the input sign bit is known to be zero, or if none of the top bits
1341 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001342 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001343 (HighBits & ~DemandedMask) == HighBits) {
1344 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001345 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001346 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001347 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001348 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1349 RHSKnownOne |= HighBits;
1350 }
1351 }
1352 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001353 case Instruction::SRem:
1354 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001355 APInt RA = Rem->getValue().abs();
1356 if (RA.isPowerOf2()) {
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001357 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001358 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001359
Nick Lewycky8e394322008-11-02 02:41:50 +00001360 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001361 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001362 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001363 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001364 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001365
1366 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1367 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001368
1369 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001370
Chris Lattner886ab6c2009-01-31 08:15:18 +00001371 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001372 }
1373 }
1374 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001375 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001376 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1377 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001378 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1379 KnownZero2, KnownOne2, Depth+1) ||
1380 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001381 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001382 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001383
Chris Lattner455e9ab2009-01-21 18:09:24 +00001384 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001385 Leaders = std::max(Leaders,
1386 KnownZero2.countLeadingOnes());
1387 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001388 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001389 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001390 case Instruction::Call:
1391 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1392 switch (II->getIntrinsicID()) {
1393 default: break;
1394 case Intrinsic::bswap: {
1395 // If the only bits demanded come from one byte of the bswap result,
1396 // just shift the input byte into position to eliminate the bswap.
1397 unsigned NLZ = DemandedMask.countLeadingZeros();
1398 unsigned NTZ = DemandedMask.countTrailingZeros();
1399
1400 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1401 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1402 // have 14 leading zeros, round to 8.
1403 NLZ &= ~7;
1404 NTZ &= ~7;
1405 // If we need exactly one byte, we can do this transformation.
1406 if (BitWidth-NLZ-NTZ == 8) {
1407 unsigned ResultBit = NTZ;
1408 unsigned InputBit = BitWidth-NTZ-8;
1409
1410 // Replace this with either a left or right shift to get the byte into
1411 // the right place.
1412 Instruction *NewVal;
1413 if (InputBit > ResultBit)
1414 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1415 ConstantInt::get(I->getType(), InputBit-ResultBit));
1416 else
1417 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1418 ConstantInt::get(I->getType(), ResultBit-InputBit));
1419 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001420 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001421 }
1422
1423 // TODO: Could compute known zero/one bits based on the input.
1424 break;
1425 }
1426 }
1427 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001428 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001429 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001430 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001431
1432 // If the client is only demanding bits that we know, return the known
1433 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001434 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1435 Constant *C = ConstantInt::get(RHSKnownOne);
1436 if (isa<PointerType>(V->getType()))
1437 C = ConstantExpr::getIntToPtr(C, V->getType());
1438 return C;
1439 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001440 return false;
1441}
1442
Chris Lattner867b99f2006-10-05 06:55:50 +00001443
Mon P Wangaeb06d22008-11-10 04:46:22 +00001444/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001445/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001446/// actually used by the caller. This method analyzes which elements of the
1447/// operand are undef and returns that information in UndefElts.
1448///
1449/// If the information about demanded elements can be used to simplify the
1450/// operation, the operation is simplified, then the resultant value is
1451/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001452Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1453 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001454 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001455 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001456 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001457 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001458
1459 if (isa<UndefValue>(V)) {
1460 // If the entire vector is undefined, just return this info.
1461 UndefElts = EltMask;
1462 return 0;
1463 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1464 UndefElts = EltMask;
1465 return UndefValue::get(V->getType());
1466 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001467
Chris Lattner867b99f2006-10-05 06:55:50 +00001468 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001469 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1470 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001471 Constant *Undef = UndefValue::get(EltTy);
1472
1473 std::vector<Constant*> Elts;
1474 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001475 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001476 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001477 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001478 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1479 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001480 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001481 } else { // Otherwise, defined.
1482 Elts.push_back(CP->getOperand(i));
1483 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001484
Chris Lattner867b99f2006-10-05 06:55:50 +00001485 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001486 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001487 return NewCP != CP ? NewCP : 0;
1488 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001489 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001490 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001491
1492 // Check if this is identity. If so, return 0 since we are not simplifying
1493 // anything.
1494 if (DemandedElts == ((1ULL << VWidth) -1))
1495 return 0;
1496
Reid Spencer9d6565a2007-02-15 02:26:10 +00001497 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001498 Constant *Zero = Constant::getNullValue(EltTy);
1499 Constant *Undef = UndefValue::get(EltTy);
1500 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001501 for (unsigned i = 0; i != VWidth; ++i) {
1502 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1503 Elts.push_back(Elt);
1504 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001505 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001506 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001507 }
1508
Dan Gohman488fbfc2008-09-09 18:11:14 +00001509 // Limit search depth.
1510 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001511 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001512
1513 // If multiple users are using the root value, procede with
1514 // simplification conservatively assuming that all elements
1515 // are needed.
1516 if (!V->hasOneUse()) {
1517 // Quit if we find multiple users of a non-root value though.
1518 // They'll be handled when it's their turn to be visited by
1519 // the main instcombine process.
1520 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001521 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001522 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001523
1524 // Conservatively assume that all elements are needed.
1525 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001526 }
1527
1528 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001529 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001530
1531 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001532 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001533 Value *TmpV;
1534 switch (I->getOpcode()) {
1535 default: break;
1536
1537 case Instruction::InsertElement: {
1538 // If this is a variable index, we don't know which element it overwrites.
1539 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001540 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001541 if (Idx == 0) {
1542 // Note that we can't propagate undef elt info, because we don't know
1543 // which elt is getting updated.
1544 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1545 UndefElts2, Depth+1);
1546 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1547 break;
1548 }
1549
1550 // If this is inserting an element that isn't demanded, remove this
1551 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001552 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001553 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001554 return AddSoonDeadInstToWorklist(*I, 0);
1555
1556 // Otherwise, the element inserted overwrites whatever was there, so the
1557 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001558 APInt DemandedElts2 = DemandedElts;
1559 DemandedElts2.clear(IdxNo);
1560 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001561 UndefElts, Depth+1);
1562 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1563
1564 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001565 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001566 break;
1567 }
1568 case Instruction::ShuffleVector: {
1569 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001570 uint64_t LHSVWidth =
1571 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001572 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001573 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001574 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001575 unsigned MaskVal = Shuffle->getMaskValue(i);
1576 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001577 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001578 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001579 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001580 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001581 else
Evan Cheng388df622009-02-03 10:05:09 +00001582 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001583 }
1584 }
1585 }
1586
Nate Begeman7b254672009-02-11 22:36:25 +00001587 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001588 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001589 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001590 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1591
Nate Begeman7b254672009-02-11 22:36:25 +00001592 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001593 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1594 UndefElts3, Depth+1);
1595 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1596
1597 bool NewUndefElts = false;
1598 for (unsigned i = 0; i < VWidth; i++) {
1599 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001600 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001601 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001602 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001603 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001604 NewUndefElts = true;
1605 UndefElts.set(i);
1606 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001607 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001608 if (UndefElts3[MaskVal - LHSVWidth]) {
1609 NewUndefElts = true;
1610 UndefElts.set(i);
1611 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001612 }
1613 }
1614
1615 if (NewUndefElts) {
1616 // Add additional discovered undefs.
1617 std::vector<Constant*> Elts;
1618 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001619 if (UndefElts[i])
Dan Gohman488fbfc2008-09-09 18:11:14 +00001620 Elts.push_back(UndefValue::get(Type::Int32Ty));
1621 else
1622 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1623 Shuffle->getMaskValue(i)));
1624 }
1625 I->setOperand(2, ConstantVector::get(Elts));
1626 MadeChange = true;
1627 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001628 break;
1629 }
Chris Lattner69878332007-04-14 22:29:23 +00001630 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001631 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001632 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1633 if (!VTy) break;
1634 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001635 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001636 unsigned Ratio;
1637
1638 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001639 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001640 // elements as are demanded of us.
1641 Ratio = 1;
1642 InputDemandedElts = DemandedElts;
1643 } else if (VWidth > InVWidth) {
1644 // Untested so far.
1645 break;
1646
1647 // If there are more elements in the result than there are in the source,
1648 // then an input element is live if any of the corresponding output
1649 // elements are live.
1650 Ratio = VWidth/InVWidth;
1651 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001652 if (DemandedElts[OutIdx])
1653 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001654 }
1655 } else {
1656 // Untested so far.
1657 break;
1658
1659 // If there are more elements in the source than there are in the result,
1660 // then an input element is live if the corresponding output element is
1661 // live.
1662 Ratio = InVWidth/VWidth;
1663 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001664 if (DemandedElts[InIdx/Ratio])
1665 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001666 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001667
Chris Lattner69878332007-04-14 22:29:23 +00001668 // div/rem demand all inputs, because they don't want divide by zero.
1669 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1670 UndefElts2, Depth+1);
1671 if (TmpV) {
1672 I->setOperand(0, TmpV);
1673 MadeChange = true;
1674 }
1675
1676 UndefElts = UndefElts2;
1677 if (VWidth > InVWidth) {
1678 assert(0 && "Unimp");
1679 // If there are more elements in the result than there are in the source,
1680 // then an output element is undef if the corresponding input element is
1681 // undef.
1682 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001683 if (UndefElts2[OutIdx/Ratio])
1684 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001685 } else if (VWidth < InVWidth) {
1686 assert(0 && "Unimp");
1687 // If there are more elements in the source than there are in the result,
1688 // then a result element is undef if all of the corresponding input
1689 // elements are undef.
1690 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1691 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001692 if (!UndefElts2[InIdx]) // Not undef?
1693 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001694 }
1695 break;
1696 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001697 case Instruction::And:
1698 case Instruction::Or:
1699 case Instruction::Xor:
1700 case Instruction::Add:
1701 case Instruction::Sub:
1702 case Instruction::Mul:
1703 // div/rem demand all inputs, because they don't want divide by zero.
1704 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1705 UndefElts, Depth+1);
1706 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1707 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1708 UndefElts2, Depth+1);
1709 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1710
1711 // Output elements are undefined if both are undefined. Consider things
1712 // like undef&0. The result is known zero, not undef.
1713 UndefElts &= UndefElts2;
1714 break;
1715
1716 case Instruction::Call: {
1717 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1718 if (!II) break;
1719 switch (II->getIntrinsicID()) {
1720 default: break;
1721
1722 // Binary vector operations that work column-wise. A dest element is a
1723 // function of the corresponding input elements from the two inputs.
1724 case Intrinsic::x86_sse_sub_ss:
1725 case Intrinsic::x86_sse_mul_ss:
1726 case Intrinsic::x86_sse_min_ss:
1727 case Intrinsic::x86_sse_max_ss:
1728 case Intrinsic::x86_sse2_sub_sd:
1729 case Intrinsic::x86_sse2_mul_sd:
1730 case Intrinsic::x86_sse2_min_sd:
1731 case Intrinsic::x86_sse2_max_sd:
1732 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1733 UndefElts, Depth+1);
1734 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1735 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1736 UndefElts2, Depth+1);
1737 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1738
1739 // If only the low elt is demanded and this is a scalarizable intrinsic,
1740 // scalarize it now.
1741 if (DemandedElts == 1) {
1742 switch (II->getIntrinsicID()) {
1743 default: break;
1744 case Intrinsic::x86_sse_sub_ss:
1745 case Intrinsic::x86_sse_mul_ss:
1746 case Intrinsic::x86_sse2_sub_sd:
1747 case Intrinsic::x86_sse2_mul_sd:
1748 // TODO: Lower MIN/MAX/ABS/etc
1749 Value *LHS = II->getOperand(1);
1750 Value *RHS = II->getOperand(2);
1751 // Extract the element as scalars.
1752 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1753 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1754
1755 switch (II->getIntrinsicID()) {
1756 default: assert(0 && "Case stmts out of sync!");
1757 case Intrinsic::x86_sse_sub_ss:
1758 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001759 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001760 II->getName()), *II);
1761 break;
1762 case Intrinsic::x86_sse_mul_ss:
1763 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001764 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001765 II->getName()), *II);
1766 break;
1767 }
1768
1769 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001770 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1771 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001772 InsertNewInstBefore(New, *II);
1773 AddSoonDeadInstToWorklist(*II, 0);
1774 return New;
1775 }
1776 }
1777
1778 // Output elements are undefined if both are undefined. Consider things
1779 // like undef&0. The result is known zero, not undef.
1780 UndefElts &= UndefElts2;
1781 break;
1782 }
1783 break;
1784 }
1785 }
1786 return MadeChange ? I : 0;
1787}
1788
Dan Gohman45b4e482008-05-19 22:14:15 +00001789
Chris Lattner564a7272003-08-13 19:01:45 +00001790/// AssociativeOpt - Perform an optimization on an associative operator. This
1791/// function is designed to check a chain of associative operators for a
1792/// potential to apply a certain optimization. Since the optimization may be
1793/// applicable if the expression was reassociated, this checks the chain, then
1794/// reassociates the expression as necessary to expose the optimization
1795/// opportunity. This makes use of a special Functor, which must define
1796/// 'shouldApply' and 'apply' methods.
1797///
1798template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001799static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001800 unsigned Opcode = Root.getOpcode();
1801 Value *LHS = Root.getOperand(0);
1802
1803 // Quick check, see if the immediate LHS matches...
1804 if (F.shouldApply(LHS))
1805 return F.apply(Root);
1806
1807 // Otherwise, if the LHS is not of the same opcode as the root, return.
1808 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001809 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001810 // Should we apply this transform to the RHS?
1811 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1812
1813 // If not to the RHS, check to see if we should apply to the LHS...
1814 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1815 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1816 ShouldApply = true;
1817 }
1818
1819 // If the functor wants to apply the optimization to the RHS of LHSI,
1820 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1821 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001822 // Now all of the instructions are in the current basic block, go ahead
1823 // and perform the reassociation.
1824 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1825
1826 // First move the selected RHS to the LHS of the root...
1827 Root.setOperand(0, LHSI->getOperand(1));
1828
1829 // Make what used to be the LHS of the root be the user of the root...
1830 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001831 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001832 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1833 return 0;
1834 }
Chris Lattner65725312004-04-16 18:08:07 +00001835 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001836 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001837 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001838 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001839 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001840
1841 // Now propagate the ExtraOperand down the chain of instructions until we
1842 // get to LHSI.
1843 while (TmpLHSI != LHSI) {
1844 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001845 // Move the instruction to immediately before the chain we are
1846 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001847 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001848 ARI = NextLHSI;
1849
Chris Lattner564a7272003-08-13 19:01:45 +00001850 Value *NextOp = NextLHSI->getOperand(1);
1851 NextLHSI->setOperand(1, ExtraOperand);
1852 TmpLHSI = NextLHSI;
1853 ExtraOperand = NextOp;
1854 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001855
Chris Lattner564a7272003-08-13 19:01:45 +00001856 // Now that the instructions are reassociated, have the functor perform
1857 // the transformation...
1858 return F.apply(Root);
1859 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001860
Chris Lattner564a7272003-08-13 19:01:45 +00001861 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1862 }
1863 return 0;
1864}
1865
Dan Gohman844731a2008-05-13 00:00:25 +00001866namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001867
Nick Lewycky02d639f2008-05-23 04:34:58 +00001868// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001869struct AddRHS {
1870 Value *RHS;
1871 AddRHS(Value *rhs) : RHS(rhs) {}
1872 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1873 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001874 return BinaryOperator::CreateShl(Add.getOperand(0),
1875 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001876 }
1877};
1878
1879// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1880// iff C1&C2 == 0
1881struct AddMaskingAnd {
1882 Constant *C2;
1883 AddMaskingAnd(Constant *c) : C2(c) {}
1884 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001885 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001886 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001887 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001888 }
1889 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001890 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001891 }
1892};
1893
Dan Gohman844731a2008-05-13 00:00:25 +00001894}
1895
Chris Lattner6e7ba452005-01-01 16:22:27 +00001896static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001897 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001898 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001899 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001900 }
1901
Chris Lattner2eefe512004-04-09 19:05:30 +00001902 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001903 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1904 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001905
Chris Lattner2eefe512004-04-09 19:05:30 +00001906 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1907 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001908 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1909 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001910 }
1911
1912 Value *Op0 = SO, *Op1 = ConstOperand;
1913 if (!ConstIsRHS)
1914 std::swap(Op0, Op1);
1915 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001916 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001917 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001918 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001919 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001920 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001921 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001922 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001923 abort();
1924 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001925 return IC->InsertNewInstBefore(New, I);
1926}
1927
1928// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1929// constant as the other operand, try to fold the binary operator into the
1930// select arguments. This also works for Cast instructions, which obviously do
1931// not have a second operand.
1932static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1933 InstCombiner *IC) {
1934 // Don't modify shared select instructions
1935 if (!SI->hasOneUse()) return 0;
1936 Value *TV = SI->getOperand(1);
1937 Value *FV = SI->getOperand(2);
1938
1939 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001940 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001941 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001942
Chris Lattner6e7ba452005-01-01 16:22:27 +00001943 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1944 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1945
Gabor Greif051a9502008-04-06 20:25:17 +00001946 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1947 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001948 }
1949 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001950}
1951
Chris Lattner4e998b22004-09-29 05:07:12 +00001952
1953/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1954/// node as operand #0, see if we can fold the instruction into the PHI (which
1955/// is only possible if all operands to the PHI are constants).
1956Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1957 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001958 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001959 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001960
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001961 // Check to see if all of the operands of the PHI are constants. If there is
1962 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001963 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001964 BasicBlock *NonConstBB = 0;
1965 for (unsigned i = 0; i != NumPHIValues; ++i)
1966 if (!isa<Constant>(PN->getIncomingValue(i))) {
1967 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001968 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001969 NonConstBB = PN->getIncomingBlock(i);
1970
1971 // If the incoming non-constant value is in I's block, we have an infinite
1972 // loop.
1973 if (NonConstBB == I.getParent())
1974 return 0;
1975 }
1976
1977 // If there is exactly one non-constant value, we can insert a copy of the
1978 // operation in that block. However, if this is a critical edge, we would be
1979 // inserting the computation one some other paths (e.g. inside a loop). Only
1980 // do this if the pred block is unconditionally branching into the phi block.
1981 if (NonConstBB) {
1982 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1983 if (!BI || !BI->isUnconditional()) return 0;
1984 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001985
1986 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001987 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001988 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001989 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001990 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001991
1992 // Next, add all of the operands to the PHI.
1993 if (I.getNumOperands() == 2) {
1994 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001995 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001996 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001997 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001998 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1999 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2000 else
2001 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002002 } else {
2003 assert(PN->getIncomingBlock(i) == NonConstBB);
2004 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002005 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002006 PN->getIncomingValue(i), C, "phitmp",
2007 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002008 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002009 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002010 CI->getPredicate(),
2011 PN->getIncomingValue(i), C, "phitmp",
2012 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002013 else
2014 assert(0 && "Unknown binop!");
2015
Chris Lattnerdbab3862007-03-02 21:28:56 +00002016 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002017 }
2018 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002019 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002020 } else {
2021 CastInst *CI = cast<CastInst>(&I);
2022 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002023 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002024 Value *InV;
2025 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002026 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002027 } else {
2028 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002029 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002030 I.getType(), "phitmp",
2031 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002032 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002033 }
2034 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002035 }
2036 }
2037 return ReplaceInstUsesWith(I, NewPN);
2038}
2039
Chris Lattner2454a2e2008-01-29 06:52:45 +00002040
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002041/// WillNotOverflowSignedAdd - Return true if we can prove that:
2042/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2043/// This basically requires proving that the add in the original type would not
2044/// overflow to change the sign bit or have a carry out.
2045bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2046 // There are different heuristics we can use for this. Here are some simple
2047 // ones.
2048
2049 // Add has the property that adding any two 2's complement numbers can only
2050 // have one carry bit which can change a sign. As such, if LHS and RHS each
2051 // have at least two sign bits, we know that the addition of the two values will
2052 // sign extend fine.
2053 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2054 return true;
2055
2056
2057 // If one of the operands only has one non-zero bit, and if the other operand
2058 // has a known-zero bit in a more significant place than it (not including the
2059 // sign bit) the ripple may go up to and fill the zero, but won't change the
2060 // sign. For example, (X & ~4) + 1.
2061
2062 // TODO: Implement.
2063
2064 return false;
2065}
2066
Chris Lattner2454a2e2008-01-29 06:52:45 +00002067
Chris Lattner7e708292002-06-25 16:13:24 +00002068Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002069 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002070 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002071
Chris Lattner66331a42004-04-10 22:01:55 +00002072 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002073 // X + undef -> undef
2074 if (isa<UndefValue>(RHS))
2075 return ReplaceInstUsesWith(I, RHS);
2076
Chris Lattner66331a42004-04-10 22:01:55 +00002077 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002078 if (RHSC->isNullValue())
2079 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002080
Chris Lattner66331a42004-04-10 22:01:55 +00002081 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002082 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002083 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002084 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002085 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002086 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002087
2088 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2089 // (X & 254)+1 -> (X&254)|1
Chris Lattner886ab6c2009-01-31 08:15:18 +00002090 if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2091 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002092
2093 // zext(i1) - 1 -> select i1, 0, -1
2094 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2095 if (CI->isAllOnesValue() &&
2096 ZI->getOperand(0)->getType() == Type::Int1Ty)
2097 return SelectInst::Create(ZI->getOperand(0),
2098 Constant::getNullValue(I.getType()),
2099 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00002100 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002101
2102 if (isa<PHINode>(LHS))
2103 if (Instruction *NV = FoldOpIntoPhi(I))
2104 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002105
Chris Lattner4f637d42006-01-06 17:59:59 +00002106 ConstantInt *XorRHS = 0;
2107 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002108 if (isa<ConstantInt>(RHSC) &&
2109 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002110 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002111 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002112
Zhou Sheng4351c642007-04-02 08:20:41 +00002113 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002114 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2115 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002116 do {
2117 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002118 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2119 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002120 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2121 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002122 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002123 if (!MaskedValueIsZero(XorLHS,
2124 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002125 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002126 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002127 }
2128 }
2129 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002130 C0080Val = APIntOps::lshr(C0080Val, Size);
2131 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2132 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002133
Reid Spencer35c38852007-03-28 01:36:16 +00002134 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002135 // with funny bit widths then this switch statement should be removed. It
2136 // is just here to get the size of the "middle" type back up to something
2137 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002138 const Type *MiddleType = 0;
2139 switch (Size) {
2140 default: break;
2141 case 32: MiddleType = Type::Int32Ty; break;
2142 case 16: MiddleType = Type::Int16Ty; break;
2143 case 8: MiddleType = Type::Int8Ty; break;
2144 }
2145 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002146 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002147 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002148 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002149 }
2150 }
Chris Lattner66331a42004-04-10 22:01:55 +00002151 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002152
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002153 if (I.getType() == Type::Int1Ty)
2154 return BinaryOperator::CreateXor(LHS, RHS);
2155
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002156 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002157 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002158 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002159
2160 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2161 if (RHSI->getOpcode() == Instruction::Sub)
2162 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2163 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2164 }
2165 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2166 if (LHSI->getOpcode() == Instruction::Sub)
2167 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2168 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2169 }
Robert Bocchino71698282004-07-27 21:02:21 +00002170 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002171
Chris Lattner5c4afb92002-05-08 22:46:53 +00002172 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002173 // -A + -B --> -(A + B)
2174 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002175 if (LHS->getType()->isIntOrIntVector()) {
2176 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002177 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002178 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002179 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002180 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002181 }
2182
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002183 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002184 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002185
2186 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002187 if (!isa<Constant>(RHS))
2188 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002189 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002190
Misha Brukmanfd939082005-04-21 23:48:37 +00002191
Chris Lattner50af16a2004-11-13 19:50:12 +00002192 ConstantInt *C2;
2193 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2194 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002195 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002196
2197 // X*C1 + X*C2 --> X * (C1+C2)
2198 ConstantInt *C1;
2199 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002200 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002201 }
2202
2203 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002204 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002205 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002206
Chris Lattnere617c9e2007-01-05 02:17:46 +00002207 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002208 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2209 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002210
Chris Lattnerad3448c2003-02-18 19:57:07 +00002211
Chris Lattner564a7272003-08-13 19:01:45 +00002212 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002213 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002214 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2215 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002216
2217 // A+B --> A|B iff A and B have no bits set in common.
2218 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2219 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2220 APInt LHSKnownOne(IT->getBitWidth(), 0);
2221 APInt LHSKnownZero(IT->getBitWidth(), 0);
2222 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2223 if (LHSKnownZero != 0) {
2224 APInt RHSKnownOne(IT->getBitWidth(), 0);
2225 APInt RHSKnownZero(IT->getBitWidth(), 0);
2226 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2227
2228 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002229 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002230 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002231 }
2232 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002233
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002234 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002235 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002236 Value *W, *X, *Y, *Z;
2237 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2238 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2239 if (W != Y) {
2240 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002241 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002242 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002243 std::swap(W, X);
2244 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002245 std::swap(Y, Z);
2246 std::swap(W, X);
2247 }
2248 }
2249
2250 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002251 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002252 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002253 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002254 }
2255 }
2256 }
2257
Chris Lattner6b032052003-10-02 15:11:26 +00002258 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002259 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002260 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002261 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002262
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002263 // (X & FF00) + xx00 -> (X+xx00) & FF00
2264 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002265 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002266 if (Anded == CRHS) {
2267 // See if all bits from the first bit set in the Add RHS up are included
2268 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002269 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002270
2271 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002272 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002273
2274 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002275 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002276
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002277 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2278 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002279 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002280 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002281 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002282 }
2283 }
2284 }
2285
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002286 // Try to fold constant add into select arguments.
2287 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002288 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002289 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002290 }
2291
Reid Spencer1628cec2006-10-26 06:15:43 +00002292 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002293 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002294 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002295 CastInst *CI = dyn_cast<CastInst>(LHS);
2296 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002297 if (!CI) {
2298 CI = dyn_cast<CastInst>(RHS);
2299 Other = LHS;
2300 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002301 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002302 (CI->getType()->getPrimitiveSizeInBits() ==
2303 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002304 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002305 unsigned AS =
2306 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002307 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2308 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002309 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002310 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002311 }
2312 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002313
Chris Lattner42790482007-12-20 01:56:58 +00002314 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002315 {
2316 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002317 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002318 if (!SI) {
2319 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002320 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002321 }
Chris Lattner42790482007-12-20 01:56:58 +00002322 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002323 Value *TV = SI->getTrueValue();
2324 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002325 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002326
2327 // Can we fold the add into the argument of the select?
2328 // We check both true and false select arguments for a matching subtract.
Chris Lattner6046fb72008-11-16 04:46:19 +00002329 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2330 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002331 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner6046fb72008-11-16 04:46:19 +00002332 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2333 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002334 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002335 }
2336 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002337
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002338 // Check for (add (sext x), y), see if we can merge this into an
2339 // integer add followed by a sext.
2340 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2341 // (add (sext x), cst) --> (sext (add x, cst'))
2342 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2343 Constant *CI =
2344 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2345 if (LHSConv->hasOneUse() &&
2346 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2347 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2348 // Insert the new, smaller add.
2349 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2350 CI, "addconv");
2351 InsertNewInstBefore(NewAdd, I);
2352 return new SExtInst(NewAdd, I.getType());
2353 }
2354 }
2355
2356 // (add (sext x), (sext y)) --> (sext (add int x, y))
2357 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2358 // Only do this if x/y have the same type, if at last one of them has a
2359 // single use (so we don't increase the number of sexts), and if the
2360 // integer add will not overflow.
2361 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2362 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2363 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2364 RHSConv->getOperand(0))) {
2365 // Insert the new integer add.
2366 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2367 RHSConv->getOperand(0),
2368 "addconv");
2369 InsertNewInstBefore(NewAdd, I);
2370 return new SExtInst(NewAdd, I.getType());
2371 }
2372 }
2373 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002374
2375 return Changed ? &I : 0;
2376}
2377
2378Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2379 bool Changed = SimplifyCommutative(I);
2380 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2381
2382 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2383 // X + 0 --> X
2384 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2385 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2386 (I.getType())->getValueAPF()))
2387 return ReplaceInstUsesWith(I, LHS);
2388 }
2389
2390 if (isa<PHINode>(LHS))
2391 if (Instruction *NV = FoldOpIntoPhi(I))
2392 return NV;
2393 }
2394
2395 // -A + B --> B - A
2396 // -A + -B --> -(A + B)
2397 if (Value *LHSV = dyn_castFNegVal(LHS))
2398 return BinaryOperator::CreateFSub(RHS, LHSV);
2399
2400 // A + -B --> A - B
2401 if (!isa<Constant>(RHS))
2402 if (Value *V = dyn_castFNegVal(RHS))
2403 return BinaryOperator::CreateFSub(LHS, V);
2404
2405 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2406 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2407 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2408 return ReplaceInstUsesWith(I, LHS);
2409
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002410 // Check for (add double (sitofp x), y), see if we can merge this into an
2411 // integer add followed by a promotion.
2412 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2413 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2414 // ... if the constant fits in the integer value. This is useful for things
2415 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2416 // requires a constant pool load, and generally allows the add to be better
2417 // instcombined.
2418 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2419 Constant *CI =
2420 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2421 if (LHSConv->hasOneUse() &&
2422 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2423 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2424 // Insert the new integer add.
2425 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2426 CI, "addconv");
2427 InsertNewInstBefore(NewAdd, I);
2428 return new SIToFPInst(NewAdd, I.getType());
2429 }
2430 }
2431
2432 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2433 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2434 // Only do this if x/y have the same type, if at last one of them has a
2435 // single use (so we don't increase the number of int->fp conversions),
2436 // and if the integer add will not overflow.
2437 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2438 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2439 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2440 RHSConv->getOperand(0))) {
2441 // Insert the new integer add.
2442 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2443 RHSConv->getOperand(0),
2444 "addconv");
2445 InsertNewInstBefore(NewAdd, I);
2446 return new SIToFPInst(NewAdd, I.getType());
2447 }
2448 }
2449 }
2450
Chris Lattner7e708292002-06-25 16:13:24 +00002451 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002452}
2453
Chris Lattner7e708292002-06-25 16:13:24 +00002454Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002455 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002456
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002457 if (Op0 == Op1) // sub X, X -> 0
Chris Lattner233f7dc2002-08-12 21:17:25 +00002458 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002459
Chris Lattner233f7dc2002-08-12 21:17:25 +00002460 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002461 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002462 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002463
Chris Lattnere87597f2004-10-16 18:11:37 +00002464 if (isa<UndefValue>(Op0))
2465 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2466 if (isa<UndefValue>(Op1))
2467 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2468
Chris Lattnerd65460f2003-11-05 01:06:05 +00002469 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2470 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002471 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002472 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002473
Chris Lattnerd65460f2003-11-05 01:06:05 +00002474 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002475 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002476 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002477 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002478
Chris Lattner76b7a062007-01-15 07:02:54 +00002479 // -(X >>u 31) -> (X >>s 31)
2480 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002481 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002482 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002483 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002484 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002485 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002486 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002487 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002488 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002489 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002490 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002491 }
2492 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002493 }
2494 else if (SI->getOpcode() == Instruction::AShr) {
2495 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2496 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002497 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002498 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002499 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002500 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002501 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002502 }
2503 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002504 }
2505 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002506 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002507
2508 // Try to fold constant sub into select arguments.
2509 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002510 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002511 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002512 }
2513
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002514 if (I.getType() == Type::Int1Ty)
2515 return BinaryOperator::CreateXor(Op0, Op1);
2516
Chris Lattner43d84d62005-04-07 16:15:25 +00002517 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002518 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002519 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002520 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002521 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002522 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002523 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2524 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2525 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002526 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002527 Op1I->getOperand(0));
2528 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002529 }
2530
Chris Lattnerfd059242003-10-15 16:48:29 +00002531 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002532 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2533 // is not used by anyone else...
2534 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002535 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002536 // Swap the two operands of the subexpr...
2537 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2538 Op1I->setOperand(0, IIOp1);
2539 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002540
Chris Lattnera2881962003-02-18 19:28:33 +00002541 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002542 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002543 }
2544
2545 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2546 //
2547 if (Op1I->getOpcode() == Instruction::And &&
2548 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2549 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2550
Chris Lattnerf523d062004-06-09 05:08:07 +00002551 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002552 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2553 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002554 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002555
Reid Spencerac5209e2006-10-16 23:08:08 +00002556 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002557 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002558 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002559 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002560 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002561 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002562 ConstantExpr::getNeg(DivRHS));
2563
Chris Lattnerad3448c2003-02-18 19:57:07 +00002564 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002565 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002566 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002567 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002568 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002569 }
Chris Lattner40371712002-05-09 01:29:19 +00002570 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002571 }
Chris Lattnera2881962003-02-18 19:28:33 +00002572
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002573 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2574 if (Op0I->getOpcode() == Instruction::Add) {
2575 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2576 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2577 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2578 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2579 } else if (Op0I->getOpcode() == Instruction::Sub) {
2580 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2581 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002582 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002583 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002584
Chris Lattner50af16a2004-11-13 19:50:12 +00002585 ConstantInt *C1;
2586 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002587 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002588 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002589
Chris Lattner50af16a2004-11-13 19:50:12 +00002590 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2591 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002592 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002593 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002594 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002595}
2596
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002597Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2598 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2599
2600 // If this is a 'B = x-(-A)', change to B = x+A...
2601 if (Value *V = dyn_castFNegVal(Op1))
2602 return BinaryOperator::CreateFAdd(Op0, V);
2603
2604 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2605 if (Op1I->getOpcode() == Instruction::FAdd) {
2606 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2607 return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2608 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2609 return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2610 }
2611
2612 if (Op1I->hasOneUse()) {
2613 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2614 // is not used by anyone else...
2615 //
2616 if (Op1I->getOpcode() == Instruction::FSub) {
2617 // Swap the two operands of the subexpr...
2618 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2619 Op1I->setOperand(0, IIOp1);
2620 Op1I->setOperand(1, IIOp0);
2621
2622 // Create the new top level fadd instruction...
2623 return BinaryOperator::CreateFAdd(Op0, Op1);
2624 }
2625 }
2626 }
2627
2628 return 0;
2629}
2630
Chris Lattnera0141b92007-07-15 20:42:37 +00002631/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2632/// comparison only checks the sign bit. If it only checks the sign bit, set
2633/// TrueIfSigned if the result of the comparison is true when the input value is
2634/// signed.
2635static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2636 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002637 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002638 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2639 TrueIfSigned = true;
2640 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002641 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2642 TrueIfSigned = true;
2643 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002644 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2645 TrueIfSigned = false;
2646 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002647 case ICmpInst::ICMP_UGT:
2648 // True if LHS u> RHS and RHS == high-bit-mask - 1
2649 TrueIfSigned = true;
2650 return RHS->getValue() ==
2651 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2652 case ICmpInst::ICMP_UGE:
2653 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2654 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002655 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002656 default:
2657 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002658 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002659}
2660
Chris Lattner7e708292002-06-25 16:13:24 +00002661Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002662 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002663 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002664
Dan Gohman77b81fe2009-06-04 17:12:12 +00002665 // TODO: If Op1 is undef and Op0 is finite, return zero.
2666 if (!I.getType()->isFPOrFPVector() &&
2667 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00002668 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2669
Chris Lattner233f7dc2002-08-12 21:17:25 +00002670 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002671 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2672 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002673
2674 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002675 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002676 if (SI->getOpcode() == Instruction::Shl)
2677 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002678 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002679 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002680
Zhou Sheng843f07672007-04-19 05:39:12 +00002681 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002682 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2683 if (CI->equalsInt(1)) // X * 1 == X
2684 return ReplaceInstUsesWith(I, Op0);
2685 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002686 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002687
Zhou Sheng97b52c22007-03-29 01:57:21 +00002688 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002689 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002690 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002691 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002692 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002693 } else if (isa<VectorType>(Op1->getType())) {
Dan Gohman77b81fe2009-06-04 17:12:12 +00002694 // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
Nick Lewycky895f0852008-11-27 20:21:08 +00002695
2696 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2697 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2698 return BinaryOperator::CreateNeg(Op0, I.getName());
2699
2700 // As above, vector X*splat(1.0) -> X in all defined cases.
2701 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002702 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2703 if (CI->equalsInt(1))
2704 return ReplaceInstUsesWith(I, Op0);
2705 }
2706 }
Chris Lattnera2881962003-02-18 19:28:33 +00002707 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002708
2709 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2710 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002711 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002712 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002713 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002714 Op1, "tmp");
2715 InsertNewInstBefore(Add, I);
2716 Value *C1C2 = ConstantExpr::getMul(Op1,
2717 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002718 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002719
2720 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002721
2722 // Try to fold constant mul into select arguments.
2723 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002724 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002725 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002726
2727 if (isa<PHINode>(Op0))
2728 if (Instruction *NV = FoldOpIntoPhi(I))
2729 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002730 }
2731
Chris Lattnera4f445b2003-03-10 23:23:04 +00002732 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2733 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002734 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002735
Nick Lewycky0c730792008-11-21 07:33:58 +00002736 // (X / Y) * Y = X - (X % Y)
2737 // (X / Y) * -Y = (X % Y) - X
2738 {
2739 Value *Op1 = I.getOperand(1);
2740 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2741 if (!BO ||
2742 (BO->getOpcode() != Instruction::UDiv &&
2743 BO->getOpcode() != Instruction::SDiv)) {
2744 Op1 = Op0;
2745 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2746 }
2747 Value *Neg = dyn_castNegVal(Op1);
2748 if (BO && BO->hasOneUse() &&
2749 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2750 (BO->getOpcode() == Instruction::UDiv ||
2751 BO->getOpcode() == Instruction::SDiv)) {
2752 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2753
2754 Instruction *Rem;
2755 if (BO->getOpcode() == Instruction::UDiv)
2756 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2757 else
2758 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2759
2760 InsertNewInstBefore(Rem, I);
2761 Rem->takeName(BO);
2762
2763 if (Op1BO == Op1)
2764 return BinaryOperator::CreateSub(Op0BO, Rem);
2765 else
2766 return BinaryOperator::CreateSub(Rem, Op0BO);
2767 }
2768 }
2769
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002770 if (I.getType() == Type::Int1Ty)
2771 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2772
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002773 // If one of the operands of the multiply is a cast from a boolean value, then
2774 // we know the bool is either zero or one, so this is a 'masking' multiply.
2775 // See if we can simplify things based on how the boolean was originally
2776 // formed.
2777 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002778 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002779 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002780 BoolCast = CI;
2781 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002782 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002783 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002784 BoolCast = CI;
2785 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002786 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002787 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2788 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002789 bool TIS = false;
2790
Reid Spencere4d87aa2006-12-23 06:05:41 +00002791 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002792 // multiply into a shift/and combination.
2793 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002794 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2795 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002796 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002797 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002798 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002799 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002800 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002801 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002802 BoolCast->getOperand(0)->getName()+
2803 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002804
2805 // If the multiply type is not the same as the source type, sign extend
2806 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002807 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002808 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2809 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002810 Instruction::CastOps opcode =
2811 (SrcBits == DstBits ? Instruction::BitCast :
2812 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2813 V = InsertCastBefore(opcode, V, I.getType(), I);
2814 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002815
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002816 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002817 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002818 }
2819 }
2820 }
2821
Chris Lattner7e708292002-06-25 16:13:24 +00002822 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002823}
2824
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002825Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2826 bool Changed = SimplifyCommutative(I);
2827 Value *Op0 = I.getOperand(0);
2828
2829 // Simplify mul instructions with a constant RHS...
2830 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2831 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2832 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2833 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2834 if (Op1F->isExactlyValue(1.0))
2835 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2836 } else if (isa<VectorType>(Op1->getType())) {
2837 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2838 // As above, vector X*splat(1.0) -> X in all defined cases.
2839 if (Constant *Splat = Op1V->getSplatValue()) {
2840 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2841 if (F->isExactlyValue(1.0))
2842 return ReplaceInstUsesWith(I, Op0);
2843 }
2844 }
2845 }
2846
2847 // Try to fold constant mul into select arguments.
2848 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2849 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2850 return R;
2851
2852 if (isa<PHINode>(Op0))
2853 if (Instruction *NV = FoldOpIntoPhi(I))
2854 return NV;
2855 }
2856
2857 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2858 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2859 return BinaryOperator::CreateFMul(Op0v, Op1v);
2860
2861 return Changed ? &I : 0;
2862}
2863
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002864/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2865/// instruction.
2866bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2867 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2868
2869 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2870 int NonNullOperand = -1;
2871 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2872 if (ST->isNullValue())
2873 NonNullOperand = 2;
2874 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2875 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2876 if (ST->isNullValue())
2877 NonNullOperand = 1;
2878
2879 if (NonNullOperand == -1)
2880 return false;
2881
2882 Value *SelectCond = SI->getOperand(0);
2883
2884 // Change the div/rem to use 'Y' instead of the select.
2885 I.setOperand(1, SI->getOperand(NonNullOperand));
2886
2887 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2888 // problem. However, the select, or the condition of the select may have
2889 // multiple uses. Based on our knowledge that the operand must be non-zero,
2890 // propagate the known value for the select into other uses of it, and
2891 // propagate a known value of the condition into its other users.
2892
2893 // If the select and condition only have a single use, don't bother with this,
2894 // early exit.
2895 if (SI->use_empty() && SelectCond->hasOneUse())
2896 return true;
2897
2898 // Scan the current block backward, looking for other uses of SI.
2899 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2900
2901 while (BBI != BBFront) {
2902 --BBI;
2903 // If we found a call to a function, we can't assume it will return, so
2904 // information from below it cannot be propagated above it.
2905 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2906 break;
2907
2908 // Replace uses of the select or its condition with the known values.
2909 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2910 I != E; ++I) {
2911 if (*I == SI) {
2912 *I = SI->getOperand(NonNullOperand);
2913 AddToWorkList(BBI);
2914 } else if (*I == SelectCond) {
2915 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2916 ConstantInt::getFalse();
2917 AddToWorkList(BBI);
2918 }
2919 }
2920
2921 // If we past the instruction, quit looking for it.
2922 if (&*BBI == SI)
2923 SI = 0;
2924 if (&*BBI == SelectCond)
2925 SelectCond = 0;
2926
2927 // If we ran out of things to eliminate, break out of the loop.
2928 if (SelectCond == 0 && SI == 0)
2929 break;
2930
2931 }
2932 return true;
2933}
2934
2935
Reid Spencer1628cec2006-10-26 06:15:43 +00002936/// This function implements the transforms on div instructions that work
2937/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2938/// used by the visitors to those instructions.
2939/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002940Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002941 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002942
Chris Lattner50b2ca42008-02-19 06:12:18 +00002943 // undef / X -> 0 for integer.
2944 // undef / X -> undef for FP (the undef could be a snan).
2945 if (isa<UndefValue>(Op0)) {
2946 if (Op0->getType()->isFPOrFPVector())
2947 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002948 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002949 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002950
2951 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002952 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002953 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002954
Reid Spencer1628cec2006-10-26 06:15:43 +00002955 return 0;
2956}
Misha Brukmanfd939082005-04-21 23:48:37 +00002957
Reid Spencer1628cec2006-10-26 06:15:43 +00002958/// This function implements the transforms common to both integer division
2959/// instructions (udiv and sdiv). It is called by the visitors to those integer
2960/// division instructions.
2961/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002962Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002963 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2964
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002965 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002966 if (Op0 == Op1) {
2967 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2968 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2969 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2970 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2971 }
2972
2973 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2974 return ReplaceInstUsesWith(I, CI);
2975 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002976
Reid Spencer1628cec2006-10-26 06:15:43 +00002977 if (Instruction *Common = commonDivTransforms(I))
2978 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002979
2980 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2981 // This does not apply for fdiv.
2982 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2983 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002984
2985 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2986 // div X, 1 == X
2987 if (RHS->equalsInt(1))
2988 return ReplaceInstUsesWith(I, Op0);
2989
2990 // (X / C1) / C2 -> X / (C1*C2)
2991 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2992 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2993 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002994 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2995 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2996 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002997 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002998 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002999 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003000
Reid Spencerbca0e382007-03-23 20:05:17 +00003001 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003002 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3003 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3004 return R;
3005 if (isa<PHINode>(Op0))
3006 if (Instruction *NV = FoldOpIntoPhi(I))
3007 return NV;
3008 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003009 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003010
Chris Lattnera2881962003-02-18 19:28:33 +00003011 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003012 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003013 if (LHS->equalsInt(0))
3014 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3015
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003016 // It can't be division by zero, hence it must be division by one.
3017 if (I.getType() == Type::Int1Ty)
3018 return ReplaceInstUsesWith(I, Op0);
3019
Nick Lewycky895f0852008-11-27 20:21:08 +00003020 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3021 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3022 // div X, 1 == X
3023 if (X->isOne())
3024 return ReplaceInstUsesWith(I, Op0);
3025 }
3026
Reid Spencer1628cec2006-10-26 06:15:43 +00003027 return 0;
3028}
3029
3030Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3031 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3032
3033 // Handle the integer div common cases
3034 if (Instruction *Common = commonIDivTransforms(I))
3035 return Common;
3036
Reid Spencer1628cec2006-10-26 06:15:43 +00003037 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003038 // X udiv C^2 -> X >> C
3039 // Check to see if this is an unsigned division with an exact power of 2,
3040 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003041 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003042 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003043 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003044
3045 // X udiv C, where C >= signbit
3046 if (C->getValue().isNegative()) {
3047 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3048 I);
3049 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3050 ConstantInt::get(I.getType(), 1));
3051 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003052 }
3053
3054 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003055 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003056 if (RHSI->getOpcode() == Instruction::Shl &&
3057 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003058 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003059 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003060 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003061 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003062 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003063 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003064 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003065 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003066 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003067 }
3068 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003069 }
3070
Reid Spencer1628cec2006-10-26 06:15:43 +00003071 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3072 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003073 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003074 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003075 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003076 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003077 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003078 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003079 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003080 // Construct the "on true" case of the select
3081 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003082 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003083 Op0, TC, SI->getName()+".t");
3084 TSI = InsertNewInstBefore(TSI, I);
3085
3086 // Construct the "on false" case of the select
3087 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003088 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003089 Op0, FC, SI->getName()+".f");
3090 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003091
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003092 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003093 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003094 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003095 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003096 return 0;
3097}
3098
Reid Spencer1628cec2006-10-26 06:15:43 +00003099Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3100 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3101
3102 // Handle the integer div common cases
3103 if (Instruction *Common = commonIDivTransforms(I))
3104 return Common;
3105
3106 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3107 // sdiv X, -1 == -X
3108 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003109 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003110 }
3111
3112 // If the sign bits of both operands are zero (i.e. we can prove they are
3113 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003114 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003115 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003116 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003117 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003118 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003119 }
3120 }
3121
3122 return 0;
3123}
3124
3125Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3126 return commonDivTransforms(I);
3127}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003128
Reid Spencer0a783f72006-11-02 01:53:59 +00003129/// This function implements the transforms on rem instructions that work
3130/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3131/// is used by the visitors to those instructions.
3132/// @brief Transforms common to all three rem instructions
3133Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003134 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003135
Chris Lattner50b2ca42008-02-19 06:12:18 +00003136 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3137 if (I.getType()->isFPOrFPVector())
3138 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003139 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003140 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003141 if (isa<UndefValue>(Op1))
3142 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003143
3144 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003145 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3146 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003147
Reid Spencer0a783f72006-11-02 01:53:59 +00003148 return 0;
3149}
3150
3151/// This function implements the transforms common to both integer remainder
3152/// instructions (urem and srem). It is called by the visitors to those integer
3153/// remainder instructions.
3154/// @brief Common integer remainder transforms
3155Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3156 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3157
3158 if (Instruction *common = commonRemTransforms(I))
3159 return common;
3160
Dale Johannesened6af242009-01-21 00:35:19 +00003161 // 0 % X == 0 for integer, we don't need to preserve faults!
3162 if (Constant *LHS = dyn_cast<Constant>(Op0))
3163 if (LHS->isNullValue())
3164 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3165
Chris Lattner857e8cd2004-12-12 21:48:58 +00003166 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003167 // X % 0 == undef, we don't need to preserve faults!
3168 if (RHS->equalsInt(0))
3169 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3170
Chris Lattnera2881962003-02-18 19:28:33 +00003171 if (RHS->equalsInt(1)) // X % 1 == 0
3172 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3173
Chris Lattner97943922006-02-28 05:49:21 +00003174 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3175 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3176 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3177 return R;
3178 } else if (isa<PHINode>(Op0I)) {
3179 if (Instruction *NV = FoldOpIntoPhi(I))
3180 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003181 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003182
3183 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003184 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003185 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003186 }
Chris Lattnera2881962003-02-18 19:28:33 +00003187 }
3188
Reid Spencer0a783f72006-11-02 01:53:59 +00003189 return 0;
3190}
3191
3192Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3193 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3194
3195 if (Instruction *common = commonIRemTransforms(I))
3196 return common;
3197
3198 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3199 // X urem C^2 -> X and C
3200 // Check to see if this is an unsigned remainder with an exact power of 2,
3201 // if so, convert to a bitwise and.
3202 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003203 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003204 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003205 }
3206
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003207 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003208 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3209 if (RHSI->getOpcode() == Instruction::Shl &&
3210 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003211 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003212 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003213 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003214 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003215 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003216 }
3217 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003218 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003219
Reid Spencer0a783f72006-11-02 01:53:59 +00003220 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3221 // where C1&C2 are powers of two.
3222 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3223 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3224 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3225 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003226 if ((STO->getValue().isPowerOf2()) &&
3227 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003228 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003229 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003230 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003231 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003232 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003233 }
3234 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003235 }
3236
Chris Lattner3f5b8772002-05-06 16:14:14 +00003237 return 0;
3238}
3239
Reid Spencer0a783f72006-11-02 01:53:59 +00003240Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3241 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3242
Dan Gohmancff55092007-11-05 23:16:33 +00003243 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003244 if (Instruction *common = commonIRemTransforms(I))
3245 return common;
3246
3247 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003248 if (!isa<Constant>(RHSNeg) ||
3249 (isa<ConstantInt>(RHSNeg) &&
3250 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003251 // X % -Y -> X % Y
3252 AddUsesToWorkList(I);
3253 I.setOperand(1, RHSNeg);
3254 return &I;
3255 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003256
Dan Gohmancff55092007-11-05 23:16:33 +00003257 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003258 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003259 if (I.getType()->isInteger()) {
3260 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3261 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3262 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003263 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003264 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003265 }
3266
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003267 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003268 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3269 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003270
Nick Lewycky9dce8732008-12-20 16:48:00 +00003271 bool hasNegative = false;
3272 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3273 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3274 if (RHS->getValue().isNegative())
3275 hasNegative = true;
3276
3277 if (hasNegative) {
3278 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003279 for (unsigned i = 0; i != VWidth; ++i) {
3280 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3281 if (RHS->getValue().isNegative())
3282 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3283 else
3284 Elts[i] = RHS;
3285 }
3286 }
3287
3288 Constant *NewRHSV = ConstantVector::get(Elts);
3289 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003290 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003291 I.setOperand(1, NewRHSV);
3292 return &I;
3293 }
3294 }
3295 }
3296
Reid Spencer0a783f72006-11-02 01:53:59 +00003297 return 0;
3298}
3299
3300Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003301 return commonRemTransforms(I);
3302}
3303
Chris Lattner457dd822004-06-09 07:59:58 +00003304// isOneBitSet - Return true if there is exactly one bit set in the specified
3305// constant.
3306static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003307 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003308}
3309
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003310// isHighOnes - Return true if the constant is of the form 1+0+.
3311// This is the same as lowones(~X).
3312static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003313 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003314}
3315
Reid Spencere4d87aa2006-12-23 06:05:41 +00003316/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003317/// are carefully arranged to allow folding of expressions such as:
3318///
3319/// (A < B) | (A > B) --> (A != B)
3320///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003321/// Note that this is only valid if the first and second predicates have the
3322/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003323///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003324/// Three bits are used to represent the condition, as follows:
3325/// 0 A > B
3326/// 1 A == B
3327/// 2 A < B
3328///
3329/// <=> Value Definition
3330/// 000 0 Always false
3331/// 001 1 A > B
3332/// 010 2 A == B
3333/// 011 3 A >= B
3334/// 100 4 A < B
3335/// 101 5 A != B
3336/// 110 6 A <= B
3337/// 111 7 Always true
3338///
3339static unsigned getICmpCode(const ICmpInst *ICI) {
3340 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003341 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003342 case ICmpInst::ICMP_UGT: return 1; // 001
3343 case ICmpInst::ICMP_SGT: return 1; // 001
3344 case ICmpInst::ICMP_EQ: return 2; // 010
3345 case ICmpInst::ICMP_UGE: return 3; // 011
3346 case ICmpInst::ICMP_SGE: return 3; // 011
3347 case ICmpInst::ICMP_ULT: return 4; // 100
3348 case ICmpInst::ICMP_SLT: return 4; // 100
3349 case ICmpInst::ICMP_NE: return 5; // 101
3350 case ICmpInst::ICMP_ULE: return 6; // 110
3351 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003352 // True -> 7
3353 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003354 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003355 return 0;
3356 }
3357}
3358
Evan Cheng8db90722008-10-14 17:15:11 +00003359/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3360/// predicate into a three bit mask. It also returns whether it is an ordered
3361/// predicate by reference.
3362static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3363 isOrdered = false;
3364 switch (CC) {
3365 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3366 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003367 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3368 case FCmpInst::FCMP_UGT: return 1; // 001
3369 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3370 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003371 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3372 case FCmpInst::FCMP_UGE: return 3; // 011
3373 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3374 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003375 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3376 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003377 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3378 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003379 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003380 default:
3381 // Not expecting FCMP_FALSE and FCMP_TRUE;
3382 assert(0 && "Unexpected FCmp predicate!");
3383 return 0;
3384 }
3385}
3386
Reid Spencere4d87aa2006-12-23 06:05:41 +00003387/// getICmpValue - This is the complement of getICmpCode, which turns an
3388/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003389/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003390/// of predicate to use in the new icmp instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003391static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3392 switch (code) {
3393 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003394 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003395 case 1:
3396 if (sign)
3397 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3398 else
3399 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3400 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3401 case 3:
3402 if (sign)
3403 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3404 else
3405 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3406 case 4:
3407 if (sign)
3408 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3409 else
3410 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3411 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3412 case 6:
3413 if (sign)
3414 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3415 else
3416 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003417 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003418 }
3419}
3420
Evan Cheng8db90722008-10-14 17:15:11 +00003421/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3422/// opcode and two operands into either a FCmp instruction. isordered is passed
3423/// in to determine which kind of predicate to use in the new fcmp instruction.
3424static Value *getFCmpValue(bool isordered, unsigned code,
3425 Value *LHS, Value *RHS) {
3426 switch (code) {
Evan Cheng4990b252008-10-14 18:13:38 +00003427 default: assert(0 && "Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003428 case 0:
3429 if (isordered)
3430 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3431 else
3432 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3433 case 1:
3434 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003435 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3436 else
3437 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003438 case 2:
3439 if (isordered)
3440 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3441 else
3442 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003443 case 3:
3444 if (isordered)
3445 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3446 else
3447 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3448 case 4:
3449 if (isordered)
3450 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3451 else
3452 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3453 case 5:
3454 if (isordered)
Evan Cheng4990b252008-10-14 18:13:38 +00003455 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3456 else
3457 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3458 case 6:
3459 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003460 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3461 else
3462 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng40300622008-10-14 18:44:08 +00003463 case 7: return ConstantInt::getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003464 }
3465}
3466
Chris Lattnerb9553d62008-11-16 04:55:20 +00003467/// PredicatesFoldable - Return true if both predicates match sign or if at
3468/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003469static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3470 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003471 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3472 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003473}
3474
3475namespace {
3476// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3477struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003478 InstCombiner &IC;
3479 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003480 ICmpInst::Predicate pred;
3481 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3482 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3483 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003484 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003485 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3486 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003487 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3488 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003489 return false;
3490 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003491 Instruction *apply(Instruction &Log) const {
3492 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3493 if (ICI->getOperand(0) != LHS) {
3494 assert(ICI->getOperand(1) == LHS);
3495 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003496 }
3497
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003498 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003499 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003500 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003501 unsigned Code;
3502 switch (Log.getOpcode()) {
3503 case Instruction::And: Code = LHSCode & RHSCode; break;
3504 case Instruction::Or: Code = LHSCode | RHSCode; break;
3505 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003506 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003507 }
3508
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003509 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3510 ICmpInst::isSignedPredicate(ICI->getPredicate());
3511
3512 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003513 if (Instruction *I = dyn_cast<Instruction>(RV))
3514 return I;
3515 // Otherwise, it's a constant boolean value...
3516 return IC.ReplaceInstUsesWith(Log, RV);
3517 }
3518};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003519} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003520
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003521// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3522// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003523// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003524Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003525 ConstantInt *OpRHS,
3526 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003527 BinaryOperator &TheAnd) {
3528 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003529 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003530 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003531 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003532
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003533 switch (Op->getOpcode()) {
3534 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003535 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003536 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003537 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003538 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003539 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003540 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003541 }
3542 break;
3543 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003544 if (Together == AndRHS) // (X | C) & C --> C
3545 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003546
Chris Lattner6e7ba452005-01-01 16:22:27 +00003547 if (Op->hasOneUse() && Together != OpRHS) {
3548 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003549 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003550 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003551 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003552 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003553 }
3554 break;
3555 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003556 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003557 // Adding a one to a single bit bit-field should be turned into an XOR
3558 // of the bit. First thing to check is to see if this AND is with a
3559 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003560 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003561
3562 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003563 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003564 // Ok, at this point, we know that we are masking the result of the
3565 // ADD down to exactly one bit. If the constant we are adding has
3566 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003567 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003568
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003569 // Check to see if any bits below the one bit set in AndRHSV are set.
3570 if ((AddRHS & (AndRHSV-1)) == 0) {
3571 // If not, the only thing that can effect the output of the AND is
3572 // the bit specified by AndRHSV. If that bit is set, the effect of
3573 // the XOR is to toggle the bit. If it is clear, then the ADD has
3574 // no effect.
3575 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3576 TheAnd.setOperand(0, X);
3577 return &TheAnd;
3578 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003579 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003580 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003581 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003582 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003583 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003584 }
3585 }
3586 }
3587 }
3588 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003589
3590 case Instruction::Shl: {
3591 // We know that the AND will not produce any of the bits shifted in, so if
3592 // the anded constant includes them, clear them now!
3593 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003594 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003595 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003596 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3597 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003598
Zhou Sheng290bec52007-03-29 08:15:12 +00003599 if (CI->getValue() == ShlMask) {
3600 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003601 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3602 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003603 TheAnd.setOperand(1, CI);
3604 return &TheAnd;
3605 }
3606 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003607 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003608 case Instruction::LShr:
3609 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003610 // We know that the AND will not produce any of the bits shifted in, so if
3611 // the anded constant includes them, clear them now! This only applies to
3612 // unsigned shifts, because a signed shr may bring in set bits!
3613 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003614 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003615 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003616 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3617 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003618
Zhou Sheng290bec52007-03-29 08:15:12 +00003619 if (CI->getValue() == ShrMask) {
3620 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003621 return ReplaceInstUsesWith(TheAnd, Op);
3622 } else if (CI != AndRHS) {
3623 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3624 return &TheAnd;
3625 }
3626 break;
3627 }
3628 case Instruction::AShr:
3629 // Signed shr.
3630 // See if this is shifting in some sign extension, then masking it out
3631 // with an and.
3632 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003633 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003634 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003635 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3636 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003637 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003638 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003639 // Make the argument unsigned.
3640 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003641 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003642 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003643 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003644 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003645 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003646 }
3647 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003648 }
3649 return 0;
3650}
3651
Chris Lattner8b170942002-08-09 23:47:40 +00003652
Chris Lattnera96879a2004-09-29 17:40:11 +00003653/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3654/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003655/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3656/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003657/// insert new instructions.
3658Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003659 bool isSigned, bool Inside,
3660 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003661 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003662 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003663 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003664
Chris Lattnera96879a2004-09-29 17:40:11 +00003665 if (Inside) {
3666 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003667 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003668
Reid Spencere4d87aa2006-12-23 06:05:41 +00003669 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003670 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003671 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003672 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3673 return new ICmpInst(pred, V, Hi);
3674 }
3675
3676 // Emit V-Lo <u Hi-Lo
3677 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003678 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003679 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003680 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3681 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003682 }
3683
3684 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003685 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003686
Reid Spencere4e40032007-03-21 23:19:50 +00003687 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003688 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003689 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003690 ICmpInst::Predicate pred = (isSigned ?
3691 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3692 return new ICmpInst(pred, V, Hi);
3693 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003694
Reid Spencere4e40032007-03-21 23:19:50 +00003695 // Emit V-Lo >u Hi-1-Lo
3696 // Note that Hi has already had one subtracted from it, above.
3697 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003698 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003699 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003700 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3701 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003702}
3703
Chris Lattner7203e152005-09-18 07:22:02 +00003704// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3705// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3706// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3707// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003708static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003709 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003710 uint32_t BitWidth = Val->getType()->getBitWidth();
3711 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003712
3713 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003714 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003715 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003716 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003717 return true;
3718}
3719
Chris Lattner7203e152005-09-18 07:22:02 +00003720/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3721/// where isSub determines whether the operator is a sub. If we can fold one of
3722/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003723///
3724/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3725/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3726/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3727///
3728/// return (A +/- B).
3729///
3730Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003731 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003732 Instruction &I) {
3733 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3734 if (!LHSI || LHSI->getNumOperands() != 2 ||
3735 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3736
3737 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3738
3739 switch (LHSI->getOpcode()) {
3740 default: return 0;
3741 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003742 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003743 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003744 if ((Mask->getValue().countLeadingZeros() +
3745 Mask->getValue().countPopulation()) ==
3746 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003747 break;
3748
3749 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3750 // part, we don't need any explicit masks to take them out of A. If that
3751 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003752 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003753 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003754 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003755 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003756 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003757 break;
3758 }
3759 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003760 return 0;
3761 case Instruction::Or:
3762 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003763 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003764 if ((Mask->getValue().countLeadingZeros() +
3765 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003766 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003767 break;
3768 return 0;
3769 }
3770
3771 Instruction *New;
3772 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003773 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003774 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003775 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003776 return InsertNewInstBefore(New, I);
3777}
3778
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003779/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3780Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3781 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003782 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003783 ConstantInt *LHSCst, *RHSCst;
3784 ICmpInst::Predicate LHSCC, RHSCC;
3785
Chris Lattnerea065fb2008-11-16 05:10:52 +00003786 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003787 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerea065fb2008-11-16 05:10:52 +00003788 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003789 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003790
3791 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3792 // where C is a power of 2
3793 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3794 LHSCst->getValue().isPowerOf2()) {
3795 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3796 InsertNewInstBefore(NewOr, I);
3797 return new ICmpInst(LHSCC, NewOr, LHSCst);
3798 }
3799
3800 // From here on, we only handle:
3801 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3802 if (Val != Val2) return 0;
3803
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003804 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3805 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3806 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3807 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3808 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3809 return 0;
3810
3811 // We can't fold (ugt x, C) & (sgt x, C2).
3812 if (!PredicatesFoldable(LHSCC, RHSCC))
3813 return 0;
3814
3815 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003816 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003817 if (ICmpInst::isSignedPredicate(LHSCC) ||
3818 (ICmpInst::isEquality(LHSCC) &&
3819 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003820 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003821 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003822 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3823
3824 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003825 std::swap(LHS, RHS);
3826 std::swap(LHSCst, RHSCst);
3827 std::swap(LHSCC, RHSCC);
3828 }
3829
3830 // At this point, we know we have have two icmp instructions
3831 // comparing a value against two constants and and'ing the result
3832 // together. Because of the above check, we know that we only have
3833 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3834 // (from the FoldICmpLogical check above), that the two constants
3835 // are not equal and that the larger constant is on the RHS
3836 assert(LHSCst != RHSCst && "Compares not folded above?");
3837
3838 switch (LHSCC) {
3839 default: assert(0 && "Unknown integer condition code!");
3840 case ICmpInst::ICMP_EQ:
3841 switch (RHSCC) {
3842 default: assert(0 && "Unknown integer condition code!");
3843 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3844 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3845 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3846 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3847 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3848 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3849 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3850 return ReplaceInstUsesWith(I, LHS);
3851 }
3852 case ICmpInst::ICMP_NE:
3853 switch (RHSCC) {
3854 default: assert(0 && "Unknown integer condition code!");
3855 case ICmpInst::ICMP_ULT:
3856 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3857 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3858 break; // (X != 13 & X u< 15) -> no change
3859 case ICmpInst::ICMP_SLT:
3860 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3861 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3862 break; // (X != 13 & X s< 15) -> no change
3863 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3864 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3865 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3866 return ReplaceInstUsesWith(I, RHS);
3867 case ICmpInst::ICMP_NE:
3868 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3869 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3870 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3871 Val->getName()+".off");
3872 InsertNewInstBefore(Add, I);
3873 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3874 ConstantInt::get(Add->getType(), 1));
3875 }
3876 break; // (X != 13 & X != 15) -> no change
3877 }
3878 break;
3879 case ICmpInst::ICMP_ULT:
3880 switch (RHSCC) {
3881 default: assert(0 && "Unknown integer condition code!");
3882 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3883 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3884 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3885 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3886 break;
3887 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3888 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3889 return ReplaceInstUsesWith(I, LHS);
3890 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3891 break;
3892 }
3893 break;
3894 case ICmpInst::ICMP_SLT:
3895 switch (RHSCC) {
3896 default: assert(0 && "Unknown integer condition code!");
3897 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3898 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3899 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3900 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3901 break;
3902 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3903 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3904 return ReplaceInstUsesWith(I, LHS);
3905 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3906 break;
3907 }
3908 break;
3909 case ICmpInst::ICMP_UGT:
3910 switch (RHSCC) {
3911 default: assert(0 && "Unknown integer condition code!");
3912 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3913 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3914 return ReplaceInstUsesWith(I, RHS);
3915 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3916 break;
3917 case ICmpInst::ICMP_NE:
3918 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3919 return new ICmpInst(LHSCC, Val, RHSCst);
3920 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003921 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003922 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3923 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3924 break;
3925 }
3926 break;
3927 case ICmpInst::ICMP_SGT:
3928 switch (RHSCC) {
3929 default: assert(0 && "Unknown integer condition code!");
3930 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3931 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3932 return ReplaceInstUsesWith(I, RHS);
3933 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3934 break;
3935 case ICmpInst::ICMP_NE:
3936 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3937 return new ICmpInst(LHSCC, Val, RHSCst);
3938 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003939 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003940 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3941 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3942 break;
3943 }
3944 break;
3945 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003946
3947 return 0;
3948}
3949
3950
Chris Lattner7e708292002-06-25 16:13:24 +00003951Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003952 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003953 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003954
Chris Lattnere87597f2004-10-16 18:11:37 +00003955 if (isa<UndefValue>(Op1)) // X & undef -> 0
3956 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3957
Chris Lattner6e7ba452005-01-01 16:22:27 +00003958 // and X, X = X
3959 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003960 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003961
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003962 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003963 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003964 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00003965 if (SimplifyDemandedInstructionBits(I))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003966 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003967 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003968 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003969 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003970 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003971 } else if (isa<ConstantAggregateZero>(Op1)) {
3972 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003973 }
3974 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003975
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003976 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003977 const APInt& AndRHSMask = AndRHS->getValue();
3978 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003979
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003980 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003981 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003982 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003983 Value *Op0LHS = Op0I->getOperand(0);
3984 Value *Op0RHS = Op0I->getOperand(1);
3985 switch (Op0I->getOpcode()) {
3986 case Instruction::Xor:
3987 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003988 // If the mask is only needed on one incoming arm, push it up.
3989 if (Op0I->hasOneUse()) {
3990 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3991 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003992 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003993 Op0RHS->getName()+".masked");
3994 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003995 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003996 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003997 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003998 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003999 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4000 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004001 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004002 Op0LHS->getName()+".masked");
4003 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004004 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004005 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4006 }
4007 }
4008
Chris Lattner6e7ba452005-01-01 16:22:27 +00004009 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004010 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004011 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4012 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4013 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4014 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004015 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004016 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004017 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004018 break;
4019
4020 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004021 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4022 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4023 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4024 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004025 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004026
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004027 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4028 // has 1's for all bits that the subtraction with A might affect.
4029 if (Op0I->hasOneUse()) {
4030 uint32_t BitWidth = AndRHSMask.getBitWidth();
4031 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4032 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4033
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004034 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004035 if (!(A && A->isZero()) && // avoid infinite recursion.
4036 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004037 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4038 InsertNewInstBefore(NewNeg, I);
4039 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4040 }
4041 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004042 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004043
4044 case Instruction::Shl:
4045 case Instruction::LShr:
4046 // (1 << x) & 1 --> zext(x == 0)
4047 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004048 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004049 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
4050 Constant::getNullValue(I.getType()));
4051 InsertNewInstBefore(NewICmp, I);
4052 return new ZExtInst(NewICmp, I.getType());
4053 }
4054 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004055 }
4056
Chris Lattner58403262003-07-23 19:25:52 +00004057 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004058 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004059 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004060 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004061 // If this is an integer truncation or change from signed-to-unsigned, and
4062 // if the source is an and/or with immediate, transform it. This
4063 // frequently occurs for bitfield accesses.
4064 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004065 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004066 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004067 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004068 if (CastOp->getOpcode() == Instruction::And) {
4069 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004070 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4071 // This will fold the two constants together, which may allow
4072 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004073 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004074 CastOp->getOperand(0), I.getType(),
4075 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004076 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004077 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00004078 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00004079 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004080 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004081 } else if (CastOp->getOpcode() == Instruction::Or) {
4082 // Change: and (cast (or X, C1) to T), C2
4083 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00004084 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00004085 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4086 return ReplaceInstUsesWith(I, AndRHS);
4087 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004088 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004089 }
Chris Lattner06782f82003-07-23 19:36:21 +00004090 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004091
4092 // Try to fold constant and into select arguments.
4093 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004094 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004095 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004096 if (isa<PHINode>(Op0))
4097 if (Instruction *NV = FoldOpIntoPhi(I))
4098 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004099 }
4100
Chris Lattner8d969642003-03-10 23:06:50 +00004101 Value *Op0NotVal = dyn_castNotVal(Op0);
4102 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004103
Chris Lattner5b62aa72004-06-18 06:07:51 +00004104 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4105 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4106
Misha Brukmancb6267b2004-07-30 12:50:08 +00004107 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004108 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004109 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004110 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004111 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004112 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004113 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004114
4115 {
Chris Lattner003b6202007-06-15 05:58:24 +00004116 Value *A = 0, *B = 0, *C = 0, *D = 0;
4117 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004118 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4119 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004120
4121 // (A|B) & ~(A&B) -> A^B
4122 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4123 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004124 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004125 }
4126 }
4127
4128 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004129 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4130 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004131
4132 // ~(A&B) & (A|B) -> A^B
4133 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4134 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004135 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004136 }
4137 }
Chris Lattner64daab52006-04-01 08:03:55 +00004138
4139 if (Op0->hasOneUse() &&
4140 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4141 if (A == Op1) { // (A^B)&A -> A&(A^B)
4142 I.swapOperands(); // Simplify below
4143 std::swap(Op0, Op1);
4144 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4145 cast<BinaryOperator>(Op0)->swapOperands();
4146 I.swapOperands(); // Simplify below
4147 std::swap(Op0, Op1);
4148 }
4149 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004150
Chris Lattner64daab52006-04-01 08:03:55 +00004151 if (Op1->hasOneUse() &&
4152 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4153 if (B == Op0) { // B&(A^B) -> B&(B^A)
4154 cast<BinaryOperator>(Op1)->swapOperands();
4155 std::swap(A, B);
4156 }
4157 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004158 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004159 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004160 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004161 }
4162 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004163
4164 // (A&((~A)|B)) -> A&B
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004165 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4166 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4167 return BinaryOperator::CreateAnd(A, Op1);
4168 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4169 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4170 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004171 }
4172
Reid Spencere4d87aa2006-12-23 06:05:41 +00004173 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4174 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4175 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004176 return R;
4177
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004178 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4179 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4180 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004181 }
4182
Chris Lattner6fc205f2006-05-05 06:39:07 +00004183 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004184 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4185 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4186 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4187 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004188 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004189 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004190 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4191 I.getType(), TD) &&
4192 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4193 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004194 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004195 Op1C->getOperand(0),
4196 I.getName());
4197 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004198 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004199 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004200 }
Chris Lattnere511b742006-11-14 07:46:50 +00004201
4202 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004203 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4204 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4205 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004206 SI0->getOperand(1) == SI1->getOperand(1) &&
4207 (SI0->hasOneUse() || SI1->hasOneUse())) {
4208 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004209 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004210 SI1->getOperand(0),
4211 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004212 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004213 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004214 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004215 }
4216
Evan Cheng8db90722008-10-14 17:15:11 +00004217 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004218 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4219 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4220 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004221 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4222 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004223 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4224 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4225 // If either of the constants are nans, then the whole thing returns
4226 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004227 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004228 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4229 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4230 RHS->getOperand(0));
4231 }
Evan Cheng8db90722008-10-14 17:15:11 +00004232 } else {
4233 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4234 FCmpInst::Predicate Op0CC, Op1CC;
4235 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4236 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Cheng4990b252008-10-14 18:13:38 +00004237 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4238 // Swap RHS operands to match LHS.
4239 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4240 std::swap(Op1LHS, Op1RHS);
4241 }
Evan Cheng8db90722008-10-14 17:15:11 +00004242 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4243 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4244 if (Op0CC == Op1CC)
4245 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4246 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4247 Op1CC == FCmpInst::FCMP_FALSE)
4248 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4249 else if (Op0CC == FCmpInst::FCMP_TRUE)
4250 return ReplaceInstUsesWith(I, Op1);
4251 else if (Op1CC == FCmpInst::FCMP_TRUE)
4252 return ReplaceInstUsesWith(I, Op0);
4253 bool Op0Ordered;
4254 bool Op1Ordered;
4255 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4256 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4257 if (Op1Pred == 0) {
4258 std::swap(Op0, Op1);
4259 std::swap(Op0Pred, Op1Pred);
4260 std::swap(Op0Ordered, Op1Ordered);
4261 }
4262 if (Op0Pred == 0) {
4263 // uno && ueq -> uno && (uno || eq) -> ueq
4264 // ord && olt -> ord && (ord && lt) -> olt
4265 if (Op0Ordered == Op1Ordered)
4266 return ReplaceInstUsesWith(I, Op1);
4267 // uno && oeq -> uno && (ord && eq) -> false
4268 // uno && ord -> false
4269 if (!Op0Ordered)
4270 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4271 // ord && ueq -> ord && (uno || eq) -> oeq
4272 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4273 Op0LHS, Op0RHS));
4274 }
4275 }
4276 }
4277 }
Chris Lattner99c65742007-10-24 05:38:08 +00004278 }
4279 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004280
Chris Lattner7e708292002-06-25 16:13:24 +00004281 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004282}
4283
Chris Lattner8c34cd22008-10-05 02:13:19 +00004284/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4285/// capable of providing pieces of a bswap. The subexpression provides pieces
4286/// of a bswap if it is proven that each of the non-zero bytes in the output of
4287/// the expression came from the corresponding "byte swapped" byte in some other
4288/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4289/// we know that the expression deposits the low byte of %X into the high byte
4290/// of the bswap result and that all other bytes are zero. This expression is
4291/// accepted, the high byte of ByteValues is set to X to indicate a correct
4292/// match.
4293///
4294/// This function returns true if the match was unsuccessful and false if so.
4295/// On entry to the function the "OverallLeftShift" is a signed integer value
4296/// indicating the number of bytes that the subexpression is later shifted. For
4297/// example, if the expression is later right shifted by 16 bits, the
4298/// OverallLeftShift value would be -2 on entry. This is used to specify which
4299/// byte of ByteValues is actually being set.
4300///
4301/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4302/// byte is masked to zero by a user. For example, in (X & 255), X will be
4303/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4304/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4305/// always in the local (OverallLeftShift) coordinate space.
4306///
4307static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4308 SmallVector<Value*, 8> &ByteValues) {
4309 if (Instruction *I = dyn_cast<Instruction>(V)) {
4310 // If this is an or instruction, it may be an inner node of the bswap.
4311 if (I->getOpcode() == Instruction::Or) {
4312 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4313 ByteValues) ||
4314 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4315 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004316 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004317
4318 // If this is a logical shift by a constant multiple of 8, recurse with
4319 // OverallLeftShift and ByteMask adjusted.
4320 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4321 unsigned ShAmt =
4322 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4323 // Ensure the shift amount is defined and of a byte value.
4324 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4325 return true;
4326
4327 unsigned ByteShift = ShAmt >> 3;
4328 if (I->getOpcode() == Instruction::Shl) {
4329 // X << 2 -> collect(X, +2)
4330 OverallLeftShift += ByteShift;
4331 ByteMask >>= ByteShift;
4332 } else {
4333 // X >>u 2 -> collect(X, -2)
4334 OverallLeftShift -= ByteShift;
4335 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004336 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004337 }
4338
4339 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4340 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4341
4342 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4343 ByteValues);
4344 }
4345
4346 // If this is a logical 'and' with a mask that clears bytes, clear the
4347 // corresponding bytes in ByteMask.
4348 if (I->getOpcode() == Instruction::And &&
4349 isa<ConstantInt>(I->getOperand(1))) {
4350 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4351 unsigned NumBytes = ByteValues.size();
4352 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4353 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4354
4355 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4356 // If this byte is masked out by a later operation, we don't care what
4357 // the and mask is.
4358 if ((ByteMask & (1 << i)) == 0)
4359 continue;
4360
4361 // If the AndMask is all zeros for this byte, clear the bit.
4362 APInt MaskB = AndMask & Byte;
4363 if (MaskB == 0) {
4364 ByteMask &= ~(1U << i);
4365 continue;
4366 }
4367
4368 // If the AndMask is not all ones for this byte, it's not a bytezap.
4369 if (MaskB != Byte)
4370 return true;
4371
4372 // Otherwise, this byte is kept.
4373 }
4374
4375 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4376 ByteValues);
4377 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004378 }
4379
Chris Lattner8c34cd22008-10-05 02:13:19 +00004380 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4381 // the input value to the bswap. Some observations: 1) if more than one byte
4382 // is demanded from this input, then it could not be successfully assembled
4383 // into a byteswap. At least one of the two bytes would not be aligned with
4384 // their ultimate destination.
4385 if (!isPowerOf2_32(ByteMask)) return true;
4386 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004387
Chris Lattner8c34cd22008-10-05 02:13:19 +00004388 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4389 // is demanded, it needs to go into byte 0 of the result. This means that the
4390 // byte needs to be shifted until it lands in the right byte bucket. The
4391 // shift amount depends on the position: if the byte is coming from the high
4392 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4393 // low part, it must be shifted left.
4394 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4395 if (InputByteNo < ByteValues.size()/2) {
4396 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4397 return true;
4398 } else {
4399 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4400 return true;
4401 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004402
4403 // If the destination byte value is already defined, the values are or'd
4404 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004405 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004406 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004407 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004408 return false;
4409}
4410
4411/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4412/// If so, insert the new bswap intrinsic and return it.
4413Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004414 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004415 if (!ITy || ITy->getBitWidth() % 16 ||
4416 // ByteMask only allows up to 32-byte values.
4417 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004418 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004419
4420 /// ByteValues - For each byte of the result, we keep track of which value
4421 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004422 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004423 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004424
4425 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004426 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4427 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004428 return 0;
4429
4430 // Check to see if all of the bytes come from the same value.
4431 Value *V = ByteValues[0];
4432 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4433
4434 // Check to make sure that all of the bytes come from the same value.
4435 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4436 if (ByteValues[i] != V)
4437 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004438 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004439 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004440 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004441 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004442}
4443
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004444/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4445/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4446/// we can simplify this expression to "cond ? C : D or B".
4447static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4448 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004449 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004450 Value *Cond = 0;
Chris Lattner159c35b2009-01-05 23:53:12 +00004451 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004452 return 0;
4453
Chris Lattnera6a474d2008-11-16 04:26:55 +00004454 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner159c35b2009-01-05 23:53:12 +00004455 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004456 return SelectInst::Create(Cond, C, B);
Chris Lattner159c35b2009-01-05 23:53:12 +00004457 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004458 return SelectInst::Create(Cond, C, B);
4459 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner159c35b2009-01-05 23:53:12 +00004460 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004461 return SelectInst::Create(Cond, C, D);
Chris Lattner159c35b2009-01-05 23:53:12 +00004462 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004463 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004464 return 0;
4465}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004466
Chris Lattner69d4ced2008-11-16 05:20:07 +00004467/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4468Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4469 ICmpInst *LHS, ICmpInst *RHS) {
4470 Value *Val, *Val2;
4471 ConstantInt *LHSCst, *RHSCst;
4472 ICmpInst::Predicate LHSCC, RHSCC;
4473
4474 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4475 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4476 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4477 return 0;
4478
4479 // From here on, we only handle:
4480 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4481 if (Val != Val2) return 0;
4482
4483 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4484 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4485 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4486 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4487 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4488 return 0;
4489
4490 // We can't fold (ugt x, C) | (sgt x, C2).
4491 if (!PredicatesFoldable(LHSCC, RHSCC))
4492 return 0;
4493
4494 // Ensure that the larger constant is on the RHS.
4495 bool ShouldSwap;
4496 if (ICmpInst::isSignedPredicate(LHSCC) ||
4497 (ICmpInst::isEquality(LHSCC) &&
4498 ICmpInst::isSignedPredicate(RHSCC)))
4499 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4500 else
4501 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4502
4503 if (ShouldSwap) {
4504 std::swap(LHS, RHS);
4505 std::swap(LHSCst, RHSCst);
4506 std::swap(LHSCC, RHSCC);
4507 }
4508
4509 // At this point, we know we have have two icmp instructions
4510 // comparing a value against two constants and or'ing the result
4511 // together. Because of the above check, we know that we only have
4512 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4513 // FoldICmpLogical check above), that the two constants are not
4514 // equal.
4515 assert(LHSCst != RHSCst && "Compares not folded above?");
4516
4517 switch (LHSCC) {
4518 default: assert(0 && "Unknown integer condition code!");
4519 case ICmpInst::ICMP_EQ:
4520 switch (RHSCC) {
4521 default: assert(0 && "Unknown integer condition code!");
4522 case ICmpInst::ICMP_EQ:
4523 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4524 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4525 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4526 Val->getName()+".off");
4527 InsertNewInstBefore(Add, I);
4528 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4529 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4530 }
4531 break; // (X == 13 | X == 15) -> no change
4532 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4533 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4534 break;
4535 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4536 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4537 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4538 return ReplaceInstUsesWith(I, RHS);
4539 }
4540 break;
4541 case ICmpInst::ICMP_NE:
4542 switch (RHSCC) {
4543 default: assert(0 && "Unknown integer condition code!");
4544 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4545 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4546 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4547 return ReplaceInstUsesWith(I, LHS);
4548 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4549 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4550 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4551 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4552 }
4553 break;
4554 case ICmpInst::ICMP_ULT:
4555 switch (RHSCC) {
4556 default: assert(0 && "Unknown integer condition code!");
4557 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4558 break;
4559 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4560 // If RHSCst is [us]MAXINT, it is always false. Not handling
4561 // this can cause overflow.
4562 if (RHSCst->isMaxValue(false))
4563 return ReplaceInstUsesWith(I, LHS);
4564 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4565 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4566 break;
4567 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4568 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4569 return ReplaceInstUsesWith(I, RHS);
4570 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4571 break;
4572 }
4573 break;
4574 case ICmpInst::ICMP_SLT:
4575 switch (RHSCC) {
4576 default: assert(0 && "Unknown integer condition code!");
4577 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4578 break;
4579 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4580 // If RHSCst is [us]MAXINT, it is always false. Not handling
4581 // this can cause overflow.
4582 if (RHSCst->isMaxValue(true))
4583 return ReplaceInstUsesWith(I, LHS);
4584 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4585 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4586 break;
4587 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4588 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4589 return ReplaceInstUsesWith(I, RHS);
4590 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4591 break;
4592 }
4593 break;
4594 case ICmpInst::ICMP_UGT:
4595 switch (RHSCC) {
4596 default: assert(0 && "Unknown integer condition code!");
4597 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4598 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4599 return ReplaceInstUsesWith(I, LHS);
4600 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4601 break;
4602 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4603 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4604 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4605 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4606 break;
4607 }
4608 break;
4609 case ICmpInst::ICMP_SGT:
4610 switch (RHSCC) {
4611 default: assert(0 && "Unknown integer condition code!");
4612 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4613 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4614 return ReplaceInstUsesWith(I, LHS);
4615 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4616 break;
4617 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4618 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4619 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4620 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4621 break;
4622 }
4623 break;
4624 }
4625 return 0;
4626}
4627
Bill Wendlinga698a472008-12-01 08:23:25 +00004628/// FoldOrWithConstants - This helper function folds:
4629///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004630/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004631///
4632/// into:
4633///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004634/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004635///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004636/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004637Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004638 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004639 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4640 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004641
Bill Wendling286a0542008-12-02 06:24:20 +00004642 Value *V1 = 0;
4643 ConstantInt *CI2 = 0;
4644 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004645
Bill Wendling29976b92008-12-02 06:18:11 +00004646 APInt Xor = CI1->getValue() ^ CI2->getValue();
4647 if (!Xor.isAllOnesValue()) return 0;
4648
Bill Wendling286a0542008-12-02 06:24:20 +00004649 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004650 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004651 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4652 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004653 }
4654
4655 return 0;
4656}
4657
Chris Lattner7e708292002-06-25 16:13:24 +00004658Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004659 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004660 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004661
Chris Lattner42593e62007-03-24 23:56:43 +00004662 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004663 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004664
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004665 // or X, X = X
4666 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004667 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004668
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004669 // See if we can simplify any instructions used by the instruction whose sole
4670 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004671 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004672 if (SimplifyDemandedInstructionBits(I))
Chris Lattner42593e62007-03-24 23:56:43 +00004673 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004674 } else if (isa<ConstantAggregateZero>(Op1)) {
4675 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4676 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4677 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4678 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004679 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004680
4681
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004682
Chris Lattner3f5b8772002-05-06 16:14:14 +00004683 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004684 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004685 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004686 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4687 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004688 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004689 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004690 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004691 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004692 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004693 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004694
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004695 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4696 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004697 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004698 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004699 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004700 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004701 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004702 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004703
4704 // Try to fold constant and into select arguments.
4705 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004706 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004707 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004708 if (isa<PHINode>(Op0))
4709 if (Instruction *NV = FoldOpIntoPhi(I))
4710 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004711 }
4712
Chris Lattner4f637d42006-01-06 17:59:59 +00004713 Value *A = 0, *B = 0;
4714 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004715
4716 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4717 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4718 return ReplaceInstUsesWith(I, Op1);
4719 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4720 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4721 return ReplaceInstUsesWith(I, Op0);
4722
Chris Lattner6423d4c2006-07-10 20:25:24 +00004723 // (A | B) | C and A | (B | C) -> bswap if possible.
4724 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004725 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004726 match(Op1, m_Or(m_Value(), m_Value())) ||
4727 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4728 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004729 if (Instruction *BSwap = MatchBSwap(I))
4730 return BSwap;
4731 }
4732
Chris Lattner6e4c6492005-05-09 04:58:36 +00004733 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4734 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004735 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004736 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004737 InsertNewInstBefore(NOr, I);
4738 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004739 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004740 }
4741
4742 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4743 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004744 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004745 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004746 InsertNewInstBefore(NOr, I);
4747 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004748 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004749 }
4750
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004751 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004752 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004753 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4754 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004755 Value *V1 = 0, *V2 = 0, *V3 = 0;
4756 C1 = dyn_cast<ConstantInt>(C);
4757 C2 = dyn_cast<ConstantInt>(D);
4758 if (C1 && C2) { // (A & C1)|(B & C2)
4759 // If we have: ((V + N) & C1) | (V & C2)
4760 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4761 // replace with V+N.
4762 if (C1->getValue() == ~C2->getValue()) {
4763 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4764 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4765 // Add commutes, try both ways.
4766 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4767 return ReplaceInstUsesWith(I, A);
4768 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4769 return ReplaceInstUsesWith(I, A);
4770 }
4771 // Or commutes, try both ways.
4772 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4773 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4774 // Add commutes, try both ways.
4775 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4776 return ReplaceInstUsesWith(I, B);
4777 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4778 return ReplaceInstUsesWith(I, B);
4779 }
4780 }
Chris Lattner044e5332007-04-08 08:01:49 +00004781 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004782 }
4783
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004784 // Check to see if we have any common things being and'ed. If so, find the
4785 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004786 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4787 if (A == B) // (A & C)|(A & D) == A & (C|D)
4788 V1 = A, V2 = C, V3 = D;
4789 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4790 V1 = A, V2 = B, V3 = C;
4791 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4792 V1 = C, V2 = A, V3 = D;
4793 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4794 V1 = C, V2 = A, V3 = B;
4795
4796 if (V1) {
4797 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004798 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4799 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004800 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004801 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004802
Dan Gohman1975d032008-10-30 20:40:10 +00004803 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004804 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4805 return Match;
4806 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4807 return Match;
4808 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4809 return Match;
4810 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4811 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004812
Bill Wendlingb01865c2008-11-30 13:52:49 +00004813 // ((A&~B)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004814 if ((match(C, m_Not(m_Specific(D))) &&
4815 match(B, m_Not(m_Specific(A)))))
4816 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004817 // ((~B&A)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004818 if ((match(A, m_Not(m_Specific(D))) &&
4819 match(B, m_Not(m_Specific(C)))))
4820 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004821 // ((A&~B)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004822 if ((match(C, m_Not(m_Specific(B))) &&
4823 match(D, m_Not(m_Specific(A)))))
4824 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004825 // ((~B&A)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004826 if ((match(A, m_Not(m_Specific(B))) &&
4827 match(D, m_Not(m_Specific(C)))))
4828 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004829 }
Chris Lattnere511b742006-11-14 07:46:50 +00004830
4831 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004832 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4833 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4834 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004835 SI0->getOperand(1) == SI1->getOperand(1) &&
4836 (SI0->hasOneUse() || SI1->hasOneUse())) {
4837 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004838 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004839 SI1->getOperand(0),
4840 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004841 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004842 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004843 }
4844 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004845
Bill Wendlingb3833d12008-12-01 01:07:11 +00004846 // ((A|B)&1)|(B&-2) -> (A&1) | B
4847 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4848 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004849 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004850 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004851 }
4852 // (B&-2)|((A|B)&1) -> (A&1) | B
4853 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4854 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004855 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004856 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004857 }
4858
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004859 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4860 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004861 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004862 } else {
4863 A = 0;
4864 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004865 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004866 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4867 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004868 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004869
Misha Brukmancb6267b2004-07-30 12:50:08 +00004870 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004871 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004872 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004873 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004874 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004875 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004876 }
Chris Lattnera2881962003-02-18 19:28:33 +00004877
Reid Spencere4d87aa2006-12-23 06:05:41 +00004878 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4879 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4880 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004881 return R;
4882
Chris Lattner69d4ced2008-11-16 05:20:07 +00004883 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4884 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4885 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004886 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004887
4888 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004889 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004890 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004891 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004892 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4893 !isa<ICmpInst>(Op1C->getOperand(0))) {
4894 const Type *SrcTy = Op0C->getOperand(0)->getType();
4895 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4896 // Only do this if the casts both really cause code to be
4897 // generated.
4898 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4899 I.getType(), TD) &&
4900 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4901 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004902 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004903 Op1C->getOperand(0),
4904 I.getName());
4905 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004906 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004907 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004908 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004909 }
Chris Lattner99c65742007-10-24 05:38:08 +00004910 }
4911
4912
4913 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4914 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4915 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4916 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004917 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004918 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004919 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4920 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4921 // If either of the constants are nans, then the whole thing returns
4922 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004923 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004924 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4925
4926 // Otherwise, no need to compare the two constants, compare the
4927 // rest.
4928 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4929 RHS->getOperand(0));
4930 }
Evan Cheng40300622008-10-14 18:44:08 +00004931 } else {
4932 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4933 FCmpInst::Predicate Op0CC, Op1CC;
4934 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4935 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4936 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4937 // Swap RHS operands to match LHS.
4938 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4939 std::swap(Op1LHS, Op1RHS);
4940 }
4941 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4942 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4943 if (Op0CC == Op1CC)
4944 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4945 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4946 Op1CC == FCmpInst::FCMP_TRUE)
4947 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4948 else if (Op0CC == FCmpInst::FCMP_FALSE)
4949 return ReplaceInstUsesWith(I, Op1);
4950 else if (Op1CC == FCmpInst::FCMP_FALSE)
4951 return ReplaceInstUsesWith(I, Op0);
4952 bool Op0Ordered;
4953 bool Op1Ordered;
4954 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4955 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4956 if (Op0Ordered == Op1Ordered) {
4957 // If both are ordered or unordered, return a new fcmp with
4958 // or'ed predicates.
4959 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4960 Op0LHS, Op0RHS);
4961 if (Instruction *I = dyn_cast<Instruction>(RV))
4962 return I;
4963 // Otherwise, it's a constant boolean value...
4964 return ReplaceInstUsesWith(I, RV);
4965 }
4966 }
4967 }
4968 }
Chris Lattner99c65742007-10-24 05:38:08 +00004969 }
4970 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004971
Chris Lattner7e708292002-06-25 16:13:24 +00004972 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004973}
4974
Dan Gohman844731a2008-05-13 00:00:25 +00004975namespace {
4976
Chris Lattnerc317d392004-02-16 01:20:27 +00004977// XorSelf - Implements: X ^ X --> 0
4978struct XorSelf {
4979 Value *RHS;
4980 XorSelf(Value *rhs) : RHS(rhs) {}
4981 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4982 Instruction *apply(BinaryOperator &Xor) const {
4983 return &Xor;
4984 }
4985};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004986
Dan Gohman844731a2008-05-13 00:00:25 +00004987}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004988
Chris Lattner7e708292002-06-25 16:13:24 +00004989Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004990 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004991 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004992
Evan Chengd34af782008-03-25 20:07:13 +00004993 if (isa<UndefValue>(Op1)) {
4994 if (isa<UndefValue>(Op0))
4995 // Handle undef ^ undef -> 0 special case. This is a common
4996 // idiom (misuse).
4997 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004998 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004999 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005000
Chris Lattnerc317d392004-02-16 01:20:27 +00005001 // xor X, X = 0, even if X is nested in a sequence of Xor's.
5002 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005003 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00005004 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005005 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005006
5007 // See if we can simplify any instructions used by the instruction whose sole
5008 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00005009 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00005010 if (SimplifyDemandedInstructionBits(I))
Reid Spencera03d45f2007-03-22 22:19:58 +00005011 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00005012 } else if (isa<ConstantAggregateZero>(Op1)) {
5013 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00005014 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005015
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005016 // Is this a ~ operation?
5017 if (Value *NotOp = dyn_castNotVal(&I)) {
5018 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5019 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5020 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5021 if (Op0I->getOpcode() == Instruction::And ||
5022 Op0I->getOpcode() == Instruction::Or) {
5023 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5024 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5025 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005026 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005027 Op0I->getOperand(1)->getName()+".not");
5028 InsertNewInstBefore(NotY, I);
5029 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005030 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005031 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005032 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005033 }
5034 }
5035 }
5036 }
5037
5038
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005039 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005040 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005041 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005042 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005043 return new ICmpInst(ICI->getInversePredicate(),
5044 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005045
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005046 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5047 return new FCmpInst(FCI->getInversePredicate(),
5048 FCI->getOperand(0), FCI->getOperand(1));
5049 }
5050
Nick Lewycky517e1f52008-05-31 19:01:33 +00005051 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5052 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5053 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5054 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5055 Instruction::CastOps Opcode = Op0C->getOpcode();
5056 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5057 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
5058 Op0C->getDestTy())) {
5059 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5060 CI->getOpcode(), CI->getInversePredicate(),
5061 CI->getOperand(0), CI->getOperand(1)), I);
5062 NewCI->takeName(CI);
5063 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5064 }
5065 }
5066 }
5067 }
5068 }
5069
Reid Spencere4d87aa2006-12-23 06:05:41 +00005070 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005071 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005072 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5073 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00005074 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5075 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005076 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005077 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005078 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005079
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005080 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005081 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005082 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005083 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00005084 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005085 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00005086 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005087 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00005088 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005089 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005090 // (X + C) ^ signbit -> (X + C + signbit)
5091 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005092 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005093
Chris Lattner7c4049c2004-01-12 19:35:11 +00005094 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005095 } else if (Op0I->getOpcode() == Instruction::Or) {
5096 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005097 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00005098 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5099 // Anything in both C1 and C2 is known to be zero, remove it from
5100 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005101 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005102 NewRHS = ConstantExpr::getAnd(NewRHS,
5103 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005104 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005105 I.setOperand(0, Op0I->getOperand(0));
5106 I.setOperand(1, NewRHS);
5107 return &I;
5108 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005109 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005110 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005111 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005112
5113 // Try to fold constant and into select arguments.
5114 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005115 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005116 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005117 if (isa<PHINode>(Op0))
5118 if (Instruction *NV = FoldOpIntoPhi(I))
5119 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005120 }
5121
Chris Lattner8d969642003-03-10 23:06:50 +00005122 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005123 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005124 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005125
Chris Lattner8d969642003-03-10 23:06:50 +00005126 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005127 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005128 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005129
Chris Lattner318bf792007-03-18 22:51:34 +00005130
5131 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5132 if (Op1I) {
5133 Value *A, *B;
5134 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5135 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005136 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005137 I.swapOperands();
5138 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005139 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005140 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005141 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005142 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005143 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5144 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5145 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5146 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Chris Lattner318bf792007-03-18 22:51:34 +00005147 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005148 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005149 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005150 std::swap(A, B);
5151 }
Chris Lattner318bf792007-03-18 22:51:34 +00005152 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005153 I.swapOperands(); // Simplified below.
5154 std::swap(Op0, Op1);
5155 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005156 }
Chris Lattner318bf792007-03-18 22:51:34 +00005157 }
5158
5159 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5160 if (Op0I) {
5161 Value *A, *B;
5162 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5163 if (A == Op1) // (B|A)^B == (A|B)^B
5164 std::swap(A, B);
5165 if (B == Op1) { // (A|B)^B == A & ~B
5166 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005167 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5168 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005169 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005170 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5171 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5172 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5173 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Chris Lattner318bf792007-03-18 22:51:34 +00005174 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5175 if (A == Op1) // (A&B)^A -> (B&A)^A
5176 std::swap(A, B);
5177 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005178 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005179 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005180 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5181 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005182 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005183 }
Chris Lattner318bf792007-03-18 22:51:34 +00005184 }
5185
5186 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5187 if (Op0I && Op1I && Op0I->isShift() &&
5188 Op0I->getOpcode() == Op1I->getOpcode() &&
5189 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5190 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5191 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005192 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005193 Op1I->getOperand(0),
5194 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005195 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005196 Op1I->getOperand(1));
5197 }
5198
5199 if (Op0I && Op1I) {
5200 Value *A, *B, *C, *D;
5201 // (A & B)^(A | B) -> A ^ B
5202 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5203 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5204 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005205 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005206 }
5207 // (A | B)^(A & B) -> A ^ B
5208 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5209 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5210 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005211 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005212 }
5213
5214 // (A & B)^(C & D)
5215 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5216 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5217 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5218 // (X & Y)^(X & Y) -> (Y^Z) & X
5219 Value *X = 0, *Y = 0, *Z = 0;
5220 if (A == C)
5221 X = A, Y = B, Z = D;
5222 else if (A == D)
5223 X = A, Y = B, Z = C;
5224 else if (B == C)
5225 X = B, Y = A, Z = D;
5226 else if (B == D)
5227 X = B, Y = A, Z = C;
5228
5229 if (X) {
5230 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005231 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5232 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005233 }
5234 }
5235 }
5236
Reid Spencere4d87aa2006-12-23 06:05:41 +00005237 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5238 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5239 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005240 return R;
5241
Chris Lattner6fc205f2006-05-05 06:39:07 +00005242 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005243 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005244 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005245 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5246 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005247 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005248 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005249 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5250 I.getType(), TD) &&
5251 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5252 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005253 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005254 Op1C->getOperand(0),
5255 I.getName());
5256 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005257 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005258 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005259 }
Chris Lattner99c65742007-10-24 05:38:08 +00005260 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005261
Chris Lattner7e708292002-06-25 16:13:24 +00005262 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005263}
5264
Chris Lattnera96879a2004-09-29 17:40:11 +00005265/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5266/// overflowed for this type.
5267static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005268 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005269 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005270
Reid Spencere4e40032007-03-21 23:19:50 +00005271 if (IsSigned)
5272 if (In2->getValue().isNegative())
5273 return Result->getValue().sgt(In1->getValue());
5274 else
5275 return Result->getValue().slt(In1->getValue());
5276 else
5277 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005278}
5279
Dan Gohman1df3fd62008-09-10 23:30:57 +00005280/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5281/// overflowed for this type.
5282static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5283 ConstantInt *In2, bool IsSigned = false) {
Dan Gohmanbcb37fd2008-09-11 18:53:02 +00005284 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohman1df3fd62008-09-10 23:30:57 +00005285
5286 if (IsSigned)
5287 if (In2->getValue().isNegative())
5288 return Result->getValue().slt(In1->getValue());
5289 else
5290 return Result->getValue().sgt(In1->getValue());
5291 else
5292 return Result->getValue().ugt(In1->getValue());
5293}
5294
Chris Lattner574da9b2005-01-13 20:14:25 +00005295/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5296/// code necessary to compute the offset from the base pointer (without adding
5297/// in the base pointer). Return the result as a signed integer of intptr size.
5298static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5299 TargetData &TD = IC.getTargetData();
5300 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005301 const Type *IntPtrTy = TD.getIntPtrType();
5302 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005303
5304 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005305 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005306 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005307
Gabor Greif177dd3f2008-06-12 21:37:33 +00005308 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5309 ++i, ++GTI) {
5310 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005311 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005312 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5313 if (OpC->isZero()) continue;
5314
5315 // Handle a struct index, which adds its field offset to the pointer.
5316 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5317 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5318
5319 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5320 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005321 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005322 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005323 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005324 ConstantInt::get(IntPtrTy, Size),
5325 GEP->getName()+".offs"), I);
5326 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005327 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005328
5329 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5330 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5331 Scale = ConstantExpr::getMul(OC, Scale);
5332 if (Constant *RC = dyn_cast<Constant>(Result))
5333 Result = ConstantExpr::getAdd(RC, Scale);
5334 else {
5335 // Emit an add instruction.
5336 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005337 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005338 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005339 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005340 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005341 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005342 // Convert to correct type.
5343 if (Op->getType() != IntPtrTy) {
5344 if (Constant *OpC = dyn_cast<Constant>(Op))
Chris Lattner62ce3b32009-04-07 05:03:34 +00005345 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005346 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005347 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5348 true,
5349 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005350 }
5351 if (Size != 1) {
5352 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5353 if (Constant *OpC = dyn_cast<Constant>(Op))
5354 Op = ConstantExpr::getMul(OpC, Scale);
5355 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005356 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005357 GEP->getName()+".idx"), I);
5358 }
5359
5360 // Emit an add instruction.
5361 if (isa<Constant>(Op) && isa<Constant>(Result))
5362 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5363 cast<Constant>(Result));
5364 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005365 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005366 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005367 }
5368 return Result;
5369}
5370
Chris Lattner10c0d912008-04-22 02:53:33 +00005371
5372/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5373/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5374/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5375/// complex, and scales are involved. The above expression would also be legal
5376/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5377/// later form is less amenable to optimization though, and we are allowed to
5378/// generate the first by knowing that pointer arithmetic doesn't overflow.
5379///
5380/// If we can't emit an optimized form for this expression, this returns null.
5381///
5382static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5383 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005384 TargetData &TD = IC.getTargetData();
5385 gep_type_iterator GTI = gep_type_begin(GEP);
5386
5387 // Check to see if this gep only has a single variable index. If so, and if
5388 // any constant indices are a multiple of its scale, then we can compute this
5389 // in terms of the scale of the variable index. For example, if the GEP
5390 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5391 // because the expression will cross zero at the same point.
5392 unsigned i, e = GEP->getNumOperands();
5393 int64_t Offset = 0;
5394 for (i = 1; i != e; ++i, ++GTI) {
5395 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5396 // Compute the aggregate offset of constant indices.
5397 if (CI->isZero()) continue;
5398
5399 // Handle a struct index, which adds its field offset to the pointer.
5400 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5401 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5402 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005403 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005404 Offset += Size*CI->getSExtValue();
5405 }
5406 } else {
5407 // Found our variable index.
5408 break;
5409 }
5410 }
5411
5412 // If there are no variable indices, we must have a constant offset, just
5413 // evaluate it the general way.
5414 if (i == e) return 0;
5415
5416 Value *VariableIdx = GEP->getOperand(i);
5417 // Determine the scale factor of the variable element. For example, this is
5418 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005419 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005420
5421 // Verify that there are no other variable indices. If so, emit the hard way.
5422 for (++i, ++GTI; i != e; ++i, ++GTI) {
5423 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5424 if (!CI) return 0;
5425
5426 // Compute the aggregate offset of constant indices.
5427 if (CI->isZero()) continue;
5428
5429 // Handle a struct index, which adds its field offset to the pointer.
5430 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5431 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5432 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005433 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005434 Offset += Size*CI->getSExtValue();
5435 }
5436 }
5437
5438 // Okay, we know we have a single variable index, which must be a
5439 // pointer/array/vector index. If there is no offset, life is simple, return
5440 // the index.
5441 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5442 if (Offset == 0) {
5443 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5444 // we don't need to bother extending: the extension won't affect where the
5445 // computation crosses zero.
5446 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5447 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5448 VariableIdx->getNameStart(), &I);
5449 return VariableIdx;
5450 }
5451
5452 // Otherwise, there is an index. The computation we will do will be modulo
5453 // the pointer size, so get it.
5454 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5455
5456 Offset &= PtrSizeMask;
5457 VariableScale &= PtrSizeMask;
5458
5459 // To do this transformation, any constant index must be a multiple of the
5460 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5461 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5462 // multiple of the variable scale.
5463 int64_t NewOffs = Offset / (int64_t)VariableScale;
5464 if (Offset != NewOffs*(int64_t)VariableScale)
5465 return 0;
5466
5467 // Okay, we can do this evaluation. Start by converting the index to intptr.
5468 const Type *IntPtrTy = TD.getIntPtrType();
5469 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005470 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005471 true /*SExt*/,
5472 VariableIdx->getNameStart(), &I);
5473 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005474 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005475}
5476
5477
Reid Spencere4d87aa2006-12-23 06:05:41 +00005478/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005479/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005480Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5481 ICmpInst::Predicate Cond,
5482 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005483 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005484
Chris Lattner10c0d912008-04-22 02:53:33 +00005485 // Look through bitcasts.
5486 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5487 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005488
Chris Lattner574da9b2005-01-13 20:14:25 +00005489 Value *PtrBase = GEPLHS->getOperand(0);
5490 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005491 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005492 // This transformation (ignoring the base and scales) is valid because we
5493 // know pointers can't overflow. See if we can output an optimized form.
5494 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5495
5496 // If not, synthesize the offset the hard way.
5497 if (Offset == 0)
5498 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005499 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5500 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005501 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005502 // If the base pointers are different, but the indices are the same, just
5503 // compare the base pointer.
5504 if (PtrBase != GEPRHS->getOperand(0)) {
5505 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005506 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005507 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005508 if (IndicesTheSame)
5509 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5510 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5511 IndicesTheSame = false;
5512 break;
5513 }
5514
5515 // If all indices are the same, just compare the base pointers.
5516 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005517 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5518 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005519
5520 // Otherwise, the base pointers are different and the indices are
5521 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005522 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005523 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005524
Chris Lattnere9d782b2005-01-13 22:25:21 +00005525 // If one of the GEPs has all zero indices, recurse.
5526 bool AllZeros = true;
5527 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5528 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5529 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5530 AllZeros = false;
5531 break;
5532 }
5533 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005534 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5535 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005536
5537 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005538 AllZeros = true;
5539 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5540 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5541 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5542 AllZeros = false;
5543 break;
5544 }
5545 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005546 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005547
Chris Lattner4401c9c2005-01-14 00:20:05 +00005548 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5549 // If the GEPs only differ by one index, compare it.
5550 unsigned NumDifferences = 0; // Keep track of # differences.
5551 unsigned DiffOperand = 0; // The operand that differs.
5552 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5553 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005554 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5555 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005556 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005557 NumDifferences = 2;
5558 break;
5559 } else {
5560 if (NumDifferences++) break;
5561 DiffOperand = i;
5562 }
5563 }
5564
5565 if (NumDifferences == 0) // SAME GEP?
5566 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005567 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005568 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005569
Chris Lattner4401c9c2005-01-14 00:20:05 +00005570 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005571 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5572 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005573 // Make sure we do a signed comparison here.
5574 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005575 }
5576 }
5577
Reid Spencere4d87aa2006-12-23 06:05:41 +00005578 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005579 // the result to fold to a constant!
5580 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5581 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5582 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5583 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5584 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005585 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005586 }
5587 }
5588 return 0;
5589}
5590
Chris Lattnera5406232008-05-19 20:18:56 +00005591/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5592///
5593Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5594 Instruction *LHSI,
5595 Constant *RHSC) {
5596 if (!isa<ConstantFP>(RHSC)) return 0;
5597 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5598
5599 // Get the width of the mantissa. We don't want to hack on conversions that
5600 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005601 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005602 if (MantissaWidth == -1) return 0; // Unknown.
5603
5604 // Check to see that the input is converted from an integer type that is small
5605 // enough that preserves all bits. TODO: check here for "known" sign bits.
5606 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5607 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5608
5609 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005610 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5611 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005612 ++InputSize;
5613
5614 // If the conversion would lose info, don't hack on this.
5615 if ((int)InputSize > MantissaWidth)
5616 return 0;
5617
5618 // Otherwise, we can potentially simplify the comparison. We know that it
5619 // will always come through as an integer value and we know the constant is
5620 // not a NAN (it would have been previously simplified).
5621 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5622
5623 ICmpInst::Predicate Pred;
5624 switch (I.getPredicate()) {
5625 default: assert(0 && "Unexpected predicate!");
5626 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005627 case FCmpInst::FCMP_OEQ:
5628 Pred = ICmpInst::ICMP_EQ;
5629 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005630 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005631 case FCmpInst::FCMP_OGT:
5632 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5633 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005634 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005635 case FCmpInst::FCMP_OGE:
5636 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5637 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005638 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005639 case FCmpInst::FCMP_OLT:
5640 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5641 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005642 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005643 case FCmpInst::FCMP_OLE:
5644 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5645 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005646 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005647 case FCmpInst::FCMP_ONE:
5648 Pred = ICmpInst::ICMP_NE;
5649 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005650 case FCmpInst::FCMP_ORD:
Eli Friedman8b019c82008-11-30 22:48:49 +00005651 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005652 case FCmpInst::FCMP_UNO:
Eli Friedman8b019c82008-11-30 22:48:49 +00005653 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005654 }
5655
5656 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5657
5658 // Now we know that the APFloat is a normal number, zero or inf.
5659
Chris Lattner85162782008-05-20 03:50:52 +00005660 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005661 // comparing an i8 to 300.0.
5662 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5663
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005664 if (!LHSUnsigned) {
5665 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5666 // and large values.
5667 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5668 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5669 APFloat::rmNearestTiesToEven);
5670 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5671 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5672 Pred == ICmpInst::ICMP_SLE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005673 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5674 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005675 }
5676 } else {
5677 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5678 // +INF and large values.
5679 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5680 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5681 APFloat::rmNearestTiesToEven);
5682 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5683 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5684 Pred == ICmpInst::ICMP_ULE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005685 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5686 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005687 }
Chris Lattnera5406232008-05-19 20:18:56 +00005688 }
5689
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005690 if (!LHSUnsigned) {
5691 // See if the RHS value is < SignedMin.
5692 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5693 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5694 APFloat::rmNearestTiesToEven);
5695 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5696 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5697 Pred == ICmpInst::ICMP_SGE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005698 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5699 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005700 }
Chris Lattnera5406232008-05-19 20:18:56 +00005701 }
5702
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005703 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5704 // [0, UMAX], but it may still be fractional. See if it is fractional by
5705 // casting the FP value to the integer value and back, checking for equality.
5706 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005707 Constant *RHSInt = LHSUnsigned
5708 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5709 : ConstantExpr::getFPToSI(RHSC, IntTy);
5710 if (!RHS.isZero()) {
5711 bool Equal = LHSUnsigned
5712 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5713 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5714 if (!Equal) {
5715 // If we had a comparison against a fractional value, we have to adjust
5716 // the compare predicate and sometimes the value. RHSC is rounded towards
5717 // zero at this point.
5718 switch (Pred) {
5719 default: assert(0 && "Unexpected integer comparison!");
5720 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedman8b019c82008-11-30 22:48:49 +00005721 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005722 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5723 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5724 case ICmpInst::ICMP_ULE:
5725 // (float)int <= 4.4 --> int <= 4
5726 // (float)int <= -4.4 --> false
5727 if (RHS.isNegative())
5728 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5729 break;
5730 case ICmpInst::ICMP_SLE:
5731 // (float)int <= 4.4 --> int <= 4
5732 // (float)int <= -4.4 --> int < -4
5733 if (RHS.isNegative())
5734 Pred = ICmpInst::ICMP_SLT;
5735 break;
5736 case ICmpInst::ICMP_ULT:
5737 // (float)int < -4.4 --> false
5738 // (float)int < 4.4 --> int <= 4
5739 if (RHS.isNegative())
5740 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5741 Pred = ICmpInst::ICMP_ULE;
5742 break;
5743 case ICmpInst::ICMP_SLT:
5744 // (float)int < -4.4 --> int < -4
5745 // (float)int < 4.4 --> int <= 4
5746 if (!RHS.isNegative())
5747 Pred = ICmpInst::ICMP_SLE;
5748 break;
5749 case ICmpInst::ICMP_UGT:
5750 // (float)int > 4.4 --> int > 4
5751 // (float)int > -4.4 --> true
5752 if (RHS.isNegative())
5753 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5754 break;
5755 case ICmpInst::ICMP_SGT:
5756 // (float)int > 4.4 --> int > 4
5757 // (float)int > -4.4 --> int >= -4
5758 if (RHS.isNegative())
5759 Pred = ICmpInst::ICMP_SGE;
5760 break;
5761 case ICmpInst::ICMP_UGE:
5762 // (float)int >= -4.4 --> true
5763 // (float)int >= 4.4 --> int > 4
5764 if (!RHS.isNegative())
5765 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5766 Pred = ICmpInst::ICMP_UGT;
5767 break;
5768 case ICmpInst::ICMP_SGE:
5769 // (float)int >= -4.4 --> int >= -4
5770 // (float)int >= 4.4 --> int > 4
5771 if (!RHS.isNegative())
5772 Pred = ICmpInst::ICMP_SGT;
5773 break;
5774 }
Chris Lattnera5406232008-05-19 20:18:56 +00005775 }
5776 }
5777
5778 // Lower this FP comparison into an appropriate integer version of the
5779 // comparison.
5780 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5781}
5782
Reid Spencere4d87aa2006-12-23 06:05:41 +00005783Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5784 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005785 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005786
Chris Lattner58e97462007-01-14 19:42:17 +00005787 // Fold trivial predicates.
5788 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005789 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005790 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005791 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005792
5793 // Simplify 'fcmp pred X, X'
5794 if (Op0 == Op1) {
5795 switch (I.getPredicate()) {
5796 default: assert(0 && "Unknown predicate!");
5797 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5798 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5799 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedman8b019c82008-11-30 22:48:49 +00005800 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005801 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5802 case FCmpInst::FCMP_OLT: // True if ordered and less than
5803 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedman8b019c82008-11-30 22:48:49 +00005804 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005805
5806 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5807 case FCmpInst::FCMP_ULT: // True if unordered or less than
5808 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5809 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5810 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5811 I.setPredicate(FCmpInst::FCMP_UNO);
5812 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5813 return &I;
5814
5815 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5816 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5817 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5818 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5819 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5820 I.setPredicate(FCmpInst::FCMP_ORD);
5821 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5822 return &I;
5823 }
5824 }
5825
Reid Spencere4d87aa2006-12-23 06:05:41 +00005826 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005827 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005828
Reid Spencere4d87aa2006-12-23 06:05:41 +00005829 // Handle fcmp with constant RHS
5830 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005831 // If the constant is a nan, see if we can fold the comparison based on it.
5832 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5833 if (CFP->getValueAPF().isNaN()) {
5834 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedman8b019c82008-11-30 22:48:49 +00005835 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005836 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5837 "Comparison must be either ordered or unordered!");
5838 // True if unordered.
Eli Friedman8b019c82008-11-30 22:48:49 +00005839 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005840 }
5841 }
5842
Reid Spencere4d87aa2006-12-23 06:05:41 +00005843 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5844 switch (LHSI->getOpcode()) {
5845 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005846 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5847 // block. If in the same block, we're encouraging jump threading. If
5848 // not, we are just pessimizing the code by making an i1 phi.
5849 if (LHSI->getParent() == I.getParent())
5850 if (Instruction *NV = FoldOpIntoPhi(I))
5851 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005852 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005853 case Instruction::SIToFP:
5854 case Instruction::UIToFP:
5855 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5856 return NV;
5857 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005858 case Instruction::Select:
5859 // If either operand of the select is a constant, we can fold the
5860 // comparison into the select arms, which will cause one to be
5861 // constant folded and the select turned into a bitwise or.
5862 Value *Op1 = 0, *Op2 = 0;
5863 if (LHSI->hasOneUse()) {
5864 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5865 // Fold the known value into the constant operand.
5866 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5867 // Insert a new FCmp of the other select operand.
5868 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5869 LHSI->getOperand(2), RHSC,
5870 I.getName()), I);
5871 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5872 // Fold the known value into the constant operand.
5873 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5874 // Insert a new FCmp of the other select operand.
5875 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5876 LHSI->getOperand(1), RHSC,
5877 I.getName()), I);
5878 }
5879 }
5880
5881 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005882 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005883 break;
5884 }
5885 }
5886
5887 return Changed ? &I : 0;
5888}
5889
5890Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5891 bool Changed = SimplifyCompare(I);
5892 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5893 const Type *Ty = Op0->getType();
5894
5895 // icmp X, X
5896 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005897 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005898 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005899
5900 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005901 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005902
Reid Spencere4d87aa2006-12-23 06:05:41 +00005903 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005904 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005905 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5906 isa<ConstantPointerNull>(Op0)) &&
5907 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005908 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005909 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005910 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005911
Reid Spencere4d87aa2006-12-23 06:05:41 +00005912 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005913 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005914 switch (I.getPredicate()) {
5915 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005916 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005917 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005918 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005919 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005920 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005921 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005922 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005923
Reid Spencere4d87aa2006-12-23 06:05:41 +00005924 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005925 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005926 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005927 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005928 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005929 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005930 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005931 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005932 case ICmpInst::ICMP_SGT:
5933 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005934 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005935 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5936 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5937 InsertNewInstBefore(Not, I);
5938 return BinaryOperator::CreateAnd(Not, Op0);
5939 }
5940 case ICmpInst::ICMP_UGE:
5941 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5942 // FALL THROUGH
5943 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005944 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005945 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005946 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005947 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005948 case ICmpInst::ICMP_SGE:
5949 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5950 // FALL THROUGH
5951 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5952 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5953 InsertNewInstBefore(Not, I);
5954 return BinaryOperator::CreateOr(Not, Op0);
5955 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005956 }
Chris Lattner8b170942002-08-09 23:47:40 +00005957 }
5958
Dan Gohman1c8491e2009-04-25 17:12:48 +00005959 unsigned BitWidth = 0;
5960 if (TD)
5961 BitWidth = TD->getTypeSizeInBits(Ty);
5962 else if (isa<IntegerType>(Ty))
5963 BitWidth = Ty->getPrimitiveSizeInBits();
5964
5965 bool isSignBit = false;
5966
Dan Gohman81b28ce2008-09-16 18:46:06 +00005967 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005968 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005969 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005970
Chris Lattnerb6566012008-01-05 01:18:20 +00005971 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5972 if (I.isEquality() && CI->isNullValue() &&
5973 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5974 // (icmp cond A B) if cond is equality
5975 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005976 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005977
Dan Gohman81b28ce2008-09-16 18:46:06 +00005978 // If we have an icmp le or icmp ge instruction, turn it into the
5979 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5980 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005981 switch (I.getPredicate()) {
5982 default: break;
5983 case ICmpInst::ICMP_ULE:
5984 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5985 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5986 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5987 case ICmpInst::ICMP_SLE:
5988 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5989 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5990 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5991 case ICmpInst::ICMP_UGE:
5992 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5993 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5994 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5995 case ICmpInst::ICMP_SGE:
5996 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5997 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5998 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5999 }
6000
Chris Lattner183661e2008-07-11 05:40:05 +00006001 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006002 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006003 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006004 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6005 }
6006
6007 // See if we can fold the comparison based on range information we can get
6008 // by checking whether bits are known to be zero or one in the input.
6009 if (BitWidth != 0) {
6010 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6011 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6012
6013 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006014 isSignBit ? APInt::getSignBit(BitWidth)
6015 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006016 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006017 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006018 if (SimplifyDemandedBits(I.getOperandUse(1),
6019 APInt::getAllOnesValue(BitWidth),
6020 Op1KnownZero, Op1KnownOne, 0))
6021 return &I;
6022
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006023 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006024 // in. Compute the Min, Max and RHS values based on the known bits. For the
6025 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006026 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6027 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6028 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6029 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6030 Op0Min, Op0Max);
6031 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6032 Op1Min, Op1Max);
6033 } else {
6034 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6035 Op0Min, Op0Max);
6036 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6037 Op1Min, Op1Max);
6038 }
6039
Chris Lattner183661e2008-07-11 05:40:05 +00006040 // If Min and Max are known to be the same, then SimplifyDemandedBits
6041 // figured out that the LHS is a constant. Just constant fold this now so
6042 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006043 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6044 return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
6045 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6046 return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
6047
Chris Lattner183661e2008-07-11 05:40:05 +00006048 // Based on the range information we know about the LHS, see if we can
6049 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006050 switch (I.getPredicate()) {
Chris Lattner84dff672008-07-11 05:08:55 +00006051 default: assert(0 && "Unknown icmp opcode!");
6052 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006053 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner84dff672008-07-11 05:08:55 +00006054 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6055 break;
6056 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006057 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner84dff672008-07-11 05:08:55 +00006058 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6059 break;
6060 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006061 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006062 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006063 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006064 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006065 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Chris Lattner183661e2008-07-11 05:40:05 +00006066 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006067 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6068 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6069 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6070
6071 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6072 if (CI->isMinValue(true))
6073 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Chris Lattner183661e2008-07-11 05:40:05 +00006074 ConstantInt::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006075 }
Chris Lattner84dff672008-07-11 05:08:55 +00006076 break;
6077 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006078 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006079 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006080 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006081 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006082
6083 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Chris Lattner183661e2008-07-11 05:40:05 +00006084 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006085 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6086 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6087 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6088
6089 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6090 if (CI->isMaxValue(true))
6091 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6092 ConstantInt::getNullValue(Op0->getType()));
6093 }
Chris Lattner84dff672008-07-11 05:08:55 +00006094 break;
6095 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006096 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Chris Lattner84dff672008-07-11 05:08:55 +00006097 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006098 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Chris Lattner84dff672008-07-11 05:08:55 +00006099 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006100 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Chris Lattner183661e2008-07-11 05:40:05 +00006101 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006102 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6103 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6104 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6105 }
Chris Lattner84dff672008-07-11 05:08:55 +00006106 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006107 case ICmpInst::ICMP_SGT:
6108 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006109 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006110 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006111 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006112
6113 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Chris Lattner183661e2008-07-11 05:40:05 +00006114 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006115 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6116 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6117 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6118 }
6119 break;
6120 case ICmpInst::ICMP_SGE:
6121 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6122 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6123 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6124 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6125 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6126 break;
6127 case ICmpInst::ICMP_SLE:
6128 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6129 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6130 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6131 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6132 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6133 break;
6134 case ICmpInst::ICMP_UGE:
6135 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6136 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6137 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6138 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6139 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6140 break;
6141 case ICmpInst::ICMP_ULE:
6142 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6143 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6144 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6145 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6146 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006147 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006148 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006149
6150 // Turn a signed comparison into an unsigned one if both operands
6151 // are known to have the same sign.
6152 if (I.isSignedPredicate() &&
6153 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6154 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6155 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006156 }
6157
6158 // Test if the ICmpInst instruction is used exclusively by a select as
6159 // part of a minimum or maximum operation. If so, refrain from doing
6160 // any other folding. This helps out other analyses which understand
6161 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6162 // and CodeGen. And in this case, at least one of the comparison
6163 // operands has at least one user besides the compare (the select),
6164 // which would often largely negate the benefit of folding anyway.
6165 if (I.hasOneUse())
6166 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6167 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6168 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6169 return 0;
6170
6171 // See if we are doing a comparison between a constant and an instruction that
6172 // can be folded into the comparison.
6173 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006174 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006175 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006176 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006177 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006178 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6179 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006180 }
6181
Chris Lattner01deb9d2007-04-03 17:43:25 +00006182 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006183 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6184 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6185 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006186 case Instruction::GetElementPtr:
6187 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006188 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006189 bool isAllZeros = true;
6190 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6191 if (!isa<Constant>(LHSI->getOperand(i)) ||
6192 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6193 isAllZeros = false;
6194 break;
6195 }
6196 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006197 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00006198 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6199 }
6200 break;
6201
Chris Lattner6970b662005-04-23 15:31:55 +00006202 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006203 // Only fold icmp into the PHI if the phi and fcmp are in the same
6204 // block. If in the same block, we're encouraging jump threading. If
6205 // not, we are just pessimizing the code by making an i1 phi.
6206 if (LHSI->getParent() == I.getParent())
6207 if (Instruction *NV = FoldOpIntoPhi(I))
6208 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006209 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006210 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006211 // If either operand of the select is a constant, we can fold the
6212 // comparison into the select arms, which will cause one to be
6213 // constant folded and the select turned into a bitwise or.
6214 Value *Op1 = 0, *Op2 = 0;
6215 if (LHSI->hasOneUse()) {
6216 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6217 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006218 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6219 // Insert a new ICmp of the other select operand.
6220 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6221 LHSI->getOperand(2), RHSC,
6222 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006223 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6224 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006225 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6226 // Insert a new ICmp of the other select operand.
6227 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6228 LHSI->getOperand(1), RHSC,
6229 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006230 }
6231 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006232
Chris Lattner6970b662005-04-23 15:31:55 +00006233 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006234 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006235 break;
6236 }
Chris Lattner4802d902007-04-06 18:57:34 +00006237 case Instruction::Malloc:
6238 // If we have (malloc != null), and if the malloc has a single use, we
6239 // can assume it is successful and remove the malloc.
6240 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6241 AddToWorkList(LHSI);
6242 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006243 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006244 }
6245 break;
6246 }
Chris Lattner6970b662005-04-23 15:31:55 +00006247 }
6248
Reid Spencere4d87aa2006-12-23 06:05:41 +00006249 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006250 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006251 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006252 return NI;
6253 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006254 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6255 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006256 return NI;
6257
Reid Spencere4d87aa2006-12-23 06:05:41 +00006258 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006259 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6260 // now.
6261 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6262 if (isa<PointerType>(Op0->getType()) &&
6263 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006264 // We keep moving the cast from the left operand over to the right
6265 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006266 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006267
Chris Lattner57d86372007-01-06 01:45:59 +00006268 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6269 // so eliminate it as well.
6270 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6271 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006272
Chris Lattnerde90b762003-11-03 04:25:02 +00006273 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006274 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006275 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006276 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006277 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006278 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006279 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006280 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006281 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006282 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006283 }
Chris Lattner57d86372007-01-06 01:45:59 +00006284 }
6285
6286 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006287 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006288 // This comes up when you have code like
6289 // int X = A < B;
6290 // if (X) ...
6291 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006292 // with a constant or another cast from the same type.
6293 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006294 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006295 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006296 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006297
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006298 // See if it's the same type of instruction on the left and right.
6299 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6300 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006301 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006302 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006303 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006304 default: break;
6305 case Instruction::Add:
6306 case Instruction::Sub:
6307 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006308 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Nick Lewycky4333f492009-01-31 21:30:05 +00006309 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6310 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006311 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6312 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6313 if (CI->getValue().isSignBit()) {
6314 ICmpInst::Predicate Pred = I.isSignedPredicate()
6315 ? I.getUnsignedPredicate()
6316 : I.getSignedPredicate();
6317 return new ICmpInst(Pred, Op0I->getOperand(0),
6318 Op1I->getOperand(0));
6319 }
6320
6321 if (CI->getValue().isMaxSignedValue()) {
6322 ICmpInst::Predicate Pred = I.isSignedPredicate()
6323 ? I.getUnsignedPredicate()
6324 : I.getSignedPredicate();
6325 Pred = I.getSwappedPredicate(Pred);
6326 return new ICmpInst(Pred, Op0I->getOperand(0),
6327 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006328 }
6329 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006330 break;
6331 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006332 if (!I.isEquality())
6333 break;
6334
Nick Lewycky5d52c452008-08-21 05:56:10 +00006335 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6336 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6337 // Mask = -1 >> count-trailing-zeros(Cst).
6338 if (!CI->isZero() && !CI->isOne()) {
6339 const APInt &AP = CI->getValue();
6340 ConstantInt *Mask = ConstantInt::get(
6341 APInt::getLowBitsSet(AP.getBitWidth(),
6342 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006343 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006344 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6345 Mask);
6346 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6347 Mask);
6348 InsertNewInstBefore(And1, I);
6349 InsertNewInstBefore(And2, I);
6350 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006351 }
6352 }
6353 break;
6354 }
6355 }
6356 }
6357 }
6358
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006359 // ~x < ~y --> y < x
6360 { Value *A, *B;
6361 if (match(Op0, m_Not(m_Value(A))) &&
6362 match(Op1, m_Not(m_Value(B))))
6363 return new ICmpInst(I.getPredicate(), B, A);
6364 }
6365
Chris Lattner65b72ba2006-09-18 04:22:48 +00006366 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006367 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006368
6369 // -x == -y --> x == y
6370 if (match(Op0, m_Neg(m_Value(A))) &&
6371 match(Op1, m_Neg(m_Value(B))))
6372 return new ICmpInst(I.getPredicate(), A, B);
6373
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006374 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6375 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6376 Value *OtherVal = A == Op1 ? B : A;
6377 return new ICmpInst(I.getPredicate(), OtherVal,
6378 Constant::getNullValue(A->getType()));
6379 }
6380
6381 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6382 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006383 ConstantInt *C1, *C2;
6384 if (match(B, m_ConstantInt(C1)) &&
6385 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6386 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6387 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6388 return new ICmpInst(I.getPredicate(), A,
6389 InsertNewInstBefore(Xor, I));
6390 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006391
6392 // A^B == A^D -> B == D
6393 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6394 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6395 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6396 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6397 }
6398 }
6399
6400 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6401 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006402 // A == (A^B) -> B == 0
6403 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006404 return new ICmpInst(I.getPredicate(), OtherVal,
6405 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006406 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006407
6408 // (A-B) == A -> B == 0
6409 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6410 return new ICmpInst(I.getPredicate(), B,
6411 Constant::getNullValue(B->getType()));
6412
6413 // A == (A-B) -> B == 0
6414 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006415 return new ICmpInst(I.getPredicate(), B,
6416 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006417
Chris Lattner9c2328e2006-11-14 06:06:06 +00006418 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6419 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6420 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6421 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6422 Value *X = 0, *Y = 0, *Z = 0;
6423
6424 if (A == C) {
6425 X = B; Y = D; Z = A;
6426 } else if (A == D) {
6427 X = B; Y = C; Z = A;
6428 } else if (B == C) {
6429 X = A; Y = D; Z = B;
6430 } else if (B == D) {
6431 X = A; Y = C; Z = B;
6432 }
6433
6434 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006435 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6436 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006437 I.setOperand(0, Op1);
6438 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6439 return &I;
6440 }
6441 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006442 }
Chris Lattner7e708292002-06-25 16:13:24 +00006443 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006444}
6445
Chris Lattner562ef782007-06-20 23:46:26 +00006446
6447/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6448/// and CmpRHS are both known to be integer constants.
6449Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6450 ConstantInt *DivRHS) {
6451 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6452 const APInt &CmpRHSV = CmpRHS->getValue();
6453
6454 // FIXME: If the operand types don't match the type of the divide
6455 // then don't attempt this transform. The code below doesn't have the
6456 // logic to deal with a signed divide and an unsigned compare (and
6457 // vice versa). This is because (x /s C1) <s C2 produces different
6458 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6459 // (x /u C1) <u C2. Simply casting the operands and result won't
6460 // work. :( The if statement below tests that condition and bails
6461 // if it finds it.
6462 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6463 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6464 return 0;
6465 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006466 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006467 if (DivIsSigned && DivRHS->isAllOnesValue())
6468 return 0; // The overflow computation also screws up here
6469 if (DivRHS->isOne())
6470 return 0; // Not worth bothering, and eliminates some funny cases
6471 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006472
6473 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6474 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6475 // C2 (CI). By solving for X we can turn this into a range check
6476 // instead of computing a divide.
6477 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6478
6479 // Determine if the product overflows by seeing if the product is
6480 // not equal to the divide. Make sure we do the same kind of divide
6481 // as in the LHS instruction that we're folding.
6482 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6483 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6484
6485 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006486 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006487
Chris Lattner1dbfd482007-06-21 18:11:19 +00006488 // Figure out the interval that is being checked. For example, a comparison
6489 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6490 // Compute this interval based on the constants involved and the signedness of
6491 // the compare/divide. This computes a half-open interval, keeping track of
6492 // whether either value in the interval overflows. After analysis each
6493 // overflow variable is set to 0 if it's corresponding bound variable is valid
6494 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6495 int LoOverflow = 0, HiOverflow = 0;
6496 ConstantInt *LoBound = 0, *HiBound = 0;
6497
Chris Lattner562ef782007-06-20 23:46:26 +00006498 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006499 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006500 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006501 HiOverflow = LoOverflow = ProdOV;
6502 if (!HiOverflow)
6503 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006504 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006505 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006506 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006507 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6508 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006509 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006510 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6511 HiOverflow = LoOverflow = ProdOV;
6512 if (!HiOverflow)
6513 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006514 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006515 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006516 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006517 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6518 if (!LoOverflow) {
6519 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6520 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6521 true) ? -1 : 0;
6522 }
Chris Lattner562ef782007-06-20 23:46:26 +00006523 }
Dan Gohman76491272008-02-13 22:09:18 +00006524 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006525 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006526 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006527 LoBound = AddOne(DivRHS);
6528 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006529 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6530 HiOverflow = 1; // [INTMIN+1, overflow)
6531 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6532 }
Dan Gohman76491272008-02-13 22:09:18 +00006533 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006534 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnera6321b42008-10-11 22:55:00 +00006535 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006536 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006537 if (!LoOverflow)
Chris Lattnera6321b42008-10-11 22:55:00 +00006538 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006539 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006540 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6541 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006542 if (!HiOverflow)
6543 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006544 }
6545
Chris Lattner1dbfd482007-06-21 18:11:19 +00006546 // Dividing by a negative swaps the condition. LT <-> GT
6547 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006548 }
6549
6550 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006551 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006552 default: assert(0 && "Unhandled icmp opcode!");
6553 case ICmpInst::ICMP_EQ:
6554 if (LoOverflow && HiOverflow)
6555 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6556 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006557 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006558 ICmpInst::ICMP_UGE, X, LoBound);
6559 else if (LoOverflow)
6560 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6561 ICmpInst::ICMP_ULT, X, HiBound);
6562 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006563 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006564 case ICmpInst::ICMP_NE:
6565 if (LoOverflow && HiOverflow)
6566 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6567 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006568 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006569 ICmpInst::ICMP_ULT, X, LoBound);
6570 else if (LoOverflow)
6571 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6572 ICmpInst::ICMP_UGE, X, HiBound);
6573 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006574 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006575 case ICmpInst::ICMP_ULT:
6576 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006577 if (LoOverflow == +1) // Low bound is greater than input range.
6578 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6579 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006580 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006581 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006582 case ICmpInst::ICMP_UGT:
6583 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006584 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006585 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006586 else if (HiOverflow == -1) // High bound less than input range.
6587 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6588 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006589 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6590 else
6591 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6592 }
6593}
6594
6595
Chris Lattner01deb9d2007-04-03 17:43:25 +00006596/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6597///
6598Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6599 Instruction *LHSI,
6600 ConstantInt *RHS) {
6601 const APInt &RHSV = RHS->getValue();
6602
6603 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006604 case Instruction::Trunc:
6605 if (ICI.isEquality() && LHSI->hasOneUse()) {
6606 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6607 // of the high bits truncated out of x are known.
6608 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6609 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6610 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6611 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6612 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6613
6614 // If all the high bits are known, we can do this xform.
6615 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6616 // Pull in the high bits from known-ones set.
6617 APInt NewRHS(RHS->getValue());
6618 NewRHS.zext(SrcBits);
6619 NewRHS |= KnownOne;
6620 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6621 ConstantInt::get(NewRHS));
6622 }
6623 }
6624 break;
6625
Duncan Sands0091bf22007-04-04 06:42:45 +00006626 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006627 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6628 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6629 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006630 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6631 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006632 Value *CompareVal = LHSI->getOperand(0);
6633
6634 // If the sign bit of the XorCST is not set, there is no change to
6635 // the operation, just stop using the Xor.
6636 if (!XorCST->getValue().isNegative()) {
6637 ICI.setOperand(0, CompareVal);
6638 AddToWorkList(LHSI);
6639 return &ICI;
6640 }
6641
6642 // Was the old condition true if the operand is positive?
6643 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6644
6645 // If so, the new one isn't.
6646 isTrueIfPositive ^= true;
6647
6648 if (isTrueIfPositive)
6649 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6650 else
6651 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6652 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006653
6654 if (LHSI->hasOneUse()) {
6655 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6656 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6657 const APInt &SignBit = XorCST->getValue();
6658 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6659 ? ICI.getUnsignedPredicate()
6660 : ICI.getSignedPredicate();
6661 return new ICmpInst(Pred, LHSI->getOperand(0),
6662 ConstantInt::get(RHSV ^ SignBit));
6663 }
6664
6665 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006666 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006667 const APInt &NotSignBit = XorCST->getValue();
6668 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6669 ? ICI.getUnsignedPredicate()
6670 : ICI.getSignedPredicate();
6671 Pred = ICI.getSwappedPredicate(Pred);
6672 return new ICmpInst(Pred, LHSI->getOperand(0),
6673 ConstantInt::get(RHSV ^ NotSignBit));
6674 }
6675 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006676 }
6677 break;
6678 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6679 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6680 LHSI->getOperand(0)->hasOneUse()) {
6681 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6682
6683 // If the LHS is an AND of a truncating cast, we can widen the
6684 // and/compare to be the input width without changing the value
6685 // produced, eliminating a cast.
6686 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6687 // We can do this transformation if either the AND constant does not
6688 // have its sign bit set or if it is an equality comparison.
6689 // Extending a relational comparison when we're checking the sign
6690 // bit would not work.
6691 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006692 (ICI.isEquality() ||
6693 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006694 uint32_t BitWidth =
6695 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6696 APInt NewCST = AndCST->getValue();
6697 NewCST.zext(BitWidth);
6698 APInt NewCI = RHSV;
6699 NewCI.zext(BitWidth);
6700 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006701 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006702 ConstantInt::get(NewCST),LHSI->getName());
6703 InsertNewInstBefore(NewAnd, ICI);
6704 return new ICmpInst(ICI.getPredicate(), NewAnd,
6705 ConstantInt::get(NewCI));
6706 }
6707 }
6708
6709 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6710 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6711 // happens a LOT in code produced by the C front-end, for bitfield
6712 // access.
6713 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6714 if (Shift && !Shift->isShift())
6715 Shift = 0;
6716
6717 ConstantInt *ShAmt;
6718 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6719 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6720 const Type *AndTy = AndCST->getType(); // Type of the and.
6721
6722 // We can fold this as long as we can't shift unknown bits
6723 // into the mask. This can only happen with signed shift
6724 // rights, as they sign-extend.
6725 if (ShAmt) {
6726 bool CanFold = Shift->isLogicalShift();
6727 if (!CanFold) {
6728 // To test for the bad case of the signed shr, see if any
6729 // of the bits shifted in could be tested after the mask.
6730 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6731 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6732
6733 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6734 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6735 AndCST->getValue()) == 0)
6736 CanFold = true;
6737 }
6738
6739 if (CanFold) {
6740 Constant *NewCst;
6741 if (Shift->getOpcode() == Instruction::Shl)
6742 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6743 else
6744 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6745
6746 // Check to see if we are shifting out any of the bits being
6747 // compared.
6748 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6749 // If we shifted bits out, the fold is not going to work out.
6750 // As a special case, check to see if this means that the
6751 // result is always true or false now.
6752 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6753 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6754 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6755 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6756 } else {
6757 ICI.setOperand(1, NewCst);
6758 Constant *NewAndCST;
6759 if (Shift->getOpcode() == Instruction::Shl)
6760 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6761 else
6762 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6763 LHSI->setOperand(1, NewAndCST);
6764 LHSI->setOperand(0, Shift->getOperand(0));
6765 AddToWorkList(Shift); // Shift is dead.
6766 AddUsesToWorkList(ICI);
6767 return &ICI;
6768 }
6769 }
6770 }
6771
6772 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6773 // preferable because it allows the C<<Y expression to be hoisted out
6774 // of a loop if Y is invariant and X is not.
6775 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006776 ICI.isEquality() && !Shift->isArithmeticShift() &&
6777 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006778 // Compute C << Y.
6779 Value *NS;
6780 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006781 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006782 Shift->getOperand(1), "tmp");
6783 } else {
6784 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006785 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006786 Shift->getOperand(1), "tmp");
6787 }
6788 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6789
6790 // Compute X & (C << Y).
6791 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006792 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006793 InsertNewInstBefore(NewAnd, ICI);
6794
6795 ICI.setOperand(0, NewAnd);
6796 return &ICI;
6797 }
6798 }
6799 break;
6800
Chris Lattnera0141b92007-07-15 20:42:37 +00006801 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6802 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6803 if (!ShAmt) break;
6804
6805 uint32_t TypeBits = RHSV.getBitWidth();
6806
6807 // Check that the shift amount is in range. If not, don't perform
6808 // undefined shifts. When the shift is visited it will be
6809 // simplified.
6810 if (ShAmt->uge(TypeBits))
6811 break;
6812
6813 if (ICI.isEquality()) {
6814 // If we are comparing against bits always shifted out, the
6815 // comparison cannot succeed.
6816 Constant *Comp =
6817 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6818 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6819 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6820 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6821 return ReplaceInstUsesWith(ICI, Cst);
6822 }
6823
6824 if (LHSI->hasOneUse()) {
6825 // Otherwise strength reduce the shift into an and.
6826 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6827 Constant *Mask =
6828 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006829
Chris Lattnera0141b92007-07-15 20:42:37 +00006830 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006831 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006832 Mask, LHSI->getName()+".mask");
6833 Value *And = InsertNewInstBefore(AndI, ICI);
6834 return new ICmpInst(ICI.getPredicate(), And,
6835 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006836 }
6837 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006838
6839 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6840 bool TrueIfSigned = false;
6841 if (LHSI->hasOneUse() &&
6842 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6843 // (X << 31) <s 0 --> (X&1) != 0
6844 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6845 (TypeBits-ShAmt->getZExtValue()-1));
6846 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006847 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006848 Mask, LHSI->getName()+".mask");
6849 Value *And = InsertNewInstBefore(AndI, ICI);
6850
6851 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6852 And, Constant::getNullValue(And->getType()));
6853 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006854 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006855 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006856
6857 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006858 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006859 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006860 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006861 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006862
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006863 // Check that the shift amount is in range. If not, don't perform
6864 // undefined shifts. When the shift is visited it will be
6865 // simplified.
6866 uint32_t TypeBits = RHSV.getBitWidth();
6867 if (ShAmt->uge(TypeBits))
6868 break;
6869
6870 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006871
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006872 // If we are comparing against bits always shifted out, the
6873 // comparison cannot succeed.
6874 APInt Comp = RHSV << ShAmtVal;
6875 if (LHSI->getOpcode() == Instruction::LShr)
6876 Comp = Comp.lshr(ShAmtVal);
6877 else
6878 Comp = Comp.ashr(ShAmtVal);
6879
6880 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6881 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6882 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6883 return ReplaceInstUsesWith(ICI, Cst);
6884 }
6885
6886 // Otherwise, check to see if the bits shifted out are known to be zero.
6887 // If so, we can compare against the unshifted value:
6888 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006889 if (LHSI->hasOneUse() &&
6890 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006891 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6892 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6893 ConstantExpr::getShl(RHS, ShAmt));
6894 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006895
Evan Chengf30752c2008-04-23 00:38:06 +00006896 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006897 // Otherwise strength reduce the shift into an and.
6898 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6899 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006900
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006901 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006902 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006903 Mask, LHSI->getName()+".mask");
6904 Value *And = InsertNewInstBefore(AndI, ICI);
6905 return new ICmpInst(ICI.getPredicate(), And,
6906 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006907 }
6908 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006909 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006910
6911 case Instruction::SDiv:
6912 case Instruction::UDiv:
6913 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6914 // Fold this div into the comparison, producing a range check.
6915 // Determine, based on the divide type, what the range is being
6916 // checked. If there is an overflow on the low or high side, remember
6917 // it, otherwise compute the range [low, hi) bounding the new value.
6918 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006919 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6920 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6921 DivRHS))
6922 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006923 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006924
6925 case Instruction::Add:
6926 // Fold: icmp pred (add, X, C1), C2
6927
6928 if (!ICI.isEquality()) {
6929 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6930 if (!LHSC) break;
6931 const APInt &LHSV = LHSC->getValue();
6932
6933 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6934 .subtract(LHSV);
6935
6936 if (ICI.isSignedPredicate()) {
6937 if (CR.getLower().isSignBit()) {
6938 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6939 ConstantInt::get(CR.getUpper()));
6940 } else if (CR.getUpper().isSignBit()) {
6941 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6942 ConstantInt::get(CR.getLower()));
6943 }
6944 } else {
6945 if (CR.getLower().isMinValue()) {
6946 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6947 ConstantInt::get(CR.getUpper()));
6948 } else if (CR.getUpper().isMinValue()) {
6949 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6950 ConstantInt::get(CR.getLower()));
6951 }
6952 }
6953 }
6954 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006955 }
6956
6957 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6958 if (ICI.isEquality()) {
6959 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6960
6961 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6962 // the second operand is a constant, simplify a bit.
6963 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6964 switch (BO->getOpcode()) {
6965 case Instruction::SRem:
6966 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6967 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6968 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6969 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6970 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006971 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006972 BO->getName());
6973 InsertNewInstBefore(NewRem, ICI);
6974 return new ICmpInst(ICI.getPredicate(), NewRem,
6975 Constant::getNullValue(BO->getType()));
6976 }
6977 }
6978 break;
6979 case Instruction::Add:
6980 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6981 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6982 if (BO->hasOneUse())
6983 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6984 Subtract(RHS, BOp1C));
6985 } else if (RHSV == 0) {
6986 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6987 // efficiently invertible, or if the add has just this one use.
6988 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6989
6990 if (Value *NegVal = dyn_castNegVal(BOp1))
6991 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6992 else if (Value *NegVal = dyn_castNegVal(BOp0))
6993 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6994 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006995 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006996 InsertNewInstBefore(Neg, ICI);
6997 Neg->takeName(BO);
6998 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6999 }
7000 }
7001 break;
7002 case Instruction::Xor:
7003 // For the xor case, we can xor two constants together, eliminating
7004 // the explicit xor.
7005 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7006 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7007 ConstantExpr::getXor(RHS, BOC));
7008
7009 // FALLTHROUGH
7010 case Instruction::Sub:
7011 // Replace (([sub|xor] A, B) != 0) with (A != B)
7012 if (RHSV == 0)
7013 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7014 BO->getOperand(1));
7015 break;
7016
7017 case Instruction::Or:
7018 // If bits are being or'd in that are not present in the constant we
7019 // are comparing against, then the comparison could never succeed!
7020 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7021 Constant *NotCI = ConstantExpr::getNot(RHS);
7022 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7023 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7024 isICMP_NE));
7025 }
7026 break;
7027
7028 case Instruction::And:
7029 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7030 // If bits are being compared against that are and'd out, then the
7031 // comparison can never succeed!
7032 if ((RHSV & ~BOC->getValue()) != 0)
7033 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7034 isICMP_NE));
7035
7036 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7037 if (RHS == BOC && RHSV.isPowerOf2())
7038 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7039 ICmpInst::ICMP_NE, LHSI,
7040 Constant::getNullValue(RHS->getType()));
7041
7042 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007043 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007044 Value *X = BO->getOperand(0);
7045 Constant *Zero = Constant::getNullValue(X->getType());
7046 ICmpInst::Predicate pred = isICMP_NE ?
7047 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7048 return new ICmpInst(pred, X, Zero);
7049 }
7050
7051 // ((X & ~7) == 0) --> X < 8
7052 if (RHSV == 0 && isHighOnes(BOC)) {
7053 Value *X = BO->getOperand(0);
7054 Constant *NegX = ConstantExpr::getNeg(BOC);
7055 ICmpInst::Predicate pred = isICMP_NE ?
7056 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7057 return new ICmpInst(pred, X, NegX);
7058 }
7059 }
7060 default: break;
7061 }
7062 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7063 // Handle icmp {eq|ne} <intrinsic>, intcst.
7064 if (II->getIntrinsicID() == Intrinsic::bswap) {
7065 AddToWorkList(II);
7066 ICI.setOperand(0, II->getOperand(1));
7067 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
7068 return &ICI;
7069 }
7070 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007071 }
7072 return 0;
7073}
7074
7075/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7076/// We only handle extending casts so far.
7077///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007078Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7079 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007080 Value *LHSCIOp = LHSCI->getOperand(0);
7081 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007082 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007083 Value *RHSCIOp;
7084
Chris Lattner8c756c12007-05-05 22:41:33 +00007085 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7086 // integer type is the same size as the pointer type.
7087 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7088 getTargetData().getPointerSizeInBits() ==
7089 cast<IntegerType>(DestTy)->getBitWidth()) {
7090 Value *RHSOp = 0;
7091 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00007092 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007093 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7094 RHSOp = RHSC->getOperand(0);
7095 // If the pointer types don't match, insert a bitcast.
7096 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007097 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007098 }
7099
7100 if (RHSOp)
7101 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7102 }
7103
7104 // The code below only handles extension cast instructions, so far.
7105 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007106 if (LHSCI->getOpcode() != Instruction::ZExt &&
7107 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007108 return 0;
7109
Reid Spencere4d87aa2006-12-23 06:05:41 +00007110 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7111 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007112
Reid Spencere4d87aa2006-12-23 06:05:41 +00007113 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007114 // Not an extension from the same type?
7115 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007116 if (RHSCIOp->getType() != LHSCIOp->getType())
7117 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007118
Nick Lewycky4189a532008-01-28 03:48:02 +00007119 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007120 // and the other is a zext), then we can't handle this.
7121 if (CI->getOpcode() != LHSCI->getOpcode())
7122 return 0;
7123
Nick Lewycky4189a532008-01-28 03:48:02 +00007124 // Deal with equality cases early.
7125 if (ICI.isEquality())
7126 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7127
7128 // A signed comparison of sign extended values simplifies into a
7129 // signed comparison.
7130 if (isSignedCmp && isSignedExt)
7131 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7132
7133 // The other three cases all fold into an unsigned comparison.
7134 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007135 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007136
Reid Spencere4d87aa2006-12-23 06:05:41 +00007137 // If we aren't dealing with a constant on the RHS, exit early
7138 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7139 if (!CI)
7140 return 0;
7141
7142 // Compute the constant that would happen if we truncated to SrcTy then
7143 // reextended to DestTy.
7144 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7145 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7146
7147 // If the re-extended constant didn't change...
7148 if (Res2 == CI) {
7149 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7150 // For example, we might have:
7151 // %A = sext short %X to uint
7152 // %B = icmp ugt uint %A, 1330
7153 // It is incorrect to transform this into
7154 // %B = icmp ugt short %X, 1330
7155 // because %A may have negative value.
7156 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007157 // However, we allow this when the compare is EQ/NE, because they are
7158 // signless.
7159 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00007160 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007161 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007162 }
7163
7164 // The re-extended constant changed so the constant cannot be represented
7165 // in the shorter type. Consequently, we cannot emit a simple comparison.
7166
7167 // First, handle some easy cases. We know the result cannot be equal at this
7168 // point so handle the ICI.isEquality() cases
7169 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007170 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007171 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007172 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007173
7174 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7175 // should have been folded away previously and not enter in here.
7176 Value *Result;
7177 if (isSignedCmp) {
7178 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007179 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007180 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007181 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007182 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007183 } else {
7184 // We're performing an unsigned comparison.
7185 if (isSignedExt) {
7186 // We're performing an unsigned comp with a sign extended value.
7187 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007188 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007189 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7190 NegOne, ICI.getName()), ICI);
7191 } else {
7192 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007193 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007194 }
7195 }
7196
7197 // Finally, return the value computed.
7198 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007199 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007200 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007201
7202 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7203 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7204 "ICmp should be folded!");
7205 if (Constant *CI = dyn_cast<Constant>(Result))
7206 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7207 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007208}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007209
Reid Spencer832254e2007-02-02 02:16:23 +00007210Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7211 return commonShiftTransforms(I);
7212}
7213
7214Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7215 return commonShiftTransforms(I);
7216}
7217
7218Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007219 if (Instruction *R = commonShiftTransforms(I))
7220 return R;
7221
7222 Value *Op0 = I.getOperand(0);
7223
7224 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7225 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7226 if (CSI->isAllOnesValue())
7227 return ReplaceInstUsesWith(I, CSI);
7228
7229 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb44b3662009-03-18 16:32:19 +00007230 if (!isa<VectorType>(I.getType())) {
7231 if (MaskedValueIsZero(Op0,
Chris Lattner348f6652007-12-06 01:59:46 +00007232 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Chris Lattnerb44b3662009-03-18 16:32:19 +00007233 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Dan Gohman0001e562009-02-24 02:00:40 +00007234
Chris Lattnerb44b3662009-03-18 16:32:19 +00007235 // Arithmetic shifting an all-sign-bit value is a no-op.
7236 unsigned NumSignBits = ComputeNumSignBits(Op0);
7237 if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7238 return ReplaceInstUsesWith(I, Op0);
7239 }
Dan Gohman0001e562009-02-24 02:00:40 +00007240
Chris Lattner348f6652007-12-06 01:59:46 +00007241 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007242}
7243
7244Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7245 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007246 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007247
7248 // shl X, 0 == X and shr X, 0 == X
7249 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00007250 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00007251 Op0 == Constant::getNullValue(Op0->getType()))
7252 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007253
Reid Spencere4d87aa2006-12-23 06:05:41 +00007254 if (isa<UndefValue>(Op0)) {
7255 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007256 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007257 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007258 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7259 }
7260 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007261 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7262 return ReplaceInstUsesWith(I, Op0);
7263 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007264 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007265 }
7266
Dan Gohman9004c8a2009-05-21 02:28:33 +00007267 // See if we can fold away this shift.
7268 if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
7269 return &I;
7270
Chris Lattner2eefe512004-04-09 19:05:30 +00007271 // Try to fold constant and into select arguments.
7272 if (isa<Constant>(Op0))
7273 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007274 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007275 return R;
7276
Reid Spencerb83eb642006-10-20 07:07:24 +00007277 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007278 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7279 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007280 return 0;
7281}
7282
Reid Spencerb83eb642006-10-20 07:07:24 +00007283Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007284 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007285 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007286
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007287 // See if we can simplify any instructions used by the instruction whose sole
7288 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00007289 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007290
Chris Lattner4d5542c2006-01-06 07:12:35 +00007291 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7292 // of a signed value.
7293 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007294 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007295 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007296 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7297 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007298 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007299 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007300 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007301 }
7302
7303 // ((X*C1) << C2) == (X * (C1 << C2))
7304 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7305 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7306 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007307 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007308 ConstantExpr::getShl(BOOp, Op1));
7309
7310 // Try to fold constant and into select arguments.
7311 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7312 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7313 return R;
7314 if (isa<PHINode>(Op0))
7315 if (Instruction *NV = FoldOpIntoPhi(I))
7316 return NV;
7317
Chris Lattner8999dd32007-12-22 09:07:47 +00007318 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7319 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7320 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7321 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7322 // place. Don't try to do this transformation in this case. Also, we
7323 // require that the input operand is a shift-by-constant so that we have
7324 // confidence that the shifts will get folded together. We could do this
7325 // xform in more cases, but it is unlikely to be profitable.
7326 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7327 isa<ConstantInt>(TrOp->getOperand(1))) {
7328 // Okay, we'll do this xform. Make the shift of shift.
7329 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007330 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007331 I.getName());
7332 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7333
7334 // For logical shifts, the truncation has the effect of making the high
7335 // part of the register be zeros. Emulate this by inserting an AND to
7336 // clear the top bits as needed. This 'and' will usually be zapped by
7337 // other xforms later if dead.
7338 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7339 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7340 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7341
7342 // The mask we constructed says what the trunc would do if occurring
7343 // between the shifts. We want to know the effect *after* the second
7344 // shift. We know that it is a logical shift by a constant, so adjust the
7345 // mask as appropriate.
7346 if (I.getOpcode() == Instruction::Shl)
7347 MaskV <<= Op1->getZExtValue();
7348 else {
7349 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7350 MaskV = MaskV.lshr(Op1->getZExtValue());
7351 }
7352
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007353 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007354 TI->getName());
7355 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7356
7357 // Return the value truncated to the interesting size.
7358 return new TruncInst(And, I.getType());
7359 }
7360 }
7361
Chris Lattner4d5542c2006-01-06 07:12:35 +00007362 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007363 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7364 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7365 Value *V1, *V2;
7366 ConstantInt *CC;
7367 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007368 default: break;
7369 case Instruction::Add:
7370 case Instruction::And:
7371 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007372 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007373 // These operators commute.
7374 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007375 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007376 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007377 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007378 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007379 Op0BO->getName());
7380 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007381 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007382 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007383 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007384 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007385 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007386 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007387 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007388 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007389
Chris Lattner150f12a2005-09-18 06:30:59 +00007390 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007391 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007392 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007393 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007394 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7395 m_ConstantInt(CC))) &&
7396 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007397 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007398 Op0BO->getOperand(0), Op1,
7399 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007400 InsertNewInstBefore(YS, I); // (Y << C)
7401 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007402 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007403 V1->getName()+".mask");
7404 InsertNewInstBefore(XM, I); // X & (CC << C)
7405
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007406 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007407 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007408 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007409
Reid Spencera07cb7d2007-02-02 14:41:37 +00007410 // FALL THROUGH.
7411 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007412 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007413 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007414 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007415 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007416 Op0BO->getOperand(1), Op1,
7417 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007418 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007419 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007420 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007421 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007422 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007423 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007424 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007425 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007426 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007427
Chris Lattner13d4ab42006-05-31 21:14:00 +00007428 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007429 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7430 match(Op0BO->getOperand(0),
7431 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007432 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007433 cast<BinaryOperator>(Op0BO->getOperand(0))
7434 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007435 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007436 Op0BO->getOperand(1), Op1,
7437 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007438 InsertNewInstBefore(YS, I); // (Y << C)
7439 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007440 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007441 V1->getName()+".mask");
7442 InsertNewInstBefore(XM, I); // X & (CC << C)
7443
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007444 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007445 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007446
Chris Lattner11021cb2005-09-18 05:12:10 +00007447 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007448 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007449 }
7450
7451
7452 // If the operand is an bitwise operator with a constant RHS, and the
7453 // shift is the only use, we can pull it out of the shift.
7454 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7455 bool isValid = true; // Valid only for And, Or, Xor
7456 bool highBitSet = false; // Transform if high bit of constant set?
7457
7458 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007459 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007460 case Instruction::Add:
7461 isValid = isLeftShift;
7462 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007463 case Instruction::Or:
7464 case Instruction::Xor:
7465 highBitSet = false;
7466 break;
7467 case Instruction::And:
7468 highBitSet = true;
7469 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007470 }
7471
7472 // If this is a signed shift right, and the high bit is modified
7473 // by the logical operation, do not perform the transformation.
7474 // The highBitSet boolean indicates the value of the high bit of
7475 // the constant which would cause it to be modified for this
7476 // operation.
7477 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007478 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007479 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007480
7481 if (isValid) {
7482 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7483
7484 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007485 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007486 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007487 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007488
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007489 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007490 NewRHS);
7491 }
7492 }
7493 }
7494 }
7495
Chris Lattnerad0124c2006-01-06 07:52:12 +00007496 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007497 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7498 if (ShiftOp && !ShiftOp->isShift())
7499 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007500
Reid Spencerb83eb642006-10-20 07:07:24 +00007501 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007502 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007503 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7504 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007505 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7506 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7507 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007508
Zhou Sheng4351c642007-04-02 08:20:41 +00007509 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007510
7511 const IntegerType *Ty = cast<IntegerType>(I.getType());
7512
7513 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007514 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007515 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7516 // saturates.
7517 if (AmtSum >= TypeBits) {
7518 if (I.getOpcode() != Instruction::AShr)
7519 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7520 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7521 }
7522
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007523 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007524 ConstantInt::get(Ty, AmtSum));
7525 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7526 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007527 if (AmtSum >= TypeBits)
7528 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7529
Chris Lattnerb87056f2007-02-05 00:57:54 +00007530 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007531 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007532 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7533 I.getOpcode() == Instruction::LShr) {
7534 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007535 if (AmtSum >= TypeBits)
7536 AmtSum = TypeBits-1;
7537
Chris Lattnerb87056f2007-02-05 00:57:54 +00007538 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007539 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007540 InsertNewInstBefore(Shift, I);
7541
Zhou Shenge9e03f62007-03-28 15:02:20 +00007542 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007543 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007544 }
7545
Chris Lattnerb87056f2007-02-05 00:57:54 +00007546 // Okay, if we get here, one shift must be left, and the other shift must be
7547 // right. See if the amounts are equal.
7548 if (ShiftAmt1 == ShiftAmt2) {
7549 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7550 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007551 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007552 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007553 }
7554 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7555 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007556 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007557 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007558 }
7559 // We can simplify ((X << C) >>s C) into a trunc + sext.
7560 // NOTE: we could do this for any C, but that would make 'unusual' integer
7561 // types. For now, just stick to ones well-supported by the code
7562 // generators.
7563 const Type *SExtType = 0;
7564 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007565 case 1 :
7566 case 8 :
7567 case 16 :
7568 case 32 :
7569 case 64 :
7570 case 128:
7571 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7572 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007573 default: break;
7574 }
7575 if (SExtType) {
7576 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7577 InsertNewInstBefore(NewTrunc, I);
7578 return new SExtInst(NewTrunc, Ty);
7579 }
7580 // Otherwise, we can't handle it yet.
7581 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007582 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007583
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007584 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007585 if (I.getOpcode() == Instruction::Shl) {
7586 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7587 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007588 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007589 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007590 InsertNewInstBefore(Shift, I);
7591
Reid Spencer55702aa2007-03-25 21:11:44 +00007592 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007593 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007594 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007595
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007596 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007597 if (I.getOpcode() == Instruction::LShr) {
7598 assert(ShiftOp->getOpcode() == Instruction::Shl);
7599 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007600 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007601 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007602
Reid Spencerd5e30f02007-03-26 17:18:58 +00007603 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007604 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007605 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007606
7607 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7608 } else {
7609 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007610 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007611
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007612 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007613 if (I.getOpcode() == Instruction::Shl) {
7614 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7615 ShiftOp->getOpcode() == Instruction::AShr);
7616 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007617 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007618 ConstantInt::get(Ty, ShiftDiff));
7619 InsertNewInstBefore(Shift, I);
7620
Reid Spencer55702aa2007-03-25 21:11:44 +00007621 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007622 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007623 }
7624
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007625 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007626 if (I.getOpcode() == Instruction::LShr) {
7627 assert(ShiftOp->getOpcode() == Instruction::Shl);
7628 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007629 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007630 InsertNewInstBefore(Shift, I);
7631
Reid Spencer68d27cf2007-03-26 23:45:51 +00007632 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007633 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007634 }
7635
7636 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007637 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007638 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007639 return 0;
7640}
7641
Chris Lattnera1be5662002-05-02 17:06:02 +00007642
Chris Lattnercfd65102005-10-29 04:36:15 +00007643/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7644/// expression. If so, decompose it, returning some value X, such that Val is
7645/// X*Scale+Offset.
7646///
7647static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007648 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007649 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007650 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007651 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007652 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007653 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007654 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7655 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7656 if (I->getOpcode() == Instruction::Shl) {
7657 // This is a value scaled by '1 << the shift amt'.
7658 Scale = 1U << RHS->getZExtValue();
7659 Offset = 0;
7660 return I->getOperand(0);
7661 } else if (I->getOpcode() == Instruction::Mul) {
7662 // This value is scaled by 'RHS'.
7663 Scale = RHS->getZExtValue();
7664 Offset = 0;
7665 return I->getOperand(0);
7666 } else if (I->getOpcode() == Instruction::Add) {
7667 // We have X+C. Check to see if we really have (X*C2)+C1,
7668 // where C1 is divisible by C2.
7669 unsigned SubScale;
7670 Value *SubVal =
7671 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7672 Offset += RHS->getZExtValue();
7673 Scale = SubScale;
7674 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007675 }
7676 }
7677 }
7678
7679 // Otherwise, we can't look past this.
7680 Scale = 1;
7681 Offset = 0;
7682 return Val;
7683}
7684
7685
Chris Lattnerb3f83972005-10-24 06:03:58 +00007686/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7687/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007688Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007689 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007690 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007691
Chris Lattnerb53c2382005-10-24 06:22:12 +00007692 // Remove any uses of AI that are dead.
7693 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007694
Chris Lattnerb53c2382005-10-24 06:22:12 +00007695 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7696 Instruction *User = cast<Instruction>(*UI++);
7697 if (isInstructionTriviallyDead(User)) {
7698 while (UI != E && *UI == User)
7699 ++UI; // If this instruction uses AI more than once, don't break UI.
7700
Chris Lattnerb53c2382005-10-24 06:22:12 +00007701 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007702 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007703 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007704 }
7705 }
7706
Chris Lattnerb3f83972005-10-24 06:03:58 +00007707 // Get the type really allocated and the type casted to.
7708 const Type *AllocElTy = AI.getAllocatedType();
7709 const Type *CastElTy = PTy->getElementType();
7710 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007711
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007712 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7713 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007714 if (CastElTyAlign < AllocElTyAlign) return 0;
7715
Chris Lattner39387a52005-10-24 06:35:18 +00007716 // If the allocation has multiple uses, only promote it if we are strictly
7717 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007718 // same, we open the door to infinite loops of various kinds. (A reference
7719 // from a dbg.declare doesn't count as a use for this purpose.)
7720 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7721 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007722
Duncan Sands777d2302009-05-09 07:06:46 +00007723 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7724 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007725 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007726
Chris Lattner455fcc82005-10-29 03:19:53 +00007727 // See if we can satisfy the modulus by pulling a scale out of the array
7728 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007729 unsigned ArraySizeScale;
7730 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007731 Value *NumElements = // See if the array size is a decomposable linear expr.
7732 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7733
Chris Lattner455fcc82005-10-29 03:19:53 +00007734 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7735 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007736 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7737 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007738
Chris Lattner455fcc82005-10-29 03:19:53 +00007739 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7740 Value *Amt = 0;
7741 if (Scale == 1) {
7742 Amt = NumElements;
7743 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007744 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007745 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7746 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007747 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007748 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007749 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007750 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007751 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007752 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007753 }
7754
Jeff Cohen86796be2007-04-04 16:58:57 +00007755 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7756 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007757 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007758 Amt = InsertNewInstBefore(Tmp, AI);
7759 }
7760
Chris Lattnerb3f83972005-10-24 06:03:58 +00007761 AllocationInst *New;
7762 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007763 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007764 else
Chris Lattner6934a042007-02-11 01:23:03 +00007765 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007766 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007767 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007768
Dale Johannesena0a66372009-03-05 00:39:02 +00007769 // If the allocation has one real use plus a dbg.declare, just remove the
7770 // declare.
7771 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7772 EraseInstFromFunction(*DI);
7773 }
7774 // If the allocation has multiple real uses, insert a cast and change all
7775 // things that used it to use the new cast. This will also hack on CI, but it
7776 // will die soon.
7777 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007778 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007779 // New is the allocation instruction, pointer typed. AI is the original
7780 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7781 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007782 InsertNewInstBefore(NewCast, AI);
7783 AI.replaceAllUsesWith(NewCast);
7784 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007785 return ReplaceInstUsesWith(CI, New);
7786}
7787
Chris Lattner70074e02006-05-13 02:06:03 +00007788/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007789/// and return it as type Ty without inserting any new casts and without
7790/// changing the computed value. This is used by code that tries to decide
7791/// whether promoting or shrinking integer operations to wider or smaller types
7792/// will allow us to eliminate a truncate or extend.
7793///
7794/// This is a truncation operation if Ty is smaller than V->getType(), or an
7795/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007796///
7797/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7798/// should return true if trunc(V) can be computed by computing V in the smaller
7799/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7800/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7801/// efficiently truncated.
7802///
7803/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7804/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7805/// the final result.
Evan Cheng4e56ab22009-01-16 02:11:43 +00007806bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7807 unsigned CastOpc,
7808 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007809 // We can always evaluate constants in another type.
7810 if (isa<ConstantInt>(V))
7811 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007812
7813 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007814 if (!I) return false;
7815
7816 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007817
Chris Lattner951626b2007-08-02 06:11:14 +00007818 // If this is an extension or truncate, we can often eliminate it.
7819 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7820 // If this is a cast from the destination type, we can trivially eliminate
7821 // it, and this will remove a cast overall.
7822 if (I->getOperand(0)->getType() == Ty) {
7823 // If the first operand is itself a cast, and is eliminable, do not count
7824 // this as an eliminable cast. We would prefer to eliminate those two
7825 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007826 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007827 ++NumCastsRemoved;
7828 return true;
7829 }
7830 }
7831
7832 // We can't extend or shrink something that has multiple uses: doing so would
7833 // require duplicating the instruction in general, which isn't profitable.
7834 if (!I->hasOneUse()) return false;
7835
Evan Chengf35fd542009-01-15 17:01:23 +00007836 unsigned Opc = I->getOpcode();
7837 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007838 case Instruction::Add:
7839 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007840 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007841 case Instruction::And:
7842 case Instruction::Or:
7843 case Instruction::Xor:
7844 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007845 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007846 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007847 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007848 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007849
Chris Lattner46b96052006-11-29 07:18:39 +00007850 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007851 // If we are truncating the result of this SHL, and if it's a shift of a
7852 // constant amount, we can always perform a SHL in a smaller type.
7853 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007854 uint32_t BitWidth = Ty->getBitWidth();
7855 if (BitWidth < OrigTy->getBitWidth() &&
7856 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007857 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007858 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007859 }
7860 break;
7861 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007862 // If this is a truncate of a logical shr, we can truncate it to a smaller
7863 // lshr iff we know that the bits we would otherwise be shifting in are
7864 // already zeros.
7865 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007866 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7867 uint32_t BitWidth = Ty->getBitWidth();
7868 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007869 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007870 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7871 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007872 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007873 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007874 }
7875 }
Chris Lattner46b96052006-11-29 07:18:39 +00007876 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007877 case Instruction::ZExt:
7878 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007879 case Instruction::Trunc:
7880 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007881 // can safely replace it. Note that replacing it does not reduce the number
7882 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007883 if (Opc == CastOpc)
7884 return true;
7885
7886 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007887 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007888 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007889 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007890 case Instruction::Select: {
7891 SelectInst *SI = cast<SelectInst>(I);
7892 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007893 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007894 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007895 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007896 }
Chris Lattner8114b712008-06-18 04:00:49 +00007897 case Instruction::PHI: {
7898 // We can change a phi if we can change all operands.
7899 PHINode *PN = cast<PHINode>(I);
7900 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7901 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007902 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007903 return false;
7904 return true;
7905 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007906 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007907 // TODO: Can handle more cases here.
7908 break;
7909 }
7910
7911 return false;
7912}
7913
7914/// EvaluateInDifferentType - Given an expression that
7915/// CanEvaluateInDifferentType returns true for, actually insert the code to
7916/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007917Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007918 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007919 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007920 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007921
7922 // Otherwise, it must be an instruction.
7923 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007924 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007925 unsigned Opc = I->getOpcode();
7926 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007927 case Instruction::Add:
7928 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007929 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007930 case Instruction::And:
7931 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007932 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007933 case Instruction::AShr:
7934 case Instruction::LShr:
7935 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007936 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007937 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007938 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007939 break;
7940 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007941 case Instruction::Trunc:
7942 case Instruction::ZExt:
7943 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007944 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007945 // just return the source. There's no need to insert it because it is not
7946 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007947 if (I->getOperand(0)->getType() == Ty)
7948 return I->getOperand(0);
7949
Chris Lattner8114b712008-06-18 04:00:49 +00007950 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007951 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007952 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007953 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007954 case Instruction::Select: {
7955 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7956 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7957 Res = SelectInst::Create(I->getOperand(0), True, False);
7958 break;
7959 }
Chris Lattner8114b712008-06-18 04:00:49 +00007960 case Instruction::PHI: {
7961 PHINode *OPN = cast<PHINode>(I);
7962 PHINode *NPN = PHINode::Create(Ty);
7963 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7964 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7965 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7966 }
7967 Res = NPN;
7968 break;
7969 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007970 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007971 // TODO: Can handle more cases here.
7972 assert(0 && "Unreachable!");
7973 break;
7974 }
7975
Chris Lattner8114b712008-06-18 04:00:49 +00007976 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007977 return InsertNewInstBefore(Res, *I);
7978}
7979
Reid Spencer3da59db2006-11-27 01:05:10 +00007980/// @brief Implement the transforms common to all CastInst visitors.
7981Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007982 Value *Src = CI.getOperand(0);
7983
Dan Gohman23d9d272007-05-11 21:10:54 +00007984 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007985 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007986 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007987 if (Instruction::CastOps opc =
7988 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7989 // The first cast (CSrc) is eliminable so we need to fix up or replace
7990 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007991 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007992 }
7993 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007994
Reid Spencer3da59db2006-11-27 01:05:10 +00007995 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007996 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7997 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7998 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007999
8000 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008001 if (isa<PHINode>(Src))
8002 if (Instruction *NV = FoldOpIntoPhi(CI))
8003 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008004
Reid Spencer3da59db2006-11-27 01:05:10 +00008005 return 0;
8006}
8007
Chris Lattner46cd5a12009-01-09 05:44:56 +00008008/// FindElementAtOffset - Given a type and a constant offset, determine whether
8009/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008010/// the specified offset. If so, fill them into NewIndices and return the
8011/// resultant element type, otherwise return null.
8012static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8013 SmallVectorImpl<Value*> &NewIndices,
8014 const TargetData *TD) {
8015 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008016
8017 // Start with the index over the outer type. Note that the type size
8018 // might be zero (even if the offset isn't zero) if the indexed type
8019 // is something like [0 x {int, int}]
8020 const Type *IntPtrTy = TD->getIntPtrType();
8021 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008022 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008023 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008024 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008025
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008026 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008027 if (Offset < 0) {
8028 --FirstIdx;
8029 Offset += TySize;
8030 assert(Offset >= 0);
8031 }
8032 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8033 }
8034
8035 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8036
8037 // Index into the types. If we fail, set OrigBase to null.
8038 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008039 // Indexing into tail padding between struct/array elements.
8040 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008041 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008042
Chris Lattner46cd5a12009-01-09 05:44:56 +00008043 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8044 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008045 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8046 "Offset must stay within the indexed type");
8047
Chris Lattner46cd5a12009-01-09 05:44:56 +00008048 unsigned Elt = SL->getElementContainingOffset(Offset);
8049 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
8050
8051 Offset -= SL->getElementOffset(Elt);
8052 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008053 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008054 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008055 assert(EltSize && "Cannot index into a zero-sized array");
8056 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8057 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008058 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008059 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008060 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008061 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008062 }
8063 }
8064
Chris Lattner3914f722009-01-24 01:00:13 +00008065 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008066}
8067
Chris Lattnerd3e28342007-04-27 17:44:50 +00008068/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8069Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8070 Value *Src = CI.getOperand(0);
8071
Chris Lattnerd3e28342007-04-27 17:44:50 +00008072 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008073 // If casting the result of a getelementptr instruction with no offset, turn
8074 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008075 if (GEP->hasAllZeroIndices()) {
8076 // Changing the cast operand is usually not a good idea but it is safe
8077 // here because the pointer operand is being replaced with another
8078 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008079 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008080 CI.setOperand(0, GEP->getOperand(0));
8081 return &CI;
8082 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008083
8084 // If the GEP has a single use, and the base pointer is a bitcast, and the
8085 // GEP computes a constant offset, see if we can convert these three
8086 // instructions into fewer. This typically happens with unions and other
8087 // non-type-safe code.
8088 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8089 if (GEP->hasAllConstantIndices()) {
8090 // We are guaranteed to get a constant from EmitGEPOffset.
8091 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8092 int64_t Offset = OffsetV->getSExtValue();
8093
8094 // Get the base pointer input of the bitcast, and the type it points to.
8095 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8096 const Type *GEPIdxTy =
8097 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008098 SmallVector<Value*, 8> NewIndices;
8099 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
8100 // If we were able to index down into an element, create the GEP
8101 // and bitcast the result. This eliminates one bitcast, potentially
8102 // two.
8103 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8104 NewIndices.begin(),
8105 NewIndices.end(), "");
8106 InsertNewInstBefore(NGEP, CI);
8107 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008108
Chris Lattner46cd5a12009-01-09 05:44:56 +00008109 if (isa<BitCastInst>(CI))
8110 return new BitCastInst(NGEP, CI.getType());
8111 assert(isa<PtrToIntInst>(CI));
8112 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008113 }
8114 }
8115 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008116 }
8117
8118 return commonCastTransforms(CI);
8119}
8120
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008121/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8122/// type like i42. We don't want to introduce operations on random non-legal
8123/// integer types where they don't already exist in the code. In the future,
8124/// we should consider making this based off target-data, so that 32-bit targets
8125/// won't get i64 operations etc.
8126static bool isSafeIntegerType(const Type *Ty) {
8127 switch (Ty->getPrimitiveSizeInBits()) {
8128 case 8:
8129 case 16:
8130 case 32:
8131 case 64:
8132 return true;
8133 default:
8134 return false;
8135 }
8136}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008137
Chris Lattnerc739cd62007-03-03 05:27:34 +00008138/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8139/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00008140/// cases.
8141/// @brief Implement the transforms common to CastInst with integer operands
8142Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8143 if (Instruction *Result = commonCastTransforms(CI))
8144 return Result;
8145
8146 Value *Src = CI.getOperand(0);
8147 const Type *SrcTy = Src->getType();
8148 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00008149 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
8150 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008151
Reid Spencer3da59db2006-11-27 01:05:10 +00008152 // See if we can simplify any instructions used by the LHS whose sole
8153 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008154 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008155 return &CI;
8156
8157 // If the source isn't an instruction or has more than one use then we
8158 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008159 Instruction *SrcI = dyn_cast<Instruction>(Src);
8160 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008161 return 0;
8162
Chris Lattnerc739cd62007-03-03 05:27:34 +00008163 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008164 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008165 if (!isa<BitCastInst>(CI) &&
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008166 // Only do this if the dest type is a simple type, don't convert the
8167 // expression tree to something weird like i93 unless the source is also
8168 // strange.
8169 (isSafeIntegerType(DestTy) || !isSafeIntegerType(SrcI->getType())) &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008170 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Evan Cheng4e56ab22009-01-16 02:11:43 +00008171 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008172 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008173 // eliminates the cast, so it is always a win. If this is a zero-extension,
8174 // we need to do an AND to maintain the clear top-part of the computation,
8175 // so we require that the input have eliminated at least one cast. If this
8176 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008177 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008178 bool DoXForm = false;
8179 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008180 switch (CI.getOpcode()) {
8181 default:
8182 // All the others use floating point so we shouldn't actually
8183 // get here because of the check above.
8184 assert(0 && "Unknown cast type");
8185 case Instruction::Trunc:
8186 DoXForm = true;
8187 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008188 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008189 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008190 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008191 // If it's unnecessary to issue an AND to clear the high bits, it's
8192 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008193 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008194 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8195 if (MaskedValueIsZero(TryRes, Mask))
8196 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008197
8198 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008199 if (TryI->use_empty())
8200 EraseInstFromFunction(*TryI);
8201 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008202 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008203 }
Evan Chengf35fd542009-01-15 17:01:23 +00008204 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008205 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008206 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008207 // If we do not have to emit the truncate + sext pair, then it's always
8208 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008209 //
8210 // It's not safe to eliminate the trunc + sext pair if one of the
8211 // eliminated cast is a truncate. e.g.
8212 // t2 = trunc i32 t1 to i16
8213 // t3 = sext i16 t2 to i32
8214 // !=
8215 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008216 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008217 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8218 if (NumSignBits > (DestBitSize - SrcBitSize))
8219 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008220
8221 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008222 if (TryI->use_empty())
8223 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008224 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008225 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008226 }
Evan Chengf35fd542009-01-15 17:01:23 +00008227 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008228
8229 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008230 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8231 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008232 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8233 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008234 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008235 // Just replace this cast with the result.
8236 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008237
Reid Spencer3da59db2006-11-27 01:05:10 +00008238 assert(Res->getType() == DestTy);
8239 switch (CI.getOpcode()) {
8240 default: assert(0 && "Unknown cast type!");
8241 case Instruction::Trunc:
8242 case Instruction::BitCast:
8243 // Just replace this cast with the result.
8244 return ReplaceInstUsesWith(CI, Res);
8245 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008246 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008247
8248 // If the high bits are already zero, just replace this cast with the
8249 // result.
8250 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8251 if (MaskedValueIsZero(Res, Mask))
8252 return ReplaceInstUsesWith(CI, Res);
8253
8254 // We need to emit an AND to clear the high bits.
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008255 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8256 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008257 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008258 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008259 case Instruction::SExt: {
8260 // If the high bits are already filled with sign bit, just replace this
8261 // cast with the result.
8262 unsigned NumSignBits = ComputeNumSignBits(Res);
8263 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008264 return ReplaceInstUsesWith(CI, Res);
8265
Reid Spencer3da59db2006-11-27 01:05:10 +00008266 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008267 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008268 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8269 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008270 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008271 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008272 }
8273 }
8274
8275 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8276 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8277
8278 switch (SrcI->getOpcode()) {
8279 case Instruction::Add:
8280 case Instruction::Mul:
8281 case Instruction::And:
8282 case Instruction::Or:
8283 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008284 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00008285 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8286 // Don't insert two casts if they cannot be eliminated. We allow
8287 // two casts to be inserted if the sizes are the same. This could
8288 // only be converting signedness, which is a noop.
8289 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008290 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8291 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00008292 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008293 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8294 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008295 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008296 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008297 }
8298 }
8299
8300 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8301 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8302 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008303 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008304 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008305 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008306 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008307 }
8308 break;
8309 case Instruction::SDiv:
8310 case Instruction::UDiv:
8311 case Instruction::SRem:
8312 case Instruction::URem:
8313 // If we are just changing the sign, rewrite.
8314 if (DestBitSize == SrcBitSize) {
8315 // Don't insert two casts if they cannot be eliminated. We allow
8316 // two casts to be inserted if the sizes are the same. This could
8317 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008318 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8319 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008320 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8321 Op0, DestTy, *SrcI);
8322 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8323 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008324 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00008325 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8326 }
8327 }
8328 break;
8329
8330 case Instruction::Shl:
8331 // Allow changing the sign of the source operand. Do not allow
8332 // changing the size of the shift, UNLESS the shift amount is a
8333 // constant. We must not change variable sized shifts to a smaller
8334 // size, because it is undefined to shift more bits out than exist
8335 // in the value.
8336 if (DestBitSize == SrcBitSize ||
8337 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00008338 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8339 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008340 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8341 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008342 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008343 }
8344 break;
8345 case Instruction::AShr:
8346 // If this is a signed shr, and if all bits shifted in are about to be
8347 // truncated off, turn it into an unsigned shr to allow greater
8348 // simplifications.
8349 if (DestBitSize < SrcBitSize &&
8350 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008351 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00008352 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8353 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008354 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008355 }
8356 }
8357 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008358 }
8359 return 0;
8360}
8361
Chris Lattner8a9f5712007-04-11 06:57:46 +00008362Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008363 if (Instruction *Result = commonIntCastTransforms(CI))
8364 return Result;
8365
8366 Value *Src = CI.getOperand(0);
8367 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00008368 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8369 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008370
8371 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8372 if (DestBitWidth == 1) {
8373 Constant *One = ConstantInt::get(Src->getType(), 1);
8374 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8375 Value *Zero = Constant::getNullValue(Src->getType());
8376 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8377 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008378
Chris Lattner4f9797d2009-03-24 18:15:30 +00008379 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8380 ConstantInt *ShAmtV = 0;
8381 Value *ShiftOp = 0;
8382 if (Src->hasOneUse() &&
8383 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8384 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8385
8386 // Get a mask for the bits shifting in.
8387 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8388 if (MaskedValueIsZero(ShiftOp, Mask)) {
8389 if (ShAmt >= DestBitWidth) // All zeros.
8390 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8391
8392 // Okay, we can shrink this. Truncate the input, then return a new
8393 // shift.
8394 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8395 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8396 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008397 }
8398 }
8399
8400 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008401}
8402
Evan Chengb98a10e2008-03-24 00:21:34 +00008403/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8404/// in order to eliminate the icmp.
8405Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8406 bool DoXform) {
8407 // If we are just checking for a icmp eq of a single bit and zext'ing it
8408 // to an integer, then shift the bit to the appropriate place and then
8409 // cast to integer to avoid the comparison.
8410 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8411 const APInt &Op1CV = Op1C->getValue();
8412
8413 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8414 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8415 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8416 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8417 if (!DoXform) return ICI;
8418
8419 Value *In = ICI->getOperand(0);
8420 Value *Sh = ConstantInt::get(In->getType(),
8421 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008422 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008423 In->getName()+".lobit"),
8424 CI);
8425 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008426 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008427 false/*ZExt*/, "tmp", &CI);
8428
8429 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8430 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008431 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008432 In->getName()+".not"),
8433 CI);
8434 }
8435
8436 return ReplaceInstUsesWith(CI, In);
8437 }
8438
8439
8440
8441 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8442 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8443 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8444 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8445 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8446 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8447 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8448 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8449 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8450 // This only works for EQ and NE
8451 ICI->isEquality()) {
8452 // If Op1C some other power of two, convert:
8453 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8454 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8455 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8456 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8457
8458 APInt KnownZeroMask(~KnownZero);
8459 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8460 if (!DoXform) return ICI;
8461
8462 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8463 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8464 // (X&4) == 2 --> false
8465 // (X&4) != 2 --> true
8466 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8467 Res = ConstantExpr::getZExt(Res, CI.getType());
8468 return ReplaceInstUsesWith(CI, Res);
8469 }
8470
8471 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8472 Value *In = ICI->getOperand(0);
8473 if (ShiftAmt) {
8474 // Perform a logical shr by shiftamt.
8475 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008476 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008477 ConstantInt::get(In->getType(), ShiftAmt),
8478 In->getName()+".lobit"), CI);
8479 }
8480
8481 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8482 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008483 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008484 InsertNewInstBefore(cast<Instruction>(In), CI);
8485 }
8486
8487 if (CI.getType() == In->getType())
8488 return ReplaceInstUsesWith(CI, In);
8489 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008490 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008491 }
8492 }
8493 }
8494
8495 return 0;
8496}
8497
Chris Lattner8a9f5712007-04-11 06:57:46 +00008498Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008499 // If one of the common conversion will work ..
8500 if (Instruction *Result = commonIntCastTransforms(CI))
8501 return Result;
8502
8503 Value *Src = CI.getOperand(0);
8504
Chris Lattnera84f47c2009-02-17 20:47:23 +00008505 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8506 // types and if the sizes are just right we can convert this into a logical
8507 // 'and' which will be much cheaper than the pair of casts.
8508 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8509 // Get the sizes of the types involved. We know that the intermediate type
8510 // will be smaller than A or C, but don't know the relation between A and C.
8511 Value *A = CSrc->getOperand(0);
8512 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8513 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8514 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8515 // If we're actually extending zero bits, then if
8516 // SrcSize < DstSize: zext(a & mask)
8517 // SrcSize == DstSize: a & mask
8518 // SrcSize > DstSize: trunc(a) & mask
8519 if (SrcSize < DstSize) {
8520 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8521 Constant *AndConst = ConstantInt::get(AndValue);
8522 Instruction *And =
8523 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8524 InsertNewInstBefore(And, CI);
8525 return new ZExtInst(And, CI.getType());
8526 } else if (SrcSize == DstSize) {
8527 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8528 return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8529 } else if (SrcSize > DstSize) {
8530 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8531 InsertNewInstBefore(Trunc, CI);
8532 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8533 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008534 }
8535 }
8536
Evan Chengb98a10e2008-03-24 00:21:34 +00008537 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8538 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008539
Evan Chengb98a10e2008-03-24 00:21:34 +00008540 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8541 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8542 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8543 // of the (zext icmp) will be transformed.
8544 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8545 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8546 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8547 (transformZExtICmp(LHS, CI, false) ||
8548 transformZExtICmp(RHS, CI, false))) {
8549 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8550 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008551 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008552 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008553 }
8554
Reid Spencer3da59db2006-11-27 01:05:10 +00008555 return 0;
8556}
8557
Chris Lattner8a9f5712007-04-11 06:57:46 +00008558Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008559 if (Instruction *I = commonIntCastTransforms(CI))
8560 return I;
8561
Chris Lattner8a9f5712007-04-11 06:57:46 +00008562 Value *Src = CI.getOperand(0);
8563
Dan Gohman1975d032008-10-30 20:40:10 +00008564 // Canonicalize sign-extend from i1 to a select.
8565 if (Src->getType() == Type::Int1Ty)
8566 return SelectInst::Create(Src,
8567 ConstantInt::getAllOnesValue(CI.getType()),
8568 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008569
8570 // See if the value being truncated is already sign extended. If so, just
8571 // eliminate the trunc/sext pair.
8572 if (getOpcode(Src) == Instruction::Trunc) {
8573 Value *Op = cast<User>(Src)->getOperand(0);
8574 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8575 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8576 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8577 unsigned NumSignBits = ComputeNumSignBits(Op);
8578
8579 if (OpBits == DestBits) {
8580 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8581 // bits, it is already ready.
8582 if (NumSignBits > DestBits-MidBits)
8583 return ReplaceInstUsesWith(CI, Op);
8584 } else if (OpBits < DestBits) {
8585 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8586 // bits, just sext from i32.
8587 if (NumSignBits > OpBits-MidBits)
8588 return new SExtInst(Op, CI.getType(), "tmp");
8589 } else {
8590 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8591 // bits, just truncate to i32.
8592 if (NumSignBits > OpBits-MidBits)
8593 return new TruncInst(Op, CI.getType(), "tmp");
8594 }
8595 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008596
8597 // If the input is a shl/ashr pair of a same constant, then this is a sign
8598 // extension from a smaller value. If we could trust arbitrary bitwidth
8599 // integers, we could turn this into a truncate to the smaller bit and then
8600 // use a sext for the whole extension. Since we don't, look deeper and check
8601 // for a truncate. If the source and dest are the same type, eliminate the
8602 // trunc and extend and just do shifts. For example, turn:
8603 // %a = trunc i32 %i to i8
8604 // %b = shl i8 %a, 6
8605 // %c = ashr i8 %b, 6
8606 // %d = sext i8 %c to i32
8607 // into:
8608 // %a = shl i32 %i, 30
8609 // %d = ashr i32 %a, 30
8610 Value *A = 0;
8611 ConstantInt *BA = 0, *CA = 0;
8612 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8613 m_ConstantInt(CA))) &&
8614 BA == CA && isa<TruncInst>(A)) {
8615 Value *I = cast<TruncInst>(A)->getOperand(0);
8616 if (I->getType() == CI.getType()) {
8617 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8618 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8619 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8620 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8621 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8622 CI.getName()), CI);
8623 return BinaryOperator::CreateAShr(I, ShAmtV);
8624 }
8625 }
8626
Chris Lattnerba417832007-04-11 06:12:58 +00008627 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008628}
8629
Chris Lattnerb7530652008-01-27 05:29:54 +00008630/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8631/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008632static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008633 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008634 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008635 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8636 if (!losesInfo)
Chris Lattner02a260a2008-04-20 00:41:09 +00008637 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008638 return 0;
8639}
8640
8641/// LookThroughFPExtensions - If this is an fp extension instruction, look
8642/// through it until we get the source value.
8643static Value *LookThroughFPExtensions(Value *V) {
8644 if (Instruction *I = dyn_cast<Instruction>(V))
8645 if (I->getOpcode() == Instruction::FPExt)
8646 return LookThroughFPExtensions(I->getOperand(0));
8647
8648 // If this value is a constant, return the constant in the smallest FP type
8649 // that can accurately represent it. This allows us to turn
8650 // (float)((double)X+2.0) into x+2.0f.
8651 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8652 if (CFP->getType() == Type::PPC_FP128Ty)
8653 return V; // No constant folding of this.
8654 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008655 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008656 return V;
8657 if (CFP->getType() == Type::DoubleTy)
8658 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008659 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008660 return V;
8661 // Don't try to shrink to various long double types.
8662 }
8663
8664 return V;
8665}
8666
8667Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8668 if (Instruction *I = commonCastTransforms(CI))
8669 return I;
8670
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008671 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008672 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008673 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008674 // many builtins (sqrt, etc).
8675 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8676 if (OpI && OpI->hasOneUse()) {
8677 switch (OpI->getOpcode()) {
8678 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008679 case Instruction::FAdd:
8680 case Instruction::FSub:
8681 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008682 case Instruction::FDiv:
8683 case Instruction::FRem:
8684 const Type *SrcTy = OpI->getType();
8685 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8686 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8687 if (LHSTrunc->getType() != SrcTy &&
8688 RHSTrunc->getType() != SrcTy) {
8689 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8690 // If the source types were both smaller than the destination type of
8691 // the cast, do this xform.
8692 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8693 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8694 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8695 CI.getType(), CI);
8696 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8697 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008698 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008699 }
8700 }
8701 break;
8702 }
8703 }
8704 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008705}
8706
8707Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8708 return commonCastTransforms(CI);
8709}
8710
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008711Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008712 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8713 if (OpI == 0)
8714 return commonCastTransforms(FI);
8715
8716 // fptoui(uitofp(X)) --> X
8717 // fptoui(sitofp(X)) --> X
8718 // This is safe if the intermediate type has enough bits in its mantissa to
8719 // accurately represent all values of X. For example, do not do this with
8720 // i64->float->i64. This is also safe for sitofp case, because any negative
8721 // 'X' value would cause an undefined result for the fptoui.
8722 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8723 OpI->getOperand(0)->getType() == FI.getType() &&
8724 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8725 OpI->getType()->getFPMantissaWidth())
8726 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008727
8728 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008729}
8730
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008731Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008732 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8733 if (OpI == 0)
8734 return commonCastTransforms(FI);
8735
8736 // fptosi(sitofp(X)) --> X
8737 // fptosi(uitofp(X)) --> X
8738 // This is safe if the intermediate type has enough bits in its mantissa to
8739 // accurately represent all values of X. For example, do not do this with
8740 // i64->float->i64. This is also safe for sitofp case, because any negative
8741 // 'X' value would cause an undefined result for the fptoui.
8742 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8743 OpI->getOperand(0)->getType() == FI.getType() &&
8744 (int)FI.getType()->getPrimitiveSizeInBits() <=
8745 OpI->getType()->getFPMantissaWidth())
8746 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008747
8748 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008749}
8750
8751Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8752 return commonCastTransforms(CI);
8753}
8754
8755Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8756 return commonCastTransforms(CI);
8757}
8758
Chris Lattnera0e69692009-03-24 18:35:40 +00008759Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8760 // If the destination integer type is smaller than the intptr_t type for
8761 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8762 // trunc to be exposed to other transforms. Don't do this for extending
8763 // ptrtoint's, because we don't know if the target sign or zero extends its
8764 // pointers.
8765 if (CI.getType()->getPrimitiveSizeInBits() < TD->getPointerSizeInBits()) {
8766 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8767 TD->getIntPtrType(),
8768 "tmp"), CI);
8769 return new TruncInst(P, CI.getType());
8770 }
8771
Chris Lattnerd3e28342007-04-27 17:44:50 +00008772 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008773}
8774
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008775Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008776 // If the source integer type is larger than the intptr_t type for
8777 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8778 // allows the trunc to be exposed to other transforms. Don't do this for
8779 // extending inttoptr's, because we don't know if the target sign or zero
8780 // extends to pointers.
8781 if (CI.getOperand(0)->getType()->getPrimitiveSizeInBits() >
8782 TD->getPointerSizeInBits()) {
8783 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8784 TD->getIntPtrType(),
8785 "tmp"), CI);
8786 return new IntToPtrInst(P, CI.getType());
8787 }
8788
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008789 if (Instruction *I = commonCastTransforms(CI))
8790 return I;
8791
8792 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8793 if (!DestPointee->isSized()) return 0;
8794
8795 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8796 ConstantInt *Cst;
8797 Value *X;
8798 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8799 m_ConstantInt(Cst)))) {
8800 // If the source and destination operands have the same type, see if this
8801 // is a single-index GEP.
8802 if (X->getType() == CI.getType()) {
8803 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008804 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008805
8806 // Convert the constant to intptr type.
8807 APInt Offset = Cst->getValue();
8808 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8809
8810 // If Offset is evenly divisible by Size, we can do this xform.
8811 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8812 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008813 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008814 }
8815 }
8816 // TODO: Could handle other cases, e.g. where add is indexing into field of
8817 // struct etc.
8818 } else if (CI.getOperand(0)->hasOneUse() &&
8819 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8820 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8821 // "inttoptr+GEP" instead of "add+intptr".
8822
8823 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008824 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008825
8826 // Convert the constant to intptr type.
8827 APInt Offset = Cst->getValue();
8828 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8829
8830 // If Offset is evenly divisible by Size, we can do this xform.
8831 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8832 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8833
8834 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8835 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008836 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008837 }
8838 }
8839 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008840}
8841
Chris Lattnerd3e28342007-04-27 17:44:50 +00008842Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008843 // If the operands are integer typed then apply the integer transforms,
8844 // otherwise just apply the common ones.
8845 Value *Src = CI.getOperand(0);
8846 const Type *SrcTy = Src->getType();
8847 const Type *DestTy = CI.getType();
8848
Chris Lattner42a75512007-01-15 02:27:26 +00008849 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008850 if (Instruction *Result = commonIntCastTransforms(CI))
8851 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008852 } else if (isa<PointerType>(SrcTy)) {
8853 if (Instruction *I = commonPointerCastTransforms(CI))
8854 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008855 } else {
8856 if (Instruction *Result = commonCastTransforms(CI))
8857 return Result;
8858 }
8859
8860
8861 // Get rid of casts from one type to the same type. These are useless and can
8862 // be replaced by the operand.
8863 if (DestTy == Src->getType())
8864 return ReplaceInstUsesWith(CI, Src);
8865
Reid Spencer3da59db2006-11-27 01:05:10 +00008866 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008867 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8868 const Type *DstElTy = DstPTy->getElementType();
8869 const Type *SrcElTy = SrcPTy->getElementType();
8870
Nate Begeman83ad90a2008-03-31 00:22:16 +00008871 // If the address spaces don't match, don't eliminate the bitcast, which is
8872 // required for changing types.
8873 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8874 return 0;
8875
Chris Lattnerd3e28342007-04-27 17:44:50 +00008876 // If we are casting a malloc or alloca to a pointer to a type of the same
8877 // size, rewrite the allocation instruction to allocate the "right" type.
8878 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8879 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8880 return V;
8881
Chris Lattnerd717c182007-05-05 22:32:24 +00008882 // If the source and destination are pointers, and this cast is equivalent
8883 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008884 // This can enhance SROA and other transforms that want type-safe pointers.
8885 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8886 unsigned NumZeros = 0;
8887 while (SrcElTy != DstElTy &&
8888 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8889 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8890 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8891 ++NumZeros;
8892 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008893
Chris Lattnerd3e28342007-04-27 17:44:50 +00008894 // If we found a path from the src to dest, create the getelementptr now.
8895 if (SrcElTy == DstElTy) {
8896 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008897 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8898 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008899 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008900 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008901
Reid Spencer3da59db2006-11-27 01:05:10 +00008902 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8903 if (SVI->hasOneUse()) {
8904 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8905 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008906 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008907 cast<VectorType>(DestTy)->getNumElements() ==
8908 SVI->getType()->getNumElements() &&
8909 SVI->getType()->getNumElements() ==
8910 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008911 CastInst *Tmp;
8912 // If either of the operands is a cast from CI.getType(), then
8913 // evaluating the shuffle in the casted destination's type will allow
8914 // us to eliminate at least one cast.
8915 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8916 Tmp->getOperand(0)->getType() == DestTy) ||
8917 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8918 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008919 Value *LHS = InsertCastBefore(Instruction::BitCast,
8920 SVI->getOperand(0), DestTy, CI);
8921 Value *RHS = InsertCastBefore(Instruction::BitCast,
8922 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008923 // Return a new shuffle vector. Use the same element ID's, as we
8924 // know the vector types match #elts.
8925 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008926 }
8927 }
8928 }
8929 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008930 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008931}
8932
Chris Lattnere576b912004-04-09 23:46:01 +00008933/// GetSelectFoldableOperands - We want to turn code that looks like this:
8934/// %C = or %A, %B
8935/// %D = select %cond, %C, %A
8936/// into:
8937/// %C = select %cond, %B, 0
8938/// %D = or %A, %C
8939///
8940/// Assuming that the specified instruction is an operand to the select, return
8941/// a bitmask indicating which operands of this instruction are foldable if they
8942/// equal the other incoming value of the select.
8943///
8944static unsigned GetSelectFoldableOperands(Instruction *I) {
8945 switch (I->getOpcode()) {
8946 case Instruction::Add:
8947 case Instruction::Mul:
8948 case Instruction::And:
8949 case Instruction::Or:
8950 case Instruction::Xor:
8951 return 3; // Can fold through either operand.
8952 case Instruction::Sub: // Can only fold on the amount subtracted.
8953 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008954 case Instruction::LShr:
8955 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008956 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008957 default:
8958 return 0; // Cannot fold
8959 }
8960}
8961
8962/// GetSelectFoldableConstant - For the same transformation as the previous
8963/// function, return the identity constant that goes into the select.
8964static Constant *GetSelectFoldableConstant(Instruction *I) {
8965 switch (I->getOpcode()) {
8966 default: assert(0 && "This cannot happen!"); abort();
8967 case Instruction::Add:
8968 case Instruction::Sub:
8969 case Instruction::Or:
8970 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008971 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008972 case Instruction::LShr:
8973 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008974 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008975 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008976 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008977 case Instruction::Mul:
8978 return ConstantInt::get(I->getType(), 1);
8979 }
8980}
8981
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008982/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8983/// have the same opcode and only one use each. Try to simplify this.
8984Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8985 Instruction *FI) {
8986 if (TI->getNumOperands() == 1) {
8987 // If this is a non-volatile load or a cast from the same type,
8988 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008989 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008990 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8991 return 0;
8992 } else {
8993 return 0; // unknown unary op.
8994 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008995
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008996 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008997 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8998 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008999 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009000 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009001 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009002 }
9003
Reid Spencer832254e2007-02-02 02:16:23 +00009004 // Only handle binary operators here.
9005 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009006 return 0;
9007
9008 // Figure out if the operations have any operands in common.
9009 Value *MatchOp, *OtherOpT, *OtherOpF;
9010 bool MatchIsOpZero;
9011 if (TI->getOperand(0) == FI->getOperand(0)) {
9012 MatchOp = TI->getOperand(0);
9013 OtherOpT = TI->getOperand(1);
9014 OtherOpF = FI->getOperand(1);
9015 MatchIsOpZero = true;
9016 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9017 MatchOp = TI->getOperand(1);
9018 OtherOpT = TI->getOperand(0);
9019 OtherOpF = FI->getOperand(0);
9020 MatchIsOpZero = false;
9021 } else if (!TI->isCommutative()) {
9022 return 0;
9023 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9024 MatchOp = TI->getOperand(0);
9025 OtherOpT = TI->getOperand(1);
9026 OtherOpF = FI->getOperand(0);
9027 MatchIsOpZero = true;
9028 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9029 MatchOp = TI->getOperand(1);
9030 OtherOpT = TI->getOperand(0);
9031 OtherOpF = FI->getOperand(1);
9032 MatchIsOpZero = true;
9033 } else {
9034 return 0;
9035 }
9036
9037 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009038 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9039 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009040 InsertNewInstBefore(NewSI, SI);
9041
9042 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9043 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009044 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009045 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009046 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009047 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00009048 assert(0 && "Shouldn't get here");
9049 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009050}
9051
Evan Chengde621922009-03-31 20:42:45 +00009052static bool isSelect01(Constant *C1, Constant *C2) {
9053 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9054 if (!C1I)
9055 return false;
9056 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9057 if (!C2I)
9058 return false;
9059 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9060}
9061
9062/// FoldSelectIntoOp - Try fold the select into one of the operands to
9063/// facilitate further optimization.
9064Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9065 Value *FalseVal) {
9066 // See the comment above GetSelectFoldableOperands for a description of the
9067 // transformation we are doing here.
9068 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9069 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9070 !isa<Constant>(FalseVal)) {
9071 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9072 unsigned OpToFold = 0;
9073 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9074 OpToFold = 1;
9075 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9076 OpToFold = 2;
9077 }
9078
9079 if (OpToFold) {
9080 Constant *C = GetSelectFoldableConstant(TVI);
9081 Value *OOp = TVI->getOperand(2-OpToFold);
9082 // Avoid creating select between 2 constants unless it's selecting
9083 // between 0 and 1.
9084 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9085 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9086 InsertNewInstBefore(NewSel, SI);
9087 NewSel->takeName(TVI);
9088 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9089 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9090 assert(0 && "Unknown instruction!!");
9091 }
9092 }
9093 }
9094 }
9095 }
9096
9097 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9098 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9099 !isa<Constant>(TrueVal)) {
9100 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9101 unsigned OpToFold = 0;
9102 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9103 OpToFold = 1;
9104 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9105 OpToFold = 2;
9106 }
9107
9108 if (OpToFold) {
9109 Constant *C = GetSelectFoldableConstant(FVI);
9110 Value *OOp = FVI->getOperand(2-OpToFold);
9111 // Avoid creating select between 2 constants unless it's selecting
9112 // between 0 and 1.
9113 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9114 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9115 InsertNewInstBefore(NewSel, SI);
9116 NewSel->takeName(FVI);
9117 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9118 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9119 assert(0 && "Unknown instruction!!");
9120 }
9121 }
9122 }
9123 }
9124 }
9125
9126 return 0;
9127}
9128
Dan Gohman81b28ce2008-09-16 18:46:06 +00009129/// visitSelectInstWithICmp - Visit a SelectInst that has an
9130/// ICmpInst as its first operand.
9131///
9132Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9133 ICmpInst *ICI) {
9134 bool Changed = false;
9135 ICmpInst::Predicate Pred = ICI->getPredicate();
9136 Value *CmpLHS = ICI->getOperand(0);
9137 Value *CmpRHS = ICI->getOperand(1);
9138 Value *TrueVal = SI.getTrueValue();
9139 Value *FalseVal = SI.getFalseValue();
9140
9141 // Check cases where the comparison is with a constant that
9142 // can be adjusted to fit the min/max idiom. We may edit ICI in
9143 // place here, so make sure the select is the only user.
9144 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009145 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009146 switch (Pred) {
9147 default: break;
9148 case ICmpInst::ICMP_ULT:
9149 case ICmpInst::ICMP_SLT: {
9150 // X < MIN ? T : F --> F
9151 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9152 return ReplaceInstUsesWith(SI, FalseVal);
9153 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9154 Constant *AdjustedRHS = SubOne(CI);
9155 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9156 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9157 Pred = ICmpInst::getSwappedPredicate(Pred);
9158 CmpRHS = AdjustedRHS;
9159 std::swap(FalseVal, TrueVal);
9160 ICI->setPredicate(Pred);
9161 ICI->setOperand(1, CmpRHS);
9162 SI.setOperand(1, TrueVal);
9163 SI.setOperand(2, FalseVal);
9164 Changed = true;
9165 }
9166 break;
9167 }
9168 case ICmpInst::ICMP_UGT:
9169 case ICmpInst::ICMP_SGT: {
9170 // X > MAX ? T : F --> F
9171 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9172 return ReplaceInstUsesWith(SI, FalseVal);
9173 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9174 Constant *AdjustedRHS = AddOne(CI);
9175 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9176 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9177 Pred = ICmpInst::getSwappedPredicate(Pred);
9178 CmpRHS = AdjustedRHS;
9179 std::swap(FalseVal, TrueVal);
9180 ICI->setPredicate(Pred);
9181 ICI->setOperand(1, CmpRHS);
9182 SI.setOperand(1, TrueVal);
9183 SI.setOperand(2, FalseVal);
9184 Changed = true;
9185 }
9186 break;
9187 }
9188 }
9189
Dan Gohman1975d032008-10-30 20:40:10 +00009190 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9191 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009192 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner159c35b2009-01-05 23:53:12 +00009193 if (match(TrueVal, m_ConstantInt<-1>()) &&
9194 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009195 Pred = ICI->getPredicate();
Chris Lattner159c35b2009-01-05 23:53:12 +00009196 else if (match(TrueVal, m_ConstantInt<0>()) &&
9197 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009198 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9199
Dan Gohman1975d032008-10-30 20:40:10 +00009200 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9201 // If we are just checking for a icmp eq of a single bit and zext'ing it
9202 // to an integer, then shift the bit to the appropriate place and then
9203 // cast to integer to avoid the comparison.
9204 const APInt &Op1CV = CI->getValue();
9205
9206 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9207 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9208 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009209 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009210 Value *In = ICI->getOperand(0);
9211 Value *Sh = ConstantInt::get(In->getType(),
9212 In->getType()->getPrimitiveSizeInBits()-1);
9213 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9214 In->getName()+".lobit"),
9215 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009216 if (In->getType() != SI.getType())
9217 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009218 true/*SExt*/, "tmp", ICI);
9219
9220 if (Pred == ICmpInst::ICMP_SGT)
9221 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9222 In->getName()+".not"), *ICI);
9223
9224 return ReplaceInstUsesWith(SI, In);
9225 }
9226 }
9227 }
9228
Dan Gohman81b28ce2008-09-16 18:46:06 +00009229 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9230 // Transform (X == Y) ? X : Y -> Y
9231 if (Pred == ICmpInst::ICMP_EQ)
9232 return ReplaceInstUsesWith(SI, FalseVal);
9233 // Transform (X != Y) ? X : Y -> X
9234 if (Pred == ICmpInst::ICMP_NE)
9235 return ReplaceInstUsesWith(SI, TrueVal);
9236 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9237
9238 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9239 // Transform (X == Y) ? Y : X -> X
9240 if (Pred == ICmpInst::ICMP_EQ)
9241 return ReplaceInstUsesWith(SI, FalseVal);
9242 // Transform (X != Y) ? Y : X -> Y
9243 if (Pred == ICmpInst::ICMP_NE)
9244 return ReplaceInstUsesWith(SI, TrueVal);
9245 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9246 }
9247
9248 /// NOTE: if we wanted to, this is where to detect integer ABS
9249
9250 return Changed ? &SI : 0;
9251}
9252
Chris Lattner3d69f462004-03-12 05:52:32 +00009253Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009254 Value *CondVal = SI.getCondition();
9255 Value *TrueVal = SI.getTrueValue();
9256 Value *FalseVal = SI.getFalseValue();
9257
9258 // select true, X, Y -> X
9259 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009260 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009261 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009262
9263 // select C, X, X -> X
9264 if (TrueVal == FalseVal)
9265 return ReplaceInstUsesWith(SI, TrueVal);
9266
Chris Lattnere87597f2004-10-16 18:11:37 +00009267 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9268 return ReplaceInstUsesWith(SI, FalseVal);
9269 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9270 return ReplaceInstUsesWith(SI, TrueVal);
9271 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9272 if (isa<Constant>(TrueVal))
9273 return ReplaceInstUsesWith(SI, TrueVal);
9274 else
9275 return ReplaceInstUsesWith(SI, FalseVal);
9276 }
9277
Reid Spencer4fe16d62007-01-11 18:21:29 +00009278 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009279 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009280 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009281 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009282 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009283 } else {
9284 // Change: A = select B, false, C --> A = and !B, C
9285 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009286 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009287 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009288 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009289 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009290 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009291 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009292 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009293 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009294 } else {
9295 // Change: A = select B, C, true --> A = or !B, C
9296 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009297 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009298 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009299 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009300 }
9301 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009302
9303 // select a, b, a -> a&b
9304 // select a, a, b -> a|b
9305 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009306 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009307 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009308 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009309 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009310
Chris Lattner2eefe512004-04-09 19:05:30 +00009311 // Selecting between two integer constants?
9312 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9313 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009314 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009315 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009316 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009317 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009318 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009319 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009320 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009321 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009322 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009323 }
Chris Lattner457dd822004-06-09 07:59:58 +00009324
Reid Spencere4d87aa2006-12-23 06:05:41 +00009325 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009326
Reid Spencere4d87aa2006-12-23 06:05:41 +00009327 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00009328 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00009329 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00009330 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009331 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00009332 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00009333 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00009334 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00009335 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009336 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00009337 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00009338 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009339
9340 // Then cast to the appropriate width.
9341 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00009342 }
9343 }
9344
9345
9346 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009347 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009348 // non-constant value, eliminate this whole mess. This corresponds to
9349 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009350 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009351 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009352 cast<Constant>(IC->getOperand(1))->isNullValue())
9353 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9354 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009355 isa<ConstantInt>(ICA->getOperand(1)) &&
9356 (ICA->getOperand(1) == TrueValC ||
9357 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009358 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9359 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009360 // know whether we have a icmp_ne or icmp_eq and whether the
9361 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009362 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009363 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009364 Value *V = ICA;
9365 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009366 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009367 Instruction::Xor, V, ICA->getOperand(1)), SI);
9368 return ReplaceInstUsesWith(SI, V);
9369 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009370 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009371 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009372
9373 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009374 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9375 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009376 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009377 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9378 // This is not safe in general for floating point:
9379 // consider X== -0, Y== +0.
9380 // It becomes safe if either operand is a nonzero constant.
9381 ConstantFP *CFPt, *CFPf;
9382 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9383 !CFPt->getValueAPF().isZero()) ||
9384 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9385 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009386 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009387 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009388 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009389 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009390 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009391 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009392
Reid Spencere4d87aa2006-12-23 06:05:41 +00009393 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009394 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009395 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9396 // This is not safe in general for floating point:
9397 // consider X== -0, Y== +0.
9398 // It becomes safe if either operand is a nonzero constant.
9399 ConstantFP *CFPt, *CFPf;
9400 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9401 !CFPt->getValueAPF().isZero()) ||
9402 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9403 !CFPf->getValueAPF().isZero()))
9404 return ReplaceInstUsesWith(SI, FalseVal);
9405 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009406 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009407 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9408 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009409 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009410 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009411 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009412 }
9413
9414 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009415 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9416 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9417 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009418
Chris Lattner87875da2005-01-13 22:52:24 +00009419 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9420 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9421 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009422 Instruction *AddOp = 0, *SubOp = 0;
9423
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009424 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9425 if (TI->getOpcode() == FI->getOpcode())
9426 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9427 return IV;
9428
9429 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9430 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009431 if ((TI->getOpcode() == Instruction::Sub &&
9432 FI->getOpcode() == Instruction::Add) ||
9433 (TI->getOpcode() == Instruction::FSub &&
9434 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009435 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009436 } else if ((FI->getOpcode() == Instruction::Sub &&
9437 TI->getOpcode() == Instruction::Add) ||
9438 (FI->getOpcode() == Instruction::FSub &&
9439 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009440 AddOp = TI; SubOp = FI;
9441 }
9442
9443 if (AddOp) {
9444 Value *OtherAddOp = 0;
9445 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9446 OtherAddOp = AddOp->getOperand(1);
9447 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9448 OtherAddOp = AddOp->getOperand(0);
9449 }
9450
9451 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009452 // So at this point we know we have (Y -> OtherAddOp):
9453 // select C, (add X, Y), (sub X, Z)
9454 Value *NegVal; // Compute -Z
9455 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9456 NegVal = ConstantExpr::getNeg(C);
9457 } else {
9458 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009459 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009460 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009461
9462 Value *NewTrueOp = OtherAddOp;
9463 Value *NewFalseOp = NegVal;
9464 if (AddOp != TI)
9465 std::swap(NewTrueOp, NewFalseOp);
9466 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009467 SelectInst::Create(CondVal, NewTrueOp,
9468 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009469
9470 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009471 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009472 }
9473 }
9474 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009475
Chris Lattnere576b912004-04-09 23:46:01 +00009476 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009477 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009478 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9479 if (FoldI)
9480 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009481 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009482
9483 if (BinaryOperator::isNot(CondVal)) {
9484 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9485 SI.setOperand(1, FalseVal);
9486 SI.setOperand(2, TrueVal);
9487 return &SI;
9488 }
9489
Chris Lattner3d69f462004-03-12 05:52:32 +00009490 return 0;
9491}
9492
Dan Gohmaneee962e2008-04-10 18:43:06 +00009493/// EnforceKnownAlignment - If the specified pointer points to an object that
9494/// we control, modify the object's alignment to PrefAlign. This isn't
9495/// often possible though. If alignment is important, a more reliable approach
9496/// is to simply align all global variables and allocation instructions to
9497/// their preferred alignment from the beginning.
9498///
9499static unsigned EnforceKnownAlignment(Value *V,
9500 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009501
Dan Gohmaneee962e2008-04-10 18:43:06 +00009502 User *U = dyn_cast<User>(V);
9503 if (!U) return Align;
9504
9505 switch (getOpcode(U)) {
9506 default: break;
9507 case Instruction::BitCast:
9508 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9509 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009510 // If all indexes are zero, it is just the alignment of the base pointer.
9511 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009512 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009513 if (!isa<Constant>(*i) ||
9514 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009515 AllZeroOperands = false;
9516 break;
9517 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009518
9519 if (AllZeroOperands) {
9520 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009521 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009522 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009523 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009524 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009525 }
9526
9527 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9528 // If there is a large requested alignment and we can, bump up the alignment
9529 // of the global.
9530 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009531 if (GV->getAlignment() >= PrefAlign)
9532 Align = GV->getAlignment();
9533 else {
9534 GV->setAlignment(PrefAlign);
9535 Align = PrefAlign;
9536 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009537 }
9538 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9539 // If there is a requested alignment and if this is an alloca, round up. We
9540 // don't do this for malloc, because some systems can't respect the request.
9541 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009542 if (AI->getAlignment() >= PrefAlign)
9543 Align = AI->getAlignment();
9544 else {
9545 AI->setAlignment(PrefAlign);
9546 Align = PrefAlign;
9547 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009548 }
9549 }
9550
9551 return Align;
9552}
9553
9554/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9555/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9556/// and it is more than the alignment of the ultimate object, see if we can
9557/// increase the alignment of the ultimate object, making this check succeed.
9558unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9559 unsigned PrefAlign) {
9560 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9561 sizeof(PrefAlign) * CHAR_BIT;
9562 APInt Mask = APInt::getAllOnesValue(BitWidth);
9563 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9564 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9565 unsigned TrailZ = KnownZero.countTrailingOnes();
9566 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9567
9568 if (PrefAlign > Align)
9569 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9570
9571 // We don't need to make any adjustment.
9572 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009573}
9574
Chris Lattnerf497b022008-01-13 23:50:23 +00009575Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009576 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009577 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009578 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009579 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009580
9581 if (CopyAlign < MinAlign) {
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009582 MI->setAlignment(MinAlign);
Chris Lattnerf497b022008-01-13 23:50:23 +00009583 return MI;
9584 }
9585
9586 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9587 // load/store.
9588 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9589 if (MemOpLength == 0) return 0;
9590
Chris Lattner37ac6082008-01-14 00:28:35 +00009591 // Source and destination pointer types are always "i8*" for intrinsic. See
9592 // if the size is something we can handle with a single primitive load/store.
9593 // A single load+store correctly handles overlapping memory in the memmove
9594 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009595 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009596 if (Size == 0) return MI; // Delete this mem transfer.
9597
9598 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009599 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009600
Chris Lattner37ac6082008-01-14 00:28:35 +00009601 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009602 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009603
9604 // Memcpy forces the use of i8* for the source and destination. That means
9605 // that if you're using memcpy to move one double around, you'll get a cast
9606 // from double* to i8*. We'd much rather use a double load+store rather than
9607 // an i64 load+store, here because this improves the odds that the source or
9608 // dest address will be promotable. See if we can find a better type than the
9609 // integer datatype.
9610 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9611 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9612 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9613 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9614 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009615 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009616 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9617 if (STy->getNumElements() == 1)
9618 SrcETy = STy->getElementType(0);
9619 else
9620 break;
9621 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9622 if (ATy->getNumElements() == 1)
9623 SrcETy = ATy->getElementType();
9624 else
9625 break;
9626 } else
9627 break;
9628 }
9629
Dan Gohman8f8e2692008-05-23 01:52:21 +00009630 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009631 NewPtrTy = PointerType::getUnqual(SrcETy);
9632 }
9633 }
9634
9635
Chris Lattnerf497b022008-01-13 23:50:23 +00009636 // If the memcpy/memmove provides better alignment info than we can
9637 // infer, use it.
9638 SrcAlign = std::max(SrcAlign, CopyAlign);
9639 DstAlign = std::max(DstAlign, CopyAlign);
9640
9641 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9642 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009643 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9644 InsertNewInstBefore(L, *MI);
9645 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9646
9647 // Set the size of the copy to 0, it will be deleted on the next iteration.
9648 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9649 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009650}
Chris Lattner3d69f462004-03-12 05:52:32 +00009651
Chris Lattner69ea9d22008-04-30 06:39:11 +00009652Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9653 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009654 if (MI->getAlignment() < Alignment) {
9655 MI->setAlignment(Alignment);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009656 return MI;
9657 }
9658
9659 // Extract the length and alignment and fill if they are constant.
9660 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9661 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9662 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9663 return 0;
9664 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009665 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009666
9667 // If the length is zero, this is a no-op
9668 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9669
9670 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9671 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9672 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9673
9674 Value *Dest = MI->getDest();
9675 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9676
9677 // Alignment 0 is identity for alignment 1 for memset, but not store.
9678 if (Alignment == 0) Alignment = 1;
9679
9680 // Extract the fill value and store.
9681 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9682 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9683 Alignment), *MI);
9684
9685 // Set the size of the copy to 0, it will be deleted on the next iteration.
9686 MI->setLength(Constant::getNullValue(LenC->getType()));
9687 return MI;
9688 }
9689
9690 return 0;
9691}
9692
9693
Chris Lattner8b0ea312006-01-13 20:11:04 +00009694/// visitCallInst - CallInst simplification. This mostly only handles folding
9695/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9696/// the heavy lifting.
9697///
Chris Lattner9fe38862003-06-19 17:00:31 +00009698Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009699 // If the caller function is nounwind, mark the call as nounwind, even if the
9700 // callee isn't.
9701 if (CI.getParent()->getParent()->doesNotThrow() &&
9702 !CI.doesNotThrow()) {
9703 CI.setDoesNotThrow();
9704 return &CI;
9705 }
9706
9707
9708
Chris Lattner8b0ea312006-01-13 20:11:04 +00009709 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9710 if (!II) return visitCallSite(&CI);
9711
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009712 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9713 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009714 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009715 bool Changed = false;
9716
9717 // memmove/cpy/set of zero bytes is a noop.
9718 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9719 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9720
Chris Lattner35b9e482004-10-12 04:52:52 +00009721 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009722 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009723 // Replace the instruction with just byte operations. We would
9724 // transform other cases to loads/stores, but we don't know if
9725 // alignment is sufficient.
9726 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009727 }
9728
Chris Lattner35b9e482004-10-12 04:52:52 +00009729 // If we have a memmove and the source operation is a constant global,
9730 // then the source and dest pointers can't alias, so we can change this
9731 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009732 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009733 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9734 if (GVSrc->isConstant()) {
9735 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009736 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9737 const Type *Tys[1];
9738 Tys[0] = CI.getOperand(3)->getType();
9739 CI.setOperand(0,
9740 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009741 Changed = true;
9742 }
Chris Lattnera935db82008-05-28 05:30:41 +00009743
9744 // memmove(x,x,size) -> noop.
9745 if (MMI->getSource() == MMI->getDest())
9746 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009747 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009748
Chris Lattner95a959d2006-03-06 20:18:44 +00009749 // If we can determine a pointer alignment that is bigger than currently
9750 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009751 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009752 if (Instruction *I = SimplifyMemTransfer(MI))
9753 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009754 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9755 if (Instruction *I = SimplifyMemSet(MSI))
9756 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009757 }
9758
Chris Lattner8b0ea312006-01-13 20:11:04 +00009759 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009760 }
9761
9762 switch (II->getIntrinsicID()) {
9763 default: break;
9764 case Intrinsic::bswap:
9765 // bswap(bswap(x)) -> x
9766 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9767 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9768 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9769 break;
9770 case Intrinsic::ppc_altivec_lvx:
9771 case Intrinsic::ppc_altivec_lvxl:
9772 case Intrinsic::x86_sse_loadu_ps:
9773 case Intrinsic::x86_sse2_loadu_pd:
9774 case Intrinsic::x86_sse2_loadu_dq:
9775 // Turn PPC lvx -> load if the pointer is known aligned.
9776 // Turn X86 loadups -> load if the pointer is known aligned.
9777 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9778 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9779 PointerType::getUnqual(II->getType()),
9780 CI);
9781 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009782 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009783 break;
9784 case Intrinsic::ppc_altivec_stvx:
9785 case Intrinsic::ppc_altivec_stvxl:
9786 // Turn stvx -> store if the pointer is known aligned.
9787 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9788 const Type *OpPtrTy =
9789 PointerType::getUnqual(II->getOperand(1)->getType());
9790 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9791 return new StoreInst(II->getOperand(1), Ptr);
9792 }
9793 break;
9794 case Intrinsic::x86_sse_storeu_ps:
9795 case Intrinsic::x86_sse2_storeu_pd:
9796 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009797 // Turn X86 storeu -> store if the pointer is known aligned.
9798 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9799 const Type *OpPtrTy =
9800 PointerType::getUnqual(II->getOperand(2)->getType());
9801 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9802 return new StoreInst(II->getOperand(2), Ptr);
9803 }
9804 break;
9805
9806 case Intrinsic::x86_sse_cvttss2si: {
9807 // These intrinsics only demands the 0th element of its input vector. If
9808 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009809 unsigned VWidth =
9810 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9811 APInt DemandedElts(VWidth, 1);
9812 APInt UndefElts(VWidth, 0);
9813 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009814 UndefElts)) {
9815 II->setOperand(1, V);
9816 return II;
9817 }
9818 break;
9819 }
9820
9821 case Intrinsic::ppc_altivec_vperm:
9822 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9823 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9824 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009825
Chris Lattner0521e3c2008-06-18 04:33:20 +00009826 // Check that all of the elements are integer constants or undefs.
9827 bool AllEltsOk = true;
9828 for (unsigned i = 0; i != 16; ++i) {
9829 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9830 !isa<UndefValue>(Mask->getOperand(i))) {
9831 AllEltsOk = false;
9832 break;
9833 }
9834 }
9835
9836 if (AllEltsOk) {
9837 // Cast the input vectors to byte vectors.
9838 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9839 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9840 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009841
Chris Lattner0521e3c2008-06-18 04:33:20 +00009842 // Only extract each element once.
9843 Value *ExtractedElts[32];
9844 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9845
Chris Lattnere2ed0572006-04-06 19:19:17 +00009846 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009847 if (isa<UndefValue>(Mask->getOperand(i)))
9848 continue;
9849 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9850 Idx &= 31; // Match the hardware behavior.
9851
9852 if (ExtractedElts[Idx] == 0) {
9853 Instruction *Elt =
9854 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9855 InsertNewInstBefore(Elt, CI);
9856 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009857 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009858
Chris Lattner0521e3c2008-06-18 04:33:20 +00009859 // Insert this value into the result vector.
9860 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9861 i, "tmp");
9862 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009863 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009864 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009865 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009866 }
9867 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009868
Chris Lattner0521e3c2008-06-18 04:33:20 +00009869 case Intrinsic::stackrestore: {
9870 // If the save is right next to the restore, remove the restore. This can
9871 // happen when variable allocas are DCE'd.
9872 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9873 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9874 BasicBlock::iterator BI = SS;
9875 if (&*++BI == II)
9876 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009877 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009878 }
9879
9880 // Scan down this block to see if there is another stack restore in the
9881 // same block without an intervening call/alloca.
9882 BasicBlock::iterator BI = II;
9883 TerminatorInst *TI = II->getParent()->getTerminator();
9884 bool CannotRemove = false;
9885 for (++BI; &*BI != TI; ++BI) {
9886 if (isa<AllocaInst>(BI)) {
9887 CannotRemove = true;
9888 break;
9889 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009890 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9891 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9892 // If there is a stackrestore below this one, remove this one.
9893 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9894 return EraseInstFromFunction(CI);
9895 // Otherwise, ignore the intrinsic.
9896 } else {
9897 // If we found a non-intrinsic call, we can't remove the stack
9898 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009899 CannotRemove = true;
9900 break;
9901 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009902 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009903 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009904
9905 // If the stack restore is in a return/unwind block and if there are no
9906 // allocas or calls between the restore and the return, nuke the restore.
9907 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9908 return EraseInstFromFunction(CI);
9909 break;
9910 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009911 }
9912
Chris Lattner8b0ea312006-01-13 20:11:04 +00009913 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009914}
9915
9916// InvokeInst simplification
9917//
9918Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009919 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009920}
9921
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009922/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9923/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009924static bool isSafeToEliminateVarargsCast(const CallSite CS,
9925 const CastInst * const CI,
9926 const TargetData * const TD,
9927 const int ix) {
9928 if (!CI->isLosslessCast())
9929 return false;
9930
9931 // The size of ByVal arguments is derived from the type, so we
9932 // can't change to a type with a different size. If the size were
9933 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009934 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009935 return true;
9936
9937 const Type* SrcTy =
9938 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9939 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9940 if (!SrcTy->isSized() || !DstTy->isSized())
9941 return false;
Duncan Sands777d2302009-05-09 07:06:46 +00009942 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009943 return false;
9944 return true;
9945}
9946
Chris Lattnera44d8a22003-10-07 22:32:43 +00009947// visitCallSite - Improvements for call and invoke instructions.
9948//
9949Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009950 bool Changed = false;
9951
9952 // If the callee is a constexpr cast of a function, attempt to move the cast
9953 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009954 if (transformConstExprCastCall(CS)) return 0;
9955
Chris Lattner6c266db2003-10-07 22:54:13 +00009956 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009957
Chris Lattner08b22ec2005-05-13 07:09:09 +00009958 if (Function *CalleeF = dyn_cast<Function>(Callee))
9959 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9960 Instruction *OldCall = CS.getInstruction();
9961 // If the call and callee calling conventions don't match, this call must
9962 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009963 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009964 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9965 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009966 if (!OldCall->use_empty())
9967 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9968 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9969 return EraseInstFromFunction(*OldCall);
9970 return 0;
9971 }
9972
Chris Lattner17be6352004-10-18 02:59:09 +00009973 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9974 // This instruction is not reachable, just remove it. We insert a store to
9975 // undef so that we know that this code is not reachable, despite the fact
9976 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009977 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009978 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009979 CS.getInstruction());
9980
9981 if (!CS.getInstruction()->use_empty())
9982 CS.getInstruction()->
9983 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9984
9985 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9986 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009987 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9988 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009989 }
Chris Lattner17be6352004-10-18 02:59:09 +00009990 return EraseInstFromFunction(*CS.getInstruction());
9991 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009992
Duncan Sandscdb6d922007-09-17 10:26:40 +00009993 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9994 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9995 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9996 return transformCallThroughTrampoline(CS);
9997
Chris Lattner6c266db2003-10-07 22:54:13 +00009998 const PointerType *PTy = cast<PointerType>(Callee->getType());
9999 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10000 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010001 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010002 // See if we can optimize any arguments passed through the varargs area of
10003 // the call.
10004 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010005 E = CS.arg_end(); I != E; ++I, ++ix) {
10006 CastInst *CI = dyn_cast<CastInst>(*I);
10007 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10008 *I = CI->getOperand(0);
10009 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010010 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010011 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010012 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010013
Duncan Sandsf0c33542007-12-19 21:13:37 +000010014 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010015 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010016 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010017 Changed = true;
10018 }
10019
Chris Lattner6c266db2003-10-07 22:54:13 +000010020 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010021}
10022
Chris Lattner9fe38862003-06-19 17:00:31 +000010023// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10024// attempt to move the cast to the arguments of the call/invoke.
10025//
10026bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10027 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10028 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010029 if (CE->getOpcode() != Instruction::BitCast ||
10030 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010031 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010032 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010033 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010034 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010035
10036 // Okay, this is a cast from a function to a different type. Unless doing so
10037 // would cause a type conversion of one of our arguments, change this call to
10038 // be a direct call with arguments casted to the appropriate types.
10039 //
10040 const FunctionType *FT = Callee->getFunctionType();
10041 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010042 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010043
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010044 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010045 return false; // TODO: Handle multiple return values.
10046
Chris Lattnerf78616b2004-01-14 06:06:08 +000010047 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010048 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010049 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010050 // Conversion is ok if changing from one pointer type to another or from
10051 // a pointer to an integer of the same size.
10052 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +000010053 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010054 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010055
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010056 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010057 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010058 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010059 return false; // Cannot transform this return value.
10060
Chris Lattner58d74912008-03-12 17:45:29 +000010061 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010062 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010063 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010064 return false; // Attribute not compatible with transformed value.
10065 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010066
Chris Lattnerf78616b2004-01-14 06:06:08 +000010067 // If the callsite is an invoke instruction, and the return value is used by
10068 // a PHI node in a successor, we cannot change the return type of the call
10069 // because there is no place to put the cast instruction (without breaking
10070 // the critical edge). Bail out in this case.
10071 if (!Caller->use_empty())
10072 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10073 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10074 UI != E; ++UI)
10075 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10076 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010077 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010078 return false;
10079 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010080
10081 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10082 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010083
Chris Lattner9fe38862003-06-19 17:00:31 +000010084 CallSite::arg_iterator AI = CS.arg_begin();
10085 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10086 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010087 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010088
10089 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010090 return false; // Cannot transform this parameter value.
10091
Devang Patel19c87462008-09-26 22:53:05 +000010092 if (CallerPAL.getParamAttributes(i + 1)
10093 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010094 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010095
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010096 // Converting from one pointer type to another or between a pointer and an
10097 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010098 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010099 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10100 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010101 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010102 }
10103
10104 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010105 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010106 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010107
Chris Lattner58d74912008-03-12 17:45:29 +000010108 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10109 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010110 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010111 // won't be dropping them. Check that these extra arguments have attributes
10112 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010113 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10114 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010115 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010116 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010117 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010118 return false;
10119 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010120
Chris Lattner9fe38862003-06-19 17:00:31 +000010121 // Okay, we decided that this is a safe thing to do: go ahead and start
10122 // inserting cast instructions as necessary...
10123 std::vector<Value*> Args;
10124 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010125 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010126 attrVec.reserve(NumCommonArgs);
10127
10128 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010129 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010130
10131 // If the return value is not being used, the type may not be compatible
10132 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010133 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010134
10135 // Add the new return attributes.
10136 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010137 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010138
10139 AI = CS.arg_begin();
10140 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10141 const Type *ParamTy = FT->getParamType(i);
10142 if ((*AI)->getType() == ParamTy) {
10143 Args.push_back(*AI);
10144 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010145 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010146 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010147 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010148 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010149 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010150
10151 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010152 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010153 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010154 }
10155
10156 // If the function takes more arguments than the call was taking, add them
10157 // now...
10158 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10159 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10160
10161 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010162 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010163 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010164 cerr << "WARNING: While resolving call to function '"
10165 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010166 } else {
10167 // Add all of the arguments in their promoted form to the arg list...
10168 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10169 const Type *PTy = getPromotedType((*AI)->getType());
10170 if (PTy != (*AI)->getType()) {
10171 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010172 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10173 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010174 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010175 InsertNewInstBefore(Cast, *Caller);
10176 Args.push_back(Cast);
10177 } else {
10178 Args.push_back(*AI);
10179 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010180
Duncan Sandse1e520f2008-01-13 08:02:44 +000010181 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010182 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010183 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010184 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010185 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010186 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010187
Devang Patel19c87462008-09-26 22:53:05 +000010188 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10189 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10190
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010191 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010192 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010193
Devang Patel05988662008-09-25 21:00:45 +000010194 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010195
Chris Lattner9fe38862003-06-19 17:00:31 +000010196 Instruction *NC;
10197 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010198 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010199 Args.begin(), Args.end(),
10200 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010201 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010202 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010203 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010204 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10205 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010206 CallInst *CI = cast<CallInst>(Caller);
10207 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010208 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010209 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010210 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010211 }
10212
Chris Lattner6934a042007-02-11 01:23:03 +000010213 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010214 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010215 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010216 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010217 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010218 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010219 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010220
10221 // If this is an invoke instruction, we should insert it after the first
10222 // non-phi, instruction in the normal successor block.
10223 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010224 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010225 InsertNewInstBefore(NC, *I);
10226 } else {
10227 // Otherwise, it's a call, just insert cast right after the call instr
10228 InsertNewInstBefore(NC, *Caller);
10229 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010230 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010231 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +000010232 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010233 }
10234 }
10235
10236 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10237 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010238 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010239 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010240 return true;
10241}
10242
Duncan Sandscdb6d922007-09-17 10:26:40 +000010243// transformCallThroughTrampoline - Turn a call to a function created by the
10244// init_trampoline intrinsic into a direct call to the underlying function.
10245//
10246Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10247 Value *Callee = CS.getCalledValue();
10248 const PointerType *PTy = cast<PointerType>(Callee->getType());
10249 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010250 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010251
10252 // If the call already has the 'nest' attribute somewhere then give up -
10253 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010254 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010255 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010256
10257 IntrinsicInst *Tramp =
10258 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10259
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010260 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010261 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10262 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10263
Devang Patel05988662008-09-25 21:00:45 +000010264 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010265 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010266 unsigned NestIdx = 1;
10267 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010268 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010269
10270 // Look for a parameter marked with the 'nest' attribute.
10271 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10272 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010273 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010274 // Record the parameter type and any other attributes.
10275 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010276 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010277 break;
10278 }
10279
10280 if (NestTy) {
10281 Instruction *Caller = CS.getInstruction();
10282 std::vector<Value*> NewArgs;
10283 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10284
Devang Patel05988662008-09-25 21:00:45 +000010285 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010286 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010287
Duncan Sandscdb6d922007-09-17 10:26:40 +000010288 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010289 // mean appending it. Likewise for attributes.
10290
Devang Patel19c87462008-09-26 22:53:05 +000010291 // Add any result attributes.
10292 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010293 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010294
Duncan Sandscdb6d922007-09-17 10:26:40 +000010295 {
10296 unsigned Idx = 1;
10297 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10298 do {
10299 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010300 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010301 Value *NestVal = Tramp->getOperand(3);
10302 if (NestVal->getType() != NestTy)
10303 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10304 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010305 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010306 }
10307
10308 if (I == E)
10309 break;
10310
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010311 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010312 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010313 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010314 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010315 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010316
10317 ++Idx, ++I;
10318 } while (1);
10319 }
10320
Devang Patel19c87462008-09-26 22:53:05 +000010321 // Add any function attributes.
10322 if (Attributes Attr = Attrs.getFnAttributes())
10323 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10324
Duncan Sandscdb6d922007-09-17 10:26:40 +000010325 // The trampoline may have been bitcast to a bogus type (FTy).
10326 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010327 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010328
Duncan Sandscdb6d922007-09-17 10:26:40 +000010329 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010330 NewTypes.reserve(FTy->getNumParams()+1);
10331
Duncan Sandscdb6d922007-09-17 10:26:40 +000010332 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010333 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010334 {
10335 unsigned Idx = 1;
10336 FunctionType::param_iterator I = FTy->param_begin(),
10337 E = FTy->param_end();
10338
10339 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010340 if (Idx == NestIdx)
10341 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010342 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010343
10344 if (I == E)
10345 break;
10346
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010347 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010348 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010349
10350 ++Idx, ++I;
10351 } while (1);
10352 }
10353
10354 // Replace the trampoline call with a direct call. Let the generic
10355 // code sort out any function type mismatches.
10356 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +000010357 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010358 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10359 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010360 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010361
10362 Instruction *NewCaller;
10363 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010364 NewCaller = InvokeInst::Create(NewCallee,
10365 II->getNormalDest(), II->getUnwindDest(),
10366 NewArgs.begin(), NewArgs.end(),
10367 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010368 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010369 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010370 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010371 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10372 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010373 if (cast<CallInst>(Caller)->isTailCall())
10374 cast<CallInst>(NewCaller)->setTailCall();
10375 cast<CallInst>(NewCaller)->
10376 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010377 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010378 }
10379 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10380 Caller->replaceAllUsesWith(NewCaller);
10381 Caller->eraseFromParent();
10382 RemoveFromWorkList(Caller);
10383 return 0;
10384 }
10385 }
10386
10387 // Replace the trampoline call with a direct call. Since there is no 'nest'
10388 // parameter, there is no need to adjust the argument list. Let the generic
10389 // code sort out any function type mismatches.
10390 Constant *NewCallee =
10391 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10392 CS.setCalledFunction(NewCallee);
10393 return CS.getInstruction();
10394}
10395
Chris Lattner7da52b22006-11-01 04:51:18 +000010396/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10397/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10398/// and a single binop.
10399Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10400 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010401 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010402 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010403 Value *LHSVal = FirstInst->getOperand(0);
10404 Value *RHSVal = FirstInst->getOperand(1);
10405
10406 const Type *LHSType = LHSVal->getType();
10407 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010408
10409 // Scan to see if all operands are the same opcode, all have one use, and all
10410 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010411 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010412 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010413 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010414 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010415 // types or GEP's with different index types.
10416 I->getOperand(0)->getType() != LHSType ||
10417 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010418 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010419
10420 // If they are CmpInst instructions, check their predicates
10421 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10422 if (cast<CmpInst>(I)->getPredicate() !=
10423 cast<CmpInst>(FirstInst)->getPredicate())
10424 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010425
10426 // Keep track of which operand needs a phi node.
10427 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10428 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010429 }
10430
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010431 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010432
Chris Lattner7da52b22006-11-01 04:51:18 +000010433 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010434 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010435 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010436 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010437 NewLHS = PHINode::Create(LHSType,
10438 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010439 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10440 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010441 InsertNewInstBefore(NewLHS, PN);
10442 LHSVal = NewLHS;
10443 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010444
10445 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010446 NewRHS = PHINode::Create(RHSType,
10447 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010448 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10449 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010450 InsertNewInstBefore(NewRHS, PN);
10451 RHSVal = NewRHS;
10452 }
10453
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010454 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010455 if (NewLHS || NewRHS) {
10456 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10457 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10458 if (NewLHS) {
10459 Value *NewInLHS = InInst->getOperand(0);
10460 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10461 }
10462 if (NewRHS) {
10463 Value *NewInRHS = InInst->getOperand(1);
10464 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10465 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010466 }
10467 }
10468
Chris Lattner7da52b22006-11-01 04:51:18 +000010469 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010470 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010471 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10472 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10473 RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010474}
10475
Chris Lattner05f18922008-12-01 02:34:36 +000010476Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10477 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10478
10479 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10480 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010481 // This is true if all GEP bases are allocas and if all indices into them are
10482 // constants.
10483 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010484
10485 // Scan to see if all operands are the same opcode, all have one use, and all
10486 // kill their operands (i.e. the operands have one use).
10487 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10488 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10489 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10490 GEP->getNumOperands() != FirstInst->getNumOperands())
10491 return 0;
10492
Chris Lattner36d3e322009-02-21 00:46:50 +000010493 // Keep track of whether or not all GEPs are of alloca pointers.
10494 if (AllBasePointersAreAllocas &&
10495 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10496 !GEP->hasAllConstantIndices()))
10497 AllBasePointersAreAllocas = false;
10498
Chris Lattner05f18922008-12-01 02:34:36 +000010499 // Compare the operand lists.
10500 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10501 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10502 continue;
10503
10504 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10505 // if one of the PHIs has a constant for the index. The index may be
10506 // substantially cheaper to compute for the constants, so making it a
10507 // variable index could pessimize the path. This also handles the case
10508 // for struct indices, which must always be constant.
10509 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10510 isa<ConstantInt>(GEP->getOperand(op)))
10511 return 0;
10512
10513 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10514 return 0;
10515 FixedOperands[op] = 0; // Needs a PHI.
10516 }
10517 }
10518
Chris Lattner36d3e322009-02-21 00:46:50 +000010519 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010520 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010521 // offset calculation, but all the predecessors will have to materialize the
10522 // stack address into a register anyway. We'd actually rather *clone* the
10523 // load up into the predecessors so that we have a load of a gep of an alloca,
10524 // which can usually all be folded into the load.
10525 if (AllBasePointersAreAllocas)
10526 return 0;
10527
Chris Lattner05f18922008-12-01 02:34:36 +000010528 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10529 // that is variable.
10530 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10531
10532 bool HasAnyPHIs = false;
10533 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10534 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10535 Value *FirstOp = FirstInst->getOperand(i);
10536 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10537 FirstOp->getName()+".pn");
10538 InsertNewInstBefore(NewPN, PN);
10539
10540 NewPN->reserveOperandSpace(e);
10541 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10542 OperandPhis[i] = NewPN;
10543 FixedOperands[i] = NewPN;
10544 HasAnyPHIs = true;
10545 }
10546
10547
10548 // Add all operands to the new PHIs.
10549 if (HasAnyPHIs) {
10550 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10551 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10552 BasicBlock *InBB = PN.getIncomingBlock(i);
10553
10554 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10555 if (PHINode *OpPhi = OperandPhis[op])
10556 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10557 }
10558 }
10559
10560 Value *Base = FixedOperands[0];
10561 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10562 FixedOperands.end());
10563}
10564
10565
Chris Lattner21550882009-02-23 05:56:17 +000010566/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10567/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010568/// obvious the value of the load is not changed from the point of the load to
10569/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010570///
10571/// Finally, it is safe, but not profitable, to sink a load targetting a
10572/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10573/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010574static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010575 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10576
10577 for (++BBI; BBI != E; ++BBI)
10578 if (BBI->mayWriteToMemory())
10579 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010580
10581 // Check for non-address taken alloca. If not address-taken already, it isn't
10582 // profitable to do this xform.
10583 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10584 bool isAddressTaken = false;
10585 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10586 UI != E; ++UI) {
10587 if (isa<LoadInst>(UI)) continue;
10588 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10589 // If storing TO the alloca, then the address isn't taken.
10590 if (SI->getOperand(1) == AI) continue;
10591 }
10592 isAddressTaken = true;
10593 break;
10594 }
10595
Chris Lattner36d3e322009-02-21 00:46:50 +000010596 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010597 return false;
10598 }
10599
Chris Lattner36d3e322009-02-21 00:46:50 +000010600 // If this load is a load from a GEP with a constant offset from an alloca,
10601 // then we don't want to sink it. In its present form, it will be
10602 // load [constant stack offset]. Sinking it will cause us to have to
10603 // materialize the stack addresses in each predecessor in a register only to
10604 // do a shared load from register in the successor.
10605 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10606 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10607 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10608 return false;
10609
Chris Lattner76c73142006-11-01 07:13:54 +000010610 return true;
10611}
10612
Chris Lattner9fe38862003-06-19 17:00:31 +000010613
Chris Lattnerbac32862004-11-14 19:13:23 +000010614// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10615// operator and they all are only used by the PHI, PHI together their
10616// inputs, and do the operation once, to the result of the PHI.
10617Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10618 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10619
10620 // Scan the instruction, looking for input operations that can be folded away.
10621 // If all input operands to the phi are the same instruction (e.g. a cast from
10622 // the same type or "+42") we can pull the operation through the PHI, reducing
10623 // code size and simplifying code.
10624 Constant *ConstantOp = 0;
10625 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010626 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010627 if (isa<CastInst>(FirstInst)) {
10628 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010629 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010630 // Can fold binop, compare or shift here if the RHS is a constant,
10631 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010632 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010633 if (ConstantOp == 0)
10634 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010635 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10636 isVolatile = LI->isVolatile();
10637 // We can't sink the load if the loaded value could be modified between the
10638 // load and the PHI.
10639 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010640 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010641 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010642
10643 // If the PHI is of volatile loads and the load block has multiple
10644 // successors, sinking it would remove a load of the volatile value from
10645 // the path through the other successor.
10646 if (isVolatile &&
10647 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10648 return 0;
10649
Chris Lattner9c080502006-11-01 07:43:41 +000010650 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010651 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010652 } else {
10653 return 0; // Cannot fold this operation.
10654 }
10655
10656 // Check to see if all arguments are the same operation.
10657 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10658 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10659 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010660 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010661 return 0;
10662 if (CastSrcTy) {
10663 if (I->getOperand(0)->getType() != CastSrcTy)
10664 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010665 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010666 // We can't sink the load if the loaded value could be modified between
10667 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010668 if (LI->isVolatile() != isVolatile ||
10669 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010670 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010671 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010672
Chris Lattner71042962008-07-08 17:18:32 +000010673 // If the PHI is of volatile loads and the load block has multiple
10674 // successors, sinking it would remove a load of the volatile value from
10675 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010676 if (isVolatile &&
10677 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10678 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010679
Chris Lattnerbac32862004-11-14 19:13:23 +000010680 } else if (I->getOperand(1) != ConstantOp) {
10681 return 0;
10682 }
10683 }
10684
10685 // Okay, they are all the same operation. Create a new PHI node of the
10686 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010687 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10688 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010689 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010690
10691 Value *InVal = FirstInst->getOperand(0);
10692 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010693
10694 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010695 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10696 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10697 if (NewInVal != InVal)
10698 InVal = 0;
10699 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10700 }
10701
10702 Value *PhiVal;
10703 if (InVal) {
10704 // The new PHI unions all of the same values together. This is really
10705 // common, so we handle it intelligently here for compile-time speed.
10706 PhiVal = InVal;
10707 delete NewPN;
10708 } else {
10709 InsertNewInstBefore(NewPN, PN);
10710 PhiVal = NewPN;
10711 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010712
Chris Lattnerbac32862004-11-14 19:13:23 +000010713 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010714 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010715 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010716 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010717 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010718 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010719 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010720 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010721 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10722
10723 // If this was a volatile load that we are merging, make sure to loop through
10724 // and mark all the input loads as non-volatile. If we don't do this, we will
10725 // insert a new volatile load and the old ones will not be deletable.
10726 if (isVolatile)
10727 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10728 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10729
10730 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010731}
Chris Lattnera1be5662002-05-02 17:06:02 +000010732
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010733/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10734/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010735static bool DeadPHICycle(PHINode *PN,
10736 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010737 if (PN->use_empty()) return true;
10738 if (!PN->hasOneUse()) return false;
10739
10740 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010741 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010742 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010743
10744 // Don't scan crazily complex things.
10745 if (PotentiallyDeadPHIs.size() == 16)
10746 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010747
10748 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10749 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010750
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010751 return false;
10752}
10753
Chris Lattnercf5008a2007-11-06 21:52:06 +000010754/// PHIsEqualValue - Return true if this phi node is always equal to
10755/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10756/// z = some value; x = phi (y, z); y = phi (x, z)
10757static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10758 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10759 // See if we already saw this PHI node.
10760 if (!ValueEqualPHIs.insert(PN))
10761 return true;
10762
10763 // Don't scan crazily complex things.
10764 if (ValueEqualPHIs.size() == 16)
10765 return false;
10766
10767 // Scan the operands to see if they are either phi nodes or are equal to
10768 // the value.
10769 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10770 Value *Op = PN->getIncomingValue(i);
10771 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10772 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10773 return false;
10774 } else if (Op != NonPhiInVal)
10775 return false;
10776 }
10777
10778 return true;
10779}
10780
10781
Chris Lattner473945d2002-05-06 18:06:38 +000010782// PHINode simplification
10783//
Chris Lattner7e708292002-06-25 16:13:24 +000010784Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010785 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010786 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010787
Owen Anderson7e057142006-07-10 22:03:18 +000010788 if (Value *V = PN.hasConstantValue())
10789 return ReplaceInstUsesWith(PN, V);
10790
Owen Anderson7e057142006-07-10 22:03:18 +000010791 // If all PHI operands are the same operation, pull them through the PHI,
10792 // reducing code size.
10793 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010794 isa<Instruction>(PN.getIncomingValue(1)) &&
10795 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10796 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10797 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10798 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010799 PN.getIncomingValue(0)->hasOneUse())
10800 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10801 return Result;
10802
10803 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10804 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10805 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010806 if (PN.hasOneUse()) {
10807 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10808 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010809 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010810 PotentiallyDeadPHIs.insert(&PN);
10811 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10812 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10813 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010814
10815 // If this phi has a single use, and if that use just computes a value for
10816 // the next iteration of a loop, delete the phi. This occurs with unused
10817 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10818 // common case here is good because the only other things that catch this
10819 // are induction variable analysis (sometimes) and ADCE, which is only run
10820 // late.
10821 if (PHIUser->hasOneUse() &&
10822 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10823 PHIUser->use_back() == &PN) {
10824 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10825 }
10826 }
Owen Anderson7e057142006-07-10 22:03:18 +000010827
Chris Lattnercf5008a2007-11-06 21:52:06 +000010828 // We sometimes end up with phi cycles that non-obviously end up being the
10829 // same value, for example:
10830 // z = some value; x = phi (y, z); y = phi (x, z)
10831 // where the phi nodes don't necessarily need to be in the same block. Do a
10832 // quick check to see if the PHI node only contains a single non-phi value, if
10833 // so, scan to see if the phi cycle is actually equal to that value.
10834 {
10835 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10836 // Scan for the first non-phi operand.
10837 while (InValNo != NumOperandVals &&
10838 isa<PHINode>(PN.getIncomingValue(InValNo)))
10839 ++InValNo;
10840
10841 if (InValNo != NumOperandVals) {
10842 Value *NonPhiInVal = PN.getOperand(InValNo);
10843
10844 // Scan the rest of the operands to see if there are any conflicts, if so
10845 // there is no need to recursively scan other phis.
10846 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10847 Value *OpVal = PN.getIncomingValue(InValNo);
10848 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10849 break;
10850 }
10851
10852 // If we scanned over all operands, then we have one unique value plus
10853 // phi values. Scan PHI nodes to see if they all merge in each other or
10854 // the value.
10855 if (InValNo == NumOperandVals) {
10856 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10857 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10858 return ReplaceInstUsesWith(PN, NonPhiInVal);
10859 }
10860 }
10861 }
Chris Lattner60921c92003-12-19 05:58:40 +000010862 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010863}
10864
Reid Spencer17212df2006-12-12 09:18:51 +000010865static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10866 Instruction *InsertPoint,
10867 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010868 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10869 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010870 // We must cast correctly to the pointer type. Ensure that we
10871 // sign extend the integer value if it is smaller as this is
10872 // used for address computation.
10873 Instruction::CastOps opcode =
10874 (VTySize < PtrSize ? Instruction::SExt :
10875 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10876 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010877}
10878
Chris Lattnera1be5662002-05-02 17:06:02 +000010879
Chris Lattner7e708292002-06-25 16:13:24 +000010880Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010881 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010882 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010883 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010884 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010885 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010886
Chris Lattnere87597f2004-10-16 18:11:37 +000010887 if (isa<UndefValue>(GEP.getOperand(0)))
10888 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10889
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010890 bool HasZeroPointerIndex = false;
10891 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10892 HasZeroPointerIndex = C->isNullValue();
10893
10894 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010895 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010896
Chris Lattner28977af2004-04-05 01:30:19 +000010897 // Eliminate unneeded casts for indices.
10898 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010899
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010900 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010901 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10902 i != e; ++i, ++GTI) {
Sanjiv Gupta7787d4a2009-04-24 02:37:54 +000010903 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010904 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010905 if (CI->getOpcode() == Instruction::ZExt ||
10906 CI->getOpcode() == Instruction::SExt) {
10907 const Type *SrcTy = CI->getOperand(0)->getType();
10908 // We can eliminate a cast from i32 to i64 iff the target
10909 // is a 32-bit pointer target.
10910 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10911 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010912 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010913 }
10914 }
10915 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010916 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010917 // to what we need. If narrower, sign-extend it to what we need.
10918 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010919 // insert it. This explicit cast can make subsequent optimizations more
10920 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010921 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010922 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010923 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010924 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010925 MadeChange = true;
10926 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010927 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10928 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010929 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010930 MadeChange = true;
10931 }
Dan Gohman4f833d42008-09-11 23:06:38 +000010932 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10933 if (Constant *C = dyn_cast<Constant>(Op)) {
10934 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10935 MadeChange = true;
10936 } else {
10937 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10938 GEP);
10939 *i = Op;
10940 MadeChange = true;
10941 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010942 }
Chris Lattner28977af2004-04-05 01:30:19 +000010943 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010944 }
Chris Lattner28977af2004-04-05 01:30:19 +000010945 if (MadeChange) return &GEP;
10946
Chris Lattner90ac28c2002-08-02 19:29:35 +000010947 // Combine Indices - If the source pointer to this getelementptr instruction
10948 // is a getelementptr instruction, combine the indices of the two
10949 // getelementptr instructions into a single instruction.
10950 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010951 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010952 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010953 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010954
10955 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010956 // Note that if our source is a gep chain itself that we wait for that
10957 // chain to be resolved before we perform this transformation. This
10958 // avoids us creating a TON of code in some cases.
10959 //
10960 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10961 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10962 return 0; // Wait until our source is folded to completion.
10963
Chris Lattner72588fc2007-02-15 22:48:32 +000010964 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010965
10966 // Find out whether the last index in the source GEP is a sequential idx.
10967 bool EndsWithSequential = false;
10968 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10969 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010970 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010971
Chris Lattner90ac28c2002-08-02 19:29:35 +000010972 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010973 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010974 // Replace: gep (gep %P, long B), long A, ...
10975 // With: T = long A+B; gep %P, T, ...
10976 //
Chris Lattner620ce142004-05-07 22:09:22 +000010977 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010978 if (SO1 == Constant::getNullValue(SO1->getType())) {
10979 Sum = GO1;
10980 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10981 Sum = SO1;
10982 } else {
10983 // If they aren't the same type, convert both to an integer of the
10984 // target's pointer size.
10985 if (SO1->getType() != GO1->getType()) {
10986 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010987 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010988 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010989 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010990 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010991 unsigned PS = TD->getPointerSizeInBits();
10992 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010993 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010994 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010995
Duncan Sands514ab342007-11-01 20:53:16 +000010996 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010997 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010998 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010999 } else {
11000 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011001 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11002 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011003 }
11004 }
11005 }
Chris Lattner620ce142004-05-07 22:09:22 +000011006 if (isa<Constant>(SO1) && isa<Constant>(GO1))
11007 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
11008 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011009 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011010 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011011 }
Chris Lattner28977af2004-04-05 01:30:19 +000011012 }
Chris Lattner620ce142004-05-07 22:09:22 +000011013
11014 // Recycle the GEP we already have if possible.
11015 if (SrcGEPOperands.size() == 2) {
11016 GEP.setOperand(0, SrcGEPOperands[0]);
11017 GEP.setOperand(1, Sum);
11018 return &GEP;
11019 } else {
11020 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11021 SrcGEPOperands.end()-1);
11022 Indices.push_back(Sum);
11023 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11024 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011025 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011026 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011027 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011028 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011029 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11030 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011031 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11032 }
11033
11034 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011035 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11036 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011037
Chris Lattner620ce142004-05-07 22:09:22 +000011038 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011039 // GEP of global variable. If all of the indices for this GEP are
11040 // constants, we can promote this to a constexpr instead of an instruction.
11041
11042 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011043 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011044 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11045 for (; I != E && isa<Constant>(*I); ++I)
11046 Indices.push_back(cast<Constant>(*I));
11047
11048 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011049 Constant *CE = ConstantExpr::getGetElementPtr(GV,
11050 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011051
11052 // Replace all uses of the GEP with the new constexpr...
11053 return ReplaceInstUsesWith(GEP, CE);
11054 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011055 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011056 if (!isa<PointerType>(X->getType())) {
11057 // Not interesting. Source pointer must be a cast from pointer.
11058 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011059 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11060 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011061 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011062 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11063 // into : GEP i8* X, ...
11064 //
Chris Lattnereed48272005-09-13 00:40:14 +000011065 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011066 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11067 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011068 if (const ArrayType *CATy =
11069 dyn_cast<ArrayType>(CPTy->getElementType())) {
11070 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11071 if (CATy->getElementType() == XTy->getElementType()) {
11072 // -> GEP i8* X, ...
11073 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11074 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11075 GEP.getName());
11076 } else if (const ArrayType *XATy =
11077 dyn_cast<ArrayType>(XTy->getElementType())) {
11078 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011079 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011080 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011081 // At this point, we know that the cast source type is a pointer
11082 // to an array of the same type as the destination pointer
11083 // array. Because the array type is never stepped over (there
11084 // is a leading zero) we can fold the cast into this GEP.
11085 GEP.setOperand(0, X);
11086 return &GEP;
11087 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011088 }
11089 }
Chris Lattnereed48272005-09-13 00:40:14 +000011090 } else if (GEP.getNumOperands() == 2) {
11091 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011092 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11093 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011094 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11095 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11096 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011097 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11098 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011099 Value *Idx[2];
11100 Idx[0] = Constant::getNullValue(Type::Int32Ty);
11101 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011102 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011103 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011104 // V and GEP are both pointer types --> BitCast
11105 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011106 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011107
11108 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011109 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011110 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011111 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011112
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011113 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011114 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011115 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011116
11117 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11118 // allow either a mul, shift, or constant here.
11119 Value *NewIdx = 0;
11120 ConstantInt *Scale = 0;
11121 if (ArrayEltSize == 1) {
11122 NewIdx = GEP.getOperand(1);
11123 Scale = ConstantInt::get(NewIdx->getType(), 1);
11124 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000011125 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011126 Scale = CI;
11127 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11128 if (Inst->getOpcode() == Instruction::Shl &&
11129 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011130 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11131 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11132 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011133 NewIdx = Inst->getOperand(0);
11134 } else if (Inst->getOpcode() == Instruction::Mul &&
11135 isa<ConstantInt>(Inst->getOperand(1))) {
11136 Scale = cast<ConstantInt>(Inst->getOperand(1));
11137 NewIdx = Inst->getOperand(0);
11138 }
11139 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011140
Chris Lattner7835cdd2005-09-13 18:36:04 +000011141 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011142 // out, perform the transformation. Note, we don't know whether Scale is
11143 // signed or not. We'll use unsigned version of division/modulo
11144 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011145 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011146 Scale->getZExtValue() % ArrayEltSize == 0) {
11147 Scale = ConstantInt::get(Scale->getType(),
11148 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011149 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000011150 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011151 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011152 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011153 NewIdx = InsertNewInstBefore(Sc, GEP);
11154 }
11155
11156 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011157 Value *Idx[2];
11158 Idx[0] = Constant::getNullValue(Type::Int32Ty);
11159 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011160 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011161 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011162 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11163 // The NewGEP must be pointer typed, so must the old one -> BitCast
11164 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011165 }
11166 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011167 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011168 }
Chris Lattner58407792009-01-09 04:53:57 +000011169
Chris Lattner46cd5a12009-01-09 05:44:56 +000011170 /// See if we can simplify:
11171 /// X = bitcast A to B*
11172 /// Y = gep X, <...constant indices...>
11173 /// into a gep of the original struct. This is important for SROA and alias
11174 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011175 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011176 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11177 // Determine how much the GEP moves the pointer. We are guaranteed to get
11178 // a constant back from EmitGEPOffset.
11179 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11180 int64_t Offset = OffsetV->getSExtValue();
11181
11182 // If this GEP instruction doesn't move the pointer, just replace the GEP
11183 // with a bitcast of the real input to the dest type.
11184 if (Offset == 0) {
11185 // If the bitcast is of an allocation, and the allocation will be
11186 // converted to match the type of the cast, don't touch this.
11187 if (isa<AllocationInst>(BCI->getOperand(0))) {
11188 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11189 if (Instruction *I = visitBitCast(*BCI)) {
11190 if (I != BCI) {
11191 I->takeName(BCI);
11192 BCI->getParent()->getInstList().insert(BCI, I);
11193 ReplaceInstUsesWith(*BCI, I);
11194 }
11195 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011196 }
Chris Lattner58407792009-01-09 04:53:57 +000011197 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011198 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011199 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011200
11201 // Otherwise, if the offset is non-zero, we need to find out if there is a
11202 // field at Offset in 'A's type. If so, we can pull the cast through the
11203 // GEP.
11204 SmallVector<Value*, 8> NewIndices;
11205 const Type *InTy =
11206 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11207 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11208 Instruction *NGEP =
11209 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11210 NewIndices.end());
11211 if (NGEP->getType() == GEP.getType()) return NGEP;
11212 InsertNewInstBefore(NGEP, GEP);
11213 NGEP->takeName(&GEP);
11214 return new BitCastInst(NGEP, GEP.getType());
11215 }
Chris Lattner58407792009-01-09 04:53:57 +000011216 }
11217 }
11218
Chris Lattner8a2a3112001-12-14 16:52:21 +000011219 return 0;
11220}
11221
Chris Lattner0864acf2002-11-04 16:18:53 +000011222Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11223 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011224 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011225 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11226 const Type *NewTy =
11227 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011228 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011229
11230 // Create and insert the replacement instruction...
11231 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000011232 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011233 else {
11234 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000011235 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011236 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011237
11238 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011239
Chris Lattner0864acf2002-11-04 16:18:53 +000011240 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011241 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011242 //
11243 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011244 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011245
11246 // Now that I is pointing to the first non-allocation-inst in the block,
11247 // insert our getelementptr instruction...
11248 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000011249 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011250 Value *Idx[2];
11251 Idx[0] = NullIdx;
11252 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011253 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11254 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011255
11256 // Now make everything use the getelementptr instead of the original
11257 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011258 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011259 } else if (isa<UndefValue>(AI.getArraySize())) {
11260 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011261 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011262 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011263
Dan Gohman6893cd72009-01-13 20:18:38 +000011264 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11265 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011266 // Note that we only do this for alloca's, because malloc should allocate
11267 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011268 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Dan Gohman6893cd72009-01-13 20:18:38 +000011269 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11270
11271 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11272 if (AI.getAlignment() == 0)
11273 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11274 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011275
Chris Lattner0864acf2002-11-04 16:18:53 +000011276 return 0;
11277}
11278
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011279Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11280 Value *Op = FI.getOperand(0);
11281
Chris Lattner17be6352004-10-18 02:59:09 +000011282 // free undef -> unreachable.
11283 if (isa<UndefValue>(Op)) {
11284 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000011285 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011286 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011287 return EraseInstFromFunction(FI);
11288 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011289
Chris Lattner6160e852004-02-28 04:57:37 +000011290 // If we have 'free null' delete the instruction. This can happen in stl code
11291 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011292 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011293 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011294
11295 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11296 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11297 FI.setOperand(0, CI->getOperand(0));
11298 return &FI;
11299 }
11300
11301 // Change free (gep X, 0,0,0,0) into free(X)
11302 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11303 if (GEPI->hasAllZeroIndices()) {
11304 AddToWorkList(GEPI);
11305 FI.setOperand(0, GEPI->getOperand(0));
11306 return &FI;
11307 }
11308 }
11309
11310 // Change free(malloc) into nothing, if the malloc has a single use.
11311 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11312 if (MI->hasOneUse()) {
11313 EraseInstFromFunction(FI);
11314 return EraseInstFromFunction(*MI);
11315 }
Chris Lattner6160e852004-02-28 04:57:37 +000011316
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011317 return 0;
11318}
11319
11320
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011321/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011322static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011323 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011324 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011325 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000011326
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011327 if (TD) {
11328 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11329 // Instead of loading constant c string, use corresponding integer value
11330 // directly if string length is small enough.
11331 std::string Str;
11332 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11333 unsigned len = Str.length();
11334 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11335 unsigned numBits = Ty->getPrimitiveSizeInBits();
11336 // Replace LI with immediate integer store.
11337 if ((numBits >> 3) == len + 1) {
11338 APInt StrVal(numBits, 0);
11339 APInt SingleChar(numBits, 0);
11340 if (TD->isLittleEndian()) {
11341 for (signed i = len-1; i >= 0; i--) {
11342 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11343 StrVal = (StrVal << 8) | SingleChar;
11344 }
11345 } else {
11346 for (unsigned i = 0; i < len; i++) {
11347 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11348 StrVal = (StrVal << 8) | SingleChar;
11349 }
11350 // Append NULL at the end.
11351 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011352 StrVal = (StrVal << 8) | SingleChar;
11353 }
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011354 Value *NL = ConstantInt::get(StrVal);
11355 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011356 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011357 }
11358 }
11359 }
11360
Mon P Wang6753f952009-02-07 22:19:29 +000011361 const PointerType *DestTy = cast<PointerType>(CI->getType());
11362 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011363 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011364
11365 // If the address spaces don't match, don't eliminate the cast.
11366 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11367 return 0;
11368
Chris Lattnerb89e0712004-07-13 01:49:43 +000011369 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011370
Reid Spencer42230162007-01-22 05:51:25 +000011371 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011372 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011373 // If the source is an array, the code below will not succeed. Check to
11374 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11375 // constants.
11376 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11377 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11378 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011379 Value *Idxs[2];
11380 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11381 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011382 SrcTy = cast<PointerType>(CastOp->getType());
11383 SrcPTy = SrcTy->getElementType();
11384 }
11385
Reid Spencer42230162007-01-22 05:51:25 +000011386 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011387 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011388 // Do not allow turning this into a load of an integer, which is then
11389 // casted to a pointer, this pessimizes pointer analysis a lot.
11390 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011391 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11392 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011393
Chris Lattnerf9527852005-01-31 04:50:46 +000011394 // Okay, we are casting from one integer or pointer type to another of
11395 // the same size. Instead of casting the pointer before the load, cast
11396 // the result of the loaded value.
11397 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11398 CI->getName(),
11399 LI.isVolatile()),LI);
11400 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011401 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011402 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011403 }
11404 }
11405 return 0;
11406}
11407
Chris Lattnerc10aced2004-09-19 18:43:46 +000011408/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000011409/// from this value cannot trap. If it is not obviously safe to load from the
11410/// specified pointer, we do a quick local scan of the basic block containing
11411/// ScanFrom, to determine if the address is already accessed.
11412static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000011413 // If it is an alloca it is always safe to load from.
11414 if (isa<AllocaInst>(V)) return true;
11415
Duncan Sands46318cd2007-09-19 10:25:38 +000011416 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000011417 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000011418 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000011419 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000011420
11421 // Otherwise, be a little bit agressive by scanning the local block where we
11422 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011423 // from/to. If so, the previous load or store would have already trapped,
11424 // so there is no harm doing an extra load (also, CSE will later eliminate
11425 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000011426 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11427
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011428 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000011429 --BBI;
11430
Chris Lattner2de3fec2008-06-20 05:12:56 +000011431 // If we see a free or a call (which might do a free) the pointer could be
11432 // marked invalid.
Dale Johannesend1c135c2009-03-13 19:23:20 +000011433 if (isa<FreeInst>(BBI) ||
11434 (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)))
Chris Lattner2de3fec2008-06-20 05:12:56 +000011435 return false;
11436
Chris Lattner8a375202004-09-19 19:18:10 +000011437 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11438 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011439 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000011440 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011441 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011442
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011443 }
Chris Lattner8a375202004-09-19 19:18:10 +000011444 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000011445}
11446
Chris Lattner833b8a42003-06-26 05:06:25 +000011447Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11448 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011449
Dan Gohman9941f742007-07-20 16:34:21 +000011450 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011451 unsigned KnownAlign =
11452 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011453 if (KnownAlign >
11454 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11455 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011456 LI.setAlignment(KnownAlign);
11457
Chris Lattner37366c12005-05-01 04:24:53 +000011458 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011459 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011460 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011461 return Res;
11462
11463 // None of the following transforms are legal for volatile loads.
11464 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011465
Dan Gohman2276a7b2008-10-15 23:19:35 +000011466 // Do really simple store-to-load forwarding and load CSE, to catch cases
11467 // where there are several consequtive memory accesses to the same location,
11468 // separated by a few arithmetic operations.
11469 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011470 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11471 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011472
Christopher Lambb15147e2007-12-29 07:56:53 +000011473 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11474 const Value *GEPI0 = GEPI->getOperand(0);
11475 // TODO: Consider a target hook for valid address spaces for this xform.
11476 if (isa<ConstantPointerNull>(GEPI0) &&
11477 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011478 // Insert a new store to null instruction before the load to indicate
11479 // that this code is not reachable. We do this instead of inserting
11480 // an unreachable instruction directly because we cannot modify the
11481 // CFG.
11482 new StoreInst(UndefValue::get(LI.getType()),
11483 Constant::getNullValue(Op->getType()), &LI);
11484 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11485 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011486 }
Chris Lattner37366c12005-05-01 04:24:53 +000011487
Chris Lattnere87597f2004-10-16 18:11:37 +000011488 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011489 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011490 // TODO: Consider a target hook for valid address spaces for this xform.
11491 if (isa<UndefValue>(C) || (C->isNullValue() &&
11492 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011493 // Insert a new store to null instruction before the load to indicate that
11494 // this code is not reachable. We do this instead of inserting an
11495 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000011496 new StoreInst(UndefValue::get(LI.getType()),
11497 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000011498 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011499 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011500
Chris Lattnere87597f2004-10-16 18:11:37 +000011501 // Instcombine load (constant global) into the value loaded.
11502 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011503 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011504 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011505
Chris Lattnere87597f2004-10-16 18:11:37 +000011506 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011507 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011508 if (CE->getOpcode() == Instruction::GetElementPtr) {
11509 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011510 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011511 if (Constant *V =
11512 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011513 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011514 if (CE->getOperand(0)->isNullValue()) {
11515 // Insert a new store to null instruction before the load to indicate
11516 // that this code is not reachable. We do this instead of inserting
11517 // an unreachable instruction directly because we cannot modify the
11518 // CFG.
11519 new StoreInst(UndefValue::get(LI.getType()),
11520 Constant::getNullValue(Op->getType()), &LI);
11521 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11522 }
11523
Reid Spencer3da59db2006-11-27 01:05:10 +000011524 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011525 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011526 return Res;
11527 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011528 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011529 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011530
11531 // If this load comes from anywhere in a constant global, and if the global
11532 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011533 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011534 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011535 if (GV->getInitializer()->isNullValue())
11536 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11537 else if (isa<UndefValue>(GV->getInitializer()))
11538 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11539 }
11540 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011541
Chris Lattner37366c12005-05-01 04:24:53 +000011542 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011543 // Change select and PHI nodes to select values instead of addresses: this
11544 // helps alias analysis out a lot, allows many others simplifications, and
11545 // exposes redundancy in the code.
11546 //
11547 // Note that we cannot do the transformation unless we know that the
11548 // introduced loads cannot trap! Something like this is valid as long as
11549 // the condition is always false: load (select bool %C, int* null, int* %G),
11550 // but it would not be valid if we transformed it to load from null
11551 // unconditionally.
11552 //
11553 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11554 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011555 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11556 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011557 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011558 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011559 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011560 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011561 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011562 }
11563
Chris Lattner684fe212004-09-23 15:46:00 +000011564 // load (select (cond, null, P)) -> load P
11565 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11566 if (C->isNullValue()) {
11567 LI.setOperand(0, SI->getOperand(2));
11568 return &LI;
11569 }
11570
11571 // load (select (cond, P, null)) -> load P
11572 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11573 if (C->isNullValue()) {
11574 LI.setOperand(0, SI->getOperand(1));
11575 return &LI;
11576 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011577 }
11578 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011579 return 0;
11580}
11581
Reid Spencer55af2b52007-01-19 21:20:31 +000011582/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011583/// when possible. This makes it generally easy to do alias analysis and/or
11584/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011585static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11586 User *CI = cast<User>(SI.getOperand(1));
11587 Value *CastOp = CI->getOperand(0);
11588
11589 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011590 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11591 if (SrcTy == 0) return 0;
11592
11593 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011594
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011595 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11596 return 0;
11597
Chris Lattner3914f722009-01-24 01:00:13 +000011598 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11599 /// to its first element. This allows us to handle things like:
11600 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11601 /// on 32-bit hosts.
11602 SmallVector<Value*, 4> NewGEPIndices;
11603
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011604 // If the source is an array, the code below will not succeed. Check to
11605 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11606 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011607 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11608 // Index through pointer.
11609 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11610 NewGEPIndices.push_back(Zero);
11611
11612 while (1) {
11613 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011614 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011615 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011616 NewGEPIndices.push_back(Zero);
11617 SrcPTy = STy->getElementType(0);
11618 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11619 NewGEPIndices.push_back(Zero);
11620 SrcPTy = ATy->getElementType();
11621 } else {
11622 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011623 }
Chris Lattner3914f722009-01-24 01:00:13 +000011624 }
11625
11626 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11627 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011628
11629 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11630 return 0;
11631
Chris Lattner71759c42009-01-16 20:12:52 +000011632 // If the pointers point into different address spaces or if they point to
11633 // values with different sizes, we can't do the transformation.
11634 if (SrcTy->getAddressSpace() !=
11635 cast<PointerType>(CI->getType())->getAddressSpace() ||
11636 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011637 IC.getTargetData().getTypeSizeInBits(DestPTy))
11638 return 0;
11639
11640 // Okay, we are casting from one integer or pointer type to another of
11641 // the same size. Instead of casting the pointer before
11642 // the store, cast the value to be stored.
11643 Value *NewCast;
11644 Value *SIOp0 = SI.getOperand(0);
11645 Instruction::CastOps opcode = Instruction::BitCast;
11646 const Type* CastSrcTy = SIOp0->getType();
11647 const Type* CastDstTy = SrcPTy;
11648 if (isa<PointerType>(CastDstTy)) {
11649 if (CastSrcTy->isInteger())
11650 opcode = Instruction::IntToPtr;
11651 } else if (isa<IntegerType>(CastDstTy)) {
11652 if (isa<PointerType>(SIOp0->getType()))
11653 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011654 }
Chris Lattner3914f722009-01-24 01:00:13 +000011655
11656 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11657 // emit a GEP to index into its first field.
11658 if (!NewGEPIndices.empty()) {
11659 if (Constant *C = dyn_cast<Constant>(CastOp))
11660 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11661 NewGEPIndices.size());
11662 else
11663 CastOp = IC.InsertNewInstBefore(
11664 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11665 NewGEPIndices.end()), SI);
11666 }
11667
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011668 if (Constant *C = dyn_cast<Constant>(SIOp0))
11669 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11670 else
11671 NewCast = IC.InsertNewInstBefore(
11672 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11673 SI);
11674 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011675}
11676
Chris Lattner4aebaee2008-11-27 08:56:30 +000011677/// equivalentAddressValues - Test if A and B will obviously have the same
11678/// value. This includes recognizing that %t0 and %t1 will have the same
11679/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011680/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011681/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011682/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011683/// %t2 = load i32* %t1
11684///
11685static bool equivalentAddressValues(Value *A, Value *B) {
11686 // Test if the values are trivially equivalent.
11687 if (A == B) return true;
11688
11689 // Test if the values come form identical arithmetic instructions.
11690 if (isa<BinaryOperator>(A) ||
11691 isa<CastInst>(A) ||
11692 isa<PHINode>(A) ||
11693 isa<GetElementPtrInst>(A))
11694 if (Instruction *BI = dyn_cast<Instruction>(B))
11695 if (cast<Instruction>(A)->isIdenticalTo(BI))
11696 return true;
11697
11698 // Otherwise they may not be equivalent.
11699 return false;
11700}
11701
Dale Johannesen4945c652009-03-03 21:26:39 +000011702// If this instruction has two uses, one of which is a llvm.dbg.declare,
11703// return the llvm.dbg.declare.
11704DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11705 if (!V->hasNUses(2))
11706 return 0;
11707 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11708 UI != E; ++UI) {
11709 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11710 return DI;
11711 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11712 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11713 return DI;
11714 }
11715 }
11716 return 0;
11717}
11718
Chris Lattner2f503e62005-01-31 05:36:43 +000011719Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11720 Value *Val = SI.getOperand(0);
11721 Value *Ptr = SI.getOperand(1);
11722
11723 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011724 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011725 ++NumCombined;
11726 return 0;
11727 }
Chris Lattner836692d2007-01-15 06:51:56 +000011728
11729 // If the RHS is an alloca with a single use, zapify the store, making the
11730 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011731 // If the RHS is an alloca with a two uses, the other one being a
11732 // llvm.dbg.declare, zapify the store and the declare, making the
11733 // alloca dead. We must do this to prevent declare's from affecting
11734 // codegen.
11735 if (!SI.isVolatile()) {
11736 if (Ptr->hasOneUse()) {
11737 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011738 EraseInstFromFunction(SI);
11739 ++NumCombined;
11740 return 0;
11741 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011742 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11743 if (isa<AllocaInst>(GEP->getOperand(0))) {
11744 if (GEP->getOperand(0)->hasOneUse()) {
11745 EraseInstFromFunction(SI);
11746 ++NumCombined;
11747 return 0;
11748 }
11749 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11750 EraseInstFromFunction(*DI);
11751 EraseInstFromFunction(SI);
11752 ++NumCombined;
11753 return 0;
11754 }
11755 }
11756 }
11757 }
11758 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11759 EraseInstFromFunction(*DI);
11760 EraseInstFromFunction(SI);
11761 ++NumCombined;
11762 return 0;
11763 }
Chris Lattner836692d2007-01-15 06:51:56 +000011764 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011765
Dan Gohman9941f742007-07-20 16:34:21 +000011766 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011767 unsigned KnownAlign =
11768 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011769 if (KnownAlign >
11770 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11771 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011772 SI.setAlignment(KnownAlign);
11773
Dale Johannesenacb51a32009-03-03 01:43:03 +000011774 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011775 // stores to the same location, separated by a few arithmetic operations. This
11776 // situation often occurs with bitfield accesses.
11777 BasicBlock::iterator BBI = &SI;
11778 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11779 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011780 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011781 // Don't count debug info directives, lest they affect codegen,
11782 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11783 // It is necessary for correctness to skip those that feed into a
11784 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011785 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011786 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011787 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011788 continue;
11789 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011790
11791 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11792 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011793 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11794 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011795 ++NumDeadStore;
11796 ++BBI;
11797 EraseInstFromFunction(*PrevSI);
11798 continue;
11799 }
11800 break;
11801 }
11802
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011803 // If this is a load, we have to stop. However, if the loaded value is from
11804 // the pointer we're loading and is producing the pointer we're storing,
11805 // then *this* store is dead (X = load P; store X -> P).
11806 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011807 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11808 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011809 EraseInstFromFunction(SI);
11810 ++NumCombined;
11811 return 0;
11812 }
11813 // Otherwise, this is a load from some other location. Stores before it
11814 // may not be dead.
11815 break;
11816 }
11817
Chris Lattner9ca96412006-02-08 03:25:32 +000011818 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011819 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011820 break;
11821 }
11822
11823
11824 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011825
11826 // store X, null -> turns into 'unreachable' in SimplifyCFG
11827 if (isa<ConstantPointerNull>(Ptr)) {
11828 if (!isa<UndefValue>(Val)) {
11829 SI.setOperand(0, UndefValue::get(Val->getType()));
11830 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011831 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011832 ++NumCombined;
11833 }
11834 return 0; // Do not modify these!
11835 }
11836
11837 // store undef, Ptr -> noop
11838 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011839 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011840 ++NumCombined;
11841 return 0;
11842 }
11843
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011844 // If the pointer destination is a cast, see if we can fold the cast into the
11845 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011846 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011847 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11848 return Res;
11849 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011850 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011851 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11852 return Res;
11853
Chris Lattner408902b2005-09-12 23:23:25 +000011854
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011855 // If this store is the last instruction in the basic block (possibly
11856 // excepting debug info instructions and the pointer bitcasts that feed
11857 // into them), and if the block ends with an unconditional branch, try
11858 // to move it to the successor block.
11859 BBI = &SI;
11860 do {
11861 ++BBI;
11862 } while (isa<DbgInfoIntrinsic>(BBI) ||
11863 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011864 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011865 if (BI->isUnconditional())
11866 if (SimplifyStoreAtEndOfBlock(SI))
11867 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011868
Chris Lattner2f503e62005-01-31 05:36:43 +000011869 return 0;
11870}
11871
Chris Lattner3284d1f2007-04-15 00:07:55 +000011872/// SimplifyStoreAtEndOfBlock - Turn things like:
11873/// if () { *P = v1; } else { *P = v2 }
11874/// into a phi node with a store in the successor.
11875///
Chris Lattner31755a02007-04-15 01:02:18 +000011876/// Simplify things like:
11877/// *P = v1; if () { *P = v2; }
11878/// into a phi node with a store in the successor.
11879///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011880bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11881 BasicBlock *StoreBB = SI.getParent();
11882
11883 // Check to see if the successor block has exactly two incoming edges. If
11884 // so, see if the other predecessor contains a store to the same location.
11885 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011886 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011887
11888 // Determine whether Dest has exactly two predecessors and, if so, compute
11889 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011890 pred_iterator PI = pred_begin(DestBB);
11891 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011892 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011893 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011894 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011895 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011896 return false;
11897
11898 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011899 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011900 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011901 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011902 }
Chris Lattner31755a02007-04-15 01:02:18 +000011903 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011904 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011905
11906 // Bail out if all the relevant blocks aren't distinct (this can happen,
11907 // for example, if SI is in an infinite loop)
11908 if (StoreBB == DestBB || OtherBB == DestBB)
11909 return false;
11910
Chris Lattner31755a02007-04-15 01:02:18 +000011911 // Verify that the other block ends in a branch and is not otherwise empty.
11912 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011913 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011914 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011915 return false;
11916
Chris Lattner31755a02007-04-15 01:02:18 +000011917 // If the other block ends in an unconditional branch, check for the 'if then
11918 // else' case. there is an instruction before the branch.
11919 StoreInst *OtherStore = 0;
11920 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011921 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011922 // Skip over debugging info.
11923 while (isa<DbgInfoIntrinsic>(BBI) ||
11924 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11925 if (BBI==OtherBB->begin())
11926 return false;
11927 --BBI;
11928 }
11929 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011930 OtherStore = dyn_cast<StoreInst>(BBI);
11931 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11932 return false;
11933 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011934 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011935 // destinations is StoreBB, then we have the if/then case.
11936 if (OtherBr->getSuccessor(0) != StoreBB &&
11937 OtherBr->getSuccessor(1) != StoreBB)
11938 return false;
11939
11940 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011941 // if/then triangle. See if there is a store to the same ptr as SI that
11942 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011943 for (;; --BBI) {
11944 // Check to see if we find the matching store.
11945 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11946 if (OtherStore->getOperand(1) != SI.getOperand(1))
11947 return false;
11948 break;
11949 }
Eli Friedman6903a242008-06-13 22:02:12 +000011950 // If we find something that may be using or overwriting the stored
11951 // value, or if we run out of instructions, we can't do the xform.
11952 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011953 BBI == OtherBB->begin())
11954 return false;
11955 }
11956
11957 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011958 // make sure nothing reads or overwrites the stored value in
11959 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011960 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11961 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011962 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011963 return false;
11964 }
11965 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011966
Chris Lattner31755a02007-04-15 01:02:18 +000011967 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011968 Value *MergedVal = OtherStore->getOperand(0);
11969 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011970 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011971 PN->reserveOperandSpace(2);
11972 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011973 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11974 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011975 }
11976
11977 // Advance to a place where it is safe to insert the new store and
11978 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011979 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011980 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11981 OtherStore->isVolatile()), *BBI);
11982
11983 // Nuke the old stores.
11984 EraseInstFromFunction(SI);
11985 EraseInstFromFunction(*OtherStore);
11986 ++NumCombined;
11987 return true;
11988}
11989
Chris Lattner2f503e62005-01-31 05:36:43 +000011990
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011991Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11992 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011993 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011994 BasicBlock *TrueDest;
11995 BasicBlock *FalseDest;
11996 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11997 !isa<Constant>(X)) {
11998 // Swap Destinations and condition...
11999 BI.setCondition(X);
12000 BI.setSuccessor(0, FalseDest);
12001 BI.setSuccessor(1, TrueDest);
12002 return &BI;
12003 }
12004
Reid Spencere4d87aa2006-12-23 06:05:41 +000012005 // Cannonicalize fcmp_one -> fcmp_oeq
12006 FCmpInst::Predicate FPred; Value *Y;
12007 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
12008 TrueDest, FalseDest)))
12009 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12010 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12011 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012012 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000012013 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
12014 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012015 // Swap Destinations and condition...
12016 BI.setCondition(NewSCC);
12017 BI.setSuccessor(0, FalseDest);
12018 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012019 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012020 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012021 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012022 return &BI;
12023 }
12024
12025 // Cannonicalize icmp_ne -> icmp_eq
12026 ICmpInst::Predicate IPred;
12027 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12028 TrueDest, FalseDest)))
12029 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12030 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12031 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12032 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012033 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000012034 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
12035 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012036 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012037 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012038 BI.setSuccessor(0, FalseDest);
12039 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012040 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012041 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012042 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012043 return &BI;
12044 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012045
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012046 return 0;
12047}
Chris Lattner0864acf2002-11-04 16:18:53 +000012048
Chris Lattner46238a62004-07-03 00:26:11 +000012049Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12050 Value *Cond = SI.getCondition();
12051 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12052 if (I->getOpcode() == Instruction::Add)
12053 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12054 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12055 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000012056 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012057 AddRHS));
12058 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012059 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012060 return &SI;
12061 }
12062 }
12063 return 0;
12064}
12065
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012066Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012067 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012068
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012069 if (!EV.hasIndices())
12070 return ReplaceInstUsesWith(EV, Agg);
12071
12072 if (Constant *C = dyn_cast<Constant>(Agg)) {
12073 if (isa<UndefValue>(C))
12074 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12075
12076 if (isa<ConstantAggregateZero>(C))
12077 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12078
12079 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12080 // Extract the element indexed by the first index out of the constant
12081 Value *V = C->getOperand(*EV.idx_begin());
12082 if (EV.getNumIndices() > 1)
12083 // Extract the remaining indices out of the constant indexed by the
12084 // first index
12085 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12086 else
12087 return ReplaceInstUsesWith(EV, V);
12088 }
12089 return 0; // Can't handle other constants
12090 }
12091 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12092 // We're extracting from an insertvalue instruction, compare the indices
12093 const unsigned *exti, *exte, *insi, *inse;
12094 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12095 exte = EV.idx_end(), inse = IV->idx_end();
12096 exti != exte && insi != inse;
12097 ++exti, ++insi) {
12098 if (*insi != *exti)
12099 // The insert and extract both reference distinctly different elements.
12100 // This means the extract is not influenced by the insert, and we can
12101 // replace the aggregate operand of the extract with the aggregate
12102 // operand of the insert. i.e., replace
12103 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12104 // %E = extractvalue { i32, { i32 } } %I, 0
12105 // with
12106 // %E = extractvalue { i32, { i32 } } %A, 0
12107 return ExtractValueInst::Create(IV->getAggregateOperand(),
12108 EV.idx_begin(), EV.idx_end());
12109 }
12110 if (exti == exte && insi == inse)
12111 // Both iterators are at the end: Index lists are identical. Replace
12112 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12113 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12114 // with "i32 42"
12115 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12116 if (exti == exte) {
12117 // The extract list is a prefix of the insert list. i.e. replace
12118 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12119 // %E = extractvalue { i32, { i32 } } %I, 1
12120 // with
12121 // %X = extractvalue { i32, { i32 } } %A, 1
12122 // %E = insertvalue { i32 } %X, i32 42, 0
12123 // by switching the order of the insert and extract (though the
12124 // insertvalue should be left in, since it may have other uses).
12125 Value *NewEV = InsertNewInstBefore(
12126 ExtractValueInst::Create(IV->getAggregateOperand(),
12127 EV.idx_begin(), EV.idx_end()),
12128 EV);
12129 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12130 insi, inse);
12131 }
12132 if (insi == inse)
12133 // The insert list is a prefix of the extract list
12134 // We can simply remove the common indices from the extract and make it
12135 // operate on the inserted value instead of the insertvalue result.
12136 // i.e., replace
12137 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12138 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12139 // with
12140 // %E extractvalue { i32 } { i32 42 }, 0
12141 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12142 exti, exte);
12143 }
12144 // Can't simplify extracts from other values. Note that nested extracts are
12145 // already simplified implicitely by the above (extract ( extract (insert) )
12146 // will be translated into extract ( insert ( extract ) ) first and then just
12147 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012148 return 0;
12149}
12150
Chris Lattner220b0cf2006-03-05 00:22:33 +000012151/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12152/// is to leave as a vector operation.
12153static bool CheapToScalarize(Value *V, bool isConstant) {
12154 if (isa<ConstantAggregateZero>(V))
12155 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012156 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012157 if (isConstant) return true;
12158 // If all elts are the same, we can extract.
12159 Constant *Op0 = C->getOperand(0);
12160 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12161 if (C->getOperand(i) != Op0)
12162 return false;
12163 return true;
12164 }
12165 Instruction *I = dyn_cast<Instruction>(V);
12166 if (!I) return false;
12167
12168 // Insert element gets simplified to the inserted element or is deleted if
12169 // this is constant idx extract element and its a constant idx insertelt.
12170 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12171 isa<ConstantInt>(I->getOperand(2)))
12172 return true;
12173 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12174 return true;
12175 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12176 if (BO->hasOneUse() &&
12177 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12178 CheapToScalarize(BO->getOperand(1), isConstant)))
12179 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012180 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12181 if (CI->hasOneUse() &&
12182 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12183 CheapToScalarize(CI->getOperand(1), isConstant)))
12184 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012185
12186 return false;
12187}
12188
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012189/// Read and decode a shufflevector mask.
12190///
12191/// It turns undef elements into values that are larger than the number of
12192/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012193static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12194 unsigned NElts = SVI->getType()->getNumElements();
12195 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12196 return std::vector<unsigned>(NElts, 0);
12197 if (isa<UndefValue>(SVI->getOperand(2)))
12198 return std::vector<unsigned>(NElts, 2*NElts);
12199
12200 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012201 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012202 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12203 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012204 Result.push_back(NElts*2); // undef -> 8
12205 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012206 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012207 return Result;
12208}
12209
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012210/// FindScalarElement - Given a vector and an element number, see if the scalar
12211/// value is already around as a register, for example if it were inserted then
12212/// extracted from the vector.
12213static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012214 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12215 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012216 unsigned Width = PTy->getNumElements();
12217 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012218 return UndefValue::get(PTy->getElementType());
12219
12220 if (isa<UndefValue>(V))
12221 return UndefValue::get(PTy->getElementType());
12222 else if (isa<ConstantAggregateZero>(V))
12223 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012224 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012225 return CP->getOperand(EltNo);
12226 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12227 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012228 if (!isa<ConstantInt>(III->getOperand(2)))
12229 return 0;
12230 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012231
12232 // If this is an insert to the element we are looking for, return the
12233 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012234 if (EltNo == IIElt)
12235 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012236
12237 // Otherwise, the insertelement doesn't modify the value, recurse on its
12238 // vector input.
12239 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000012240 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012241 unsigned LHSWidth =
12242 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012243 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012244 if (InEl < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012245 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012246 else if (InEl < LHSWidth*2)
12247 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000012248 else
12249 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012250 }
12251
12252 // Otherwise, we don't know.
12253 return 0;
12254}
12255
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012256Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012257 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012258 if (isa<UndefValue>(EI.getOperand(0)))
12259 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12260
Dan Gohman07a96762007-07-16 14:29:03 +000012261 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012262 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12263 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12264
Reid Spencer9d6565a2007-02-15 02:26:10 +000012265 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012266 // If vector val is constant with all elements the same, replace EI with
12267 // that element. When the elements are not identical, we cannot replace yet
12268 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012269 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012270 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012271 if (C->getOperand(i) != op0) {
12272 op0 = 0;
12273 break;
12274 }
12275 if (op0)
12276 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012277 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000012278
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012279 // If extracting a specified index from the vector, see if we can recursively
12280 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012281 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012282 unsigned IndexVal = IdxC->getZExtValue();
12283 unsigned VectorWidth =
12284 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12285
12286 // If this is extracting an invalid index, turn this into undef, to avoid
12287 // crashing the code below.
12288 if (IndexVal >= VectorWidth)
12289 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12290
Chris Lattner867b99f2006-10-05 06:55:50 +000012291 // This instruction only demands the single element from the input vector.
12292 // If the input vector has a single use, simplify it based on this use
12293 // property.
Chris Lattner85464092007-04-09 01:37:55 +000012294 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012295 APInt UndefElts(VectorWidth, 0);
12296 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012297 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012298 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012299 EI.setOperand(0, V);
12300 return &EI;
12301 }
12302 }
12303
Reid Spencerb83eb642006-10-20 07:07:24 +000012304 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012305 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012306
12307 // If the this extractelement is directly using a bitcast from a vector of
12308 // the same number of elements, see if we can find the source element from
12309 // it. In this case, we will end up needing to bitcast the scalars.
12310 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12311 if (const VectorType *VT =
12312 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12313 if (VT->getNumElements() == VectorWidth)
12314 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12315 return new BitCastInst(Elt, EI.getType());
12316 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012317 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012318
Chris Lattner73fa49d2006-05-25 22:53:38 +000012319 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012320 if (I->hasOneUse()) {
12321 // Push extractelement into predecessor operation if legal and
12322 // profitable to do so
12323 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012324 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12325 if (CheapToScalarize(BO, isConstantElt)) {
12326 ExtractElementInst *newEI0 =
12327 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12328 EI.getName()+".lhs");
12329 ExtractElementInst *newEI1 =
12330 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12331 EI.getName()+".rhs");
12332 InsertNewInstBefore(newEI0, EI);
12333 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012334 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012335 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012336 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012337 unsigned AS =
12338 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012339 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12340 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012341 GetElementPtrInst *GEP =
12342 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012343 InsertNewInstBefore(GEP, EI);
12344 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012345 }
12346 }
12347 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12348 // Extracting the inserted element?
12349 if (IE->getOperand(2) == EI.getOperand(1))
12350 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12351 // If the inserted and extracted elements are constants, they must not
12352 // be the same value, extract from the pre-inserted value instead.
12353 if (isa<Constant>(IE->getOperand(2)) &&
12354 isa<Constant>(EI.getOperand(1))) {
12355 AddUsesToWorkList(EI);
12356 EI.setOperand(0, IE->getOperand(0));
12357 return &EI;
12358 }
12359 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12360 // If this is extracting an element from a shufflevector, figure out where
12361 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012362 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12363 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012364 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012365 unsigned LHSWidth =
12366 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12367
12368 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012369 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012370 else if (SrcIdx < LHSWidth*2) {
12371 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012372 Src = SVI->getOperand(1);
12373 } else {
12374 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012375 }
Chris Lattner867b99f2006-10-05 06:55:50 +000012376 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012377 }
12378 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012379 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012380 return 0;
12381}
12382
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012383/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12384/// elements from either LHS or RHS, return the shuffle mask and true.
12385/// Otherwise, return false.
12386static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12387 std::vector<Constant*> &Mask) {
12388 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12389 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012390 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012391
12392 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012393 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012394 return true;
12395 } else if (V == LHS) {
12396 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012397 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012398 return true;
12399 } else if (V == RHS) {
12400 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012401 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012402 return true;
12403 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12404 // If this is an insert of an extract from some other vector, include it.
12405 Value *VecOp = IEI->getOperand(0);
12406 Value *ScalarOp = IEI->getOperand(1);
12407 Value *IdxOp = IEI->getOperand(2);
12408
Chris Lattnerd929f062006-04-27 21:14:21 +000012409 if (!isa<ConstantInt>(IdxOp))
12410 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012411 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012412
12413 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12414 // Okay, we can handle this if the vector we are insertinting into is
12415 // transitively ok.
12416 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12417 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000012418 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012419 return true;
12420 }
12421 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12422 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012423 EI->getOperand(0)->getType() == V->getType()) {
12424 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012425 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012426
12427 // This must be extracting from either LHS or RHS.
12428 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12429 // Okay, we can handle this if the vector we are insertinting into is
12430 // transitively ok.
12431 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12432 // If so, update the mask to reflect the inserted value.
12433 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012434 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012435 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012436 } else {
12437 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012438 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012439 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012440
12441 }
12442 return true;
12443 }
12444 }
12445 }
12446 }
12447 }
12448 // TODO: Handle shufflevector here!
12449
12450 return false;
12451}
12452
12453/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12454/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12455/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012456static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012457 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012458 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012459 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012460 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012461 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012462
12463 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012464 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012465 return V;
12466 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012467 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012468 return V;
12469 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12470 // If this is an insert of an extract from some other vector, include it.
12471 Value *VecOp = IEI->getOperand(0);
12472 Value *ScalarOp = IEI->getOperand(1);
12473 Value *IdxOp = IEI->getOperand(2);
12474
12475 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12476 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12477 EI->getOperand(0)->getType() == V->getType()) {
12478 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012479 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12480 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012481
12482 // Either the extracted from or inserted into vector must be RHSVec,
12483 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012484 if (EI->getOperand(0) == RHS || RHS == 0) {
12485 RHS = EI->getOperand(0);
12486 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012487 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012488 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012489 return V;
12490 }
12491
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012492 if (VecOp == RHS) {
12493 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000012494 // Everything but the extracted element is replaced with the RHS.
12495 for (unsigned i = 0; i != NumElts; ++i) {
12496 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012497 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012498 }
12499 return V;
12500 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012501
12502 // If this insertelement is a chain that comes from exactly these two
12503 // vectors, return the vector and the effective shuffle.
12504 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12505 return EI->getOperand(0);
12506
Chris Lattnerefb47352006-04-15 01:39:45 +000012507 }
12508 }
12509 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012510 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012511
12512 // Otherwise, can't do anything fancy. Return an identity vector.
12513 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012514 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012515 return V;
12516}
12517
12518Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12519 Value *VecOp = IE.getOperand(0);
12520 Value *ScalarOp = IE.getOperand(1);
12521 Value *IdxOp = IE.getOperand(2);
12522
Chris Lattner599ded12007-04-09 01:11:16 +000012523 // Inserting an undef or into an undefined place, remove this.
12524 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12525 ReplaceInstUsesWith(IE, VecOp);
12526
Chris Lattnerefb47352006-04-15 01:39:45 +000012527 // If the inserted element was extracted from some other vector, and if the
12528 // indexes are constant, try to turn this into a shufflevector operation.
12529 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12530 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12531 EI->getOperand(0)->getType() == IE.getType()) {
12532 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012533 unsigned ExtractedIdx =
12534 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012535 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012536
12537 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12538 return ReplaceInstUsesWith(IE, VecOp);
12539
12540 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12541 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12542
12543 // If we are extracting a value from a vector, then inserting it right
12544 // back into the same place, just use the input vector.
12545 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12546 return ReplaceInstUsesWith(IE, VecOp);
12547
12548 // We could theoretically do this for ANY input. However, doing so could
12549 // turn chains of insertelement instructions into a chain of shufflevector
12550 // instructions, and right now we do not merge shufflevectors. As such,
12551 // only do this in a situation where it is clear that there is benefit.
12552 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12553 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12554 // the values of VecOp, except then one read from EIOp0.
12555 // Build a new shuffle mask.
12556 std::vector<Constant*> Mask;
12557 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000012558 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012559 else {
12560 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000012561 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012562 NumVectorElts));
12563 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000012564 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012565 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000012566 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012567 }
12568
12569 // If this insertelement isn't used by some other insertelement, turn it
12570 // (and any insertelements it points to), into one big shuffle.
12571 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12572 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012573 Value *RHS = 0;
12574 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12575 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12576 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000012577 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012578 }
12579 }
12580 }
12581
12582 return 0;
12583}
12584
12585
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012586Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12587 Value *LHS = SVI.getOperand(0);
12588 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012589 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012590
12591 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012592
Chris Lattner867b99f2006-10-05 06:55:50 +000012593 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012594 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012595 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012596
Dan Gohman488fbfc2008-09-09 18:11:14 +000012597 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012598
12599 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12600 return 0;
12601
Evan Cheng388df622009-02-03 10:05:09 +000012602 APInt UndefElts(VWidth, 0);
12603 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12604 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012605 LHS = SVI.getOperand(0);
12606 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012607 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012608 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012609
Chris Lattner863bcff2006-05-25 23:48:38 +000012610 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12611 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12612 if (LHS == RHS || isa<UndefValue>(LHS)) {
12613 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012614 // shuffle(undef,undef,mask) -> undef.
12615 return ReplaceInstUsesWith(SVI, LHS);
12616 }
12617
Chris Lattner863bcff2006-05-25 23:48:38 +000012618 // Remap any references to RHS to use LHS.
12619 std::vector<Constant*> Elts;
12620 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012621 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012622 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012623 else {
12624 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012625 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012626 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000012627 Elts.push_back(UndefValue::get(Type::Int32Ty));
12628 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012629 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000012630 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12631 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012632 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012633 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012634 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012635 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000012636 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012637 LHS = SVI.getOperand(0);
12638 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012639 MadeChange = true;
12640 }
12641
Chris Lattner7b2e27922006-05-26 00:29:06 +000012642 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012643 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012644
Chris Lattner863bcff2006-05-25 23:48:38 +000012645 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12646 if (Mask[i] >= e*2) continue; // Ignore undef values.
12647 // Is this an identity shuffle of the LHS value?
12648 isLHSID &= (Mask[i] == i);
12649
12650 // Is this an identity shuffle of the RHS value?
12651 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012652 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012653
Chris Lattner863bcff2006-05-25 23:48:38 +000012654 // Eliminate identity shuffles.
12655 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12656 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012657
Chris Lattner7b2e27922006-05-26 00:29:06 +000012658 // If the LHS is a shufflevector itself, see if we can combine it with this
12659 // one without producing an unusual shuffle. Here we are really conservative:
12660 // we are absolutely afraid of producing a shuffle mask not in the input
12661 // program, because the code gen may not be smart enough to turn a merged
12662 // shuffle into two specific shuffles: it may produce worse code. As such,
12663 // we only merge two shuffles if the result is one of the two input shuffle
12664 // masks. In this case, merging the shuffles just removes one instruction,
12665 // which we know is safe. This is good for things like turning:
12666 // (splat(splat)) -> splat.
12667 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12668 if (isa<UndefValue>(RHS)) {
12669 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12670
12671 std::vector<unsigned> NewMask;
12672 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12673 if (Mask[i] >= 2*e)
12674 NewMask.push_back(2*e);
12675 else
12676 NewMask.push_back(LHSMask[Mask[i]]);
12677
12678 // If the result mask is equal to the src shuffle or this shuffle mask, do
12679 // the replacement.
12680 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012681 unsigned LHSInNElts =
12682 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012683 std::vector<Constant*> Elts;
12684 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012685 if (NewMask[i] >= LHSInNElts*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012686 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012687 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012688 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012689 }
12690 }
12691 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12692 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000012693 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012694 }
12695 }
12696 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012697
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012698 return MadeChange ? &SVI : 0;
12699}
12700
12701
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012702
Chris Lattnerea1c4542004-12-08 23:43:58 +000012703
12704/// TryToSinkInstruction - Try to move the specified instruction from its
12705/// current block into the beginning of DestBlock, which can only happen if it's
12706/// safe to move the instruction past all of the instructions between it and the
12707/// end of its block.
12708static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12709 assert(I->hasOneUse() && "Invariants didn't hold!");
12710
Chris Lattner108e9022005-10-27 17:13:11 +000012711 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012712 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012713 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012714
Chris Lattnerea1c4542004-12-08 23:43:58 +000012715 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012716 if (isa<AllocaInst>(I) && I->getParent() ==
12717 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012718 return false;
12719
Chris Lattner96a52a62004-12-09 07:14:34 +000012720 // We can only sink load instructions if there is nothing between the load and
12721 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012722 if (I->mayReadFromMemory()) {
12723 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012724 Scan != E; ++Scan)
12725 if (Scan->mayWriteToMemory())
12726 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012727 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012728
Dan Gohman02dea8b2008-05-23 21:05:58 +000012729 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012730
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012731 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012732 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012733 ++NumSunkInst;
12734 return true;
12735}
12736
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012737
12738/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12739/// all reachable code to the worklist.
12740///
12741/// This has a couple of tricks to make the code faster and more powerful. In
12742/// particular, we constant fold and DCE instructions as we go, to avoid adding
12743/// them to the worklist (this significantly speeds up instcombine on code where
12744/// many instructions are dead or constant). Additionally, if we find a branch
12745/// whose condition is a known constant, we only visit the reachable successors.
12746///
12747static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012748 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012749 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012750 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012751 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012752 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012753
Chris Lattner2c7718a2007-03-23 19:17:18 +000012754 while (!Worklist.empty()) {
12755 BB = Worklist.back();
12756 Worklist.pop_back();
12757
12758 // We have now visited this block! If we've already been here, ignore it.
12759 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012760
12761 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012762 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12763 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012764
Chris Lattner2c7718a2007-03-23 19:17:18 +000012765 // DCE instruction if trivially dead.
12766 if (isInstructionTriviallyDead(Inst)) {
12767 ++NumDeadInst;
12768 DOUT << "IC: DCE: " << *Inst;
12769 Inst->eraseFromParent();
12770 continue;
12771 }
12772
12773 // ConstantProp instruction if trivially constant.
12774 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12775 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12776 Inst->replaceAllUsesWith(C);
12777 ++NumConstProp;
12778 Inst->eraseFromParent();
12779 continue;
12780 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012781
Devang Patel7fe1dec2008-11-19 18:56:50 +000012782 // If there are two consecutive llvm.dbg.stoppoint calls then
12783 // it is likely that the optimizer deleted code in between these
12784 // two intrinsics.
12785 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12786 if (DBI_Next) {
12787 if (DBI_Prev
12788 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12789 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12790 IC.RemoveFromWorkList(DBI_Prev);
12791 DBI_Prev->eraseFromParent();
12792 }
12793 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012794 } else {
12795 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012796 }
12797
Chris Lattner2c7718a2007-03-23 19:17:18 +000012798 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012799 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012800
12801 // Recursively visit successors. If this is a branch or switch on a
12802 // constant, only visit the reachable successor.
12803 TerminatorInst *TI = BB->getTerminator();
12804 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12805 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12806 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012807 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012808 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012809 continue;
12810 }
12811 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12812 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12813 // See if this is an explicit destination.
12814 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12815 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012816 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012817 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012818 continue;
12819 }
12820
12821 // Otherwise it is the default destination.
12822 Worklist.push_back(SI->getSuccessor(0));
12823 continue;
12824 }
12825 }
12826
12827 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12828 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012829 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012830}
12831
Chris Lattnerec9c3582007-03-03 02:04:50 +000012832bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012833 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012834 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012835
12836 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12837 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012838
Chris Lattnerb3d59702005-07-07 20:40:38 +000012839 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012840 // Do a depth-first traversal of the function, populate the worklist with
12841 // the reachable instructions. Ignore blocks that are not reachable. Keep
12842 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012843 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012844 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012845
Chris Lattnerb3d59702005-07-07 20:40:38 +000012846 // Do a quick scan over the function. If we find any blocks that are
12847 // unreachable, remove any instructions inside of them. This prevents
12848 // the instcombine code from having to deal with some bad special cases.
12849 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12850 if (!Visited.count(BB)) {
12851 Instruction *Term = BB->getTerminator();
12852 while (Term != BB->begin()) { // Remove instrs bottom-up
12853 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012854
Bill Wendlingb7427032006-11-26 09:46:52 +000012855 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012856 // A debug intrinsic shouldn't force another iteration if we weren't
12857 // going to do one without it.
12858 if (!isa<DbgInfoIntrinsic>(I)) {
12859 ++NumDeadInst;
12860 Changed = true;
12861 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012862 if (!I->use_empty())
12863 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12864 I->eraseFromParent();
12865 }
12866 }
12867 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012868
Chris Lattnerdbab3862007-03-02 21:28:56 +000012869 while (!Worklist.empty()) {
12870 Instruction *I = RemoveOneFromWorkList();
12871 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012872
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012873 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012874 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012875 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012876 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012877 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012878 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012879
Bill Wendlingb7427032006-11-26 09:46:52 +000012880 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012881
12882 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012883 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012884 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012885 continue;
12886 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012887
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012888 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000012889 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012890 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012891
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012892 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012893 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012894 ReplaceInstUsesWith(*I, C);
12895
Chris Lattner62b14df2002-09-02 04:59:56 +000012896 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012897 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012898 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012899 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012900 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012901 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012902
Dan Gohman31e4c772009-05-07 19:43:39 +000012903 if (TD &&
12904 (I->getType()->getTypeID() == Type::VoidTyID ||
12905 I->isTrapping())) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012906 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012907 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12908 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012909 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012910 if (NewC != CE) {
12911 i->set(NewC);
12912 Changed = true;
12913 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012914 }
12915
Chris Lattnerea1c4542004-12-08 23:43:58 +000012916 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012917 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012918 BasicBlock *BB = I->getParent();
12919 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12920 if (UserParent != BB) {
12921 bool UserIsSuccessor = false;
12922 // See if the user is one of our successors.
12923 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12924 if (*SI == UserParent) {
12925 UserIsSuccessor = true;
12926 break;
12927 }
12928
12929 // If the user is one of our immediate successors, and if that successor
12930 // only has us as a predecessors (we'd have to split the critical edge
12931 // otherwise), we can keep going.
12932 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12933 next(pred_begin(UserParent)) == pred_end(UserParent))
12934 // Okay, the CFG is simple enough, try to sink this instruction.
12935 Changed |= TryToSinkInstruction(I, UserParent);
12936 }
12937 }
12938
Chris Lattner8a2a3112001-12-14 16:52:21 +000012939 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012940#ifndef NDEBUG
12941 std::string OrigI;
12942#endif
12943 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012944 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012945 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012946 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012947 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012948 DOUT << "IC: Old = " << *I
12949 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000012950
Chris Lattnerf523d062004-06-09 05:08:07 +000012951 // Everything uses the new instruction now.
12952 I->replaceAllUsesWith(Result);
12953
12954 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012955 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000012956 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012957
Chris Lattner6934a042007-02-11 01:23:03 +000012958 // Move the name to the new instruction first.
12959 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012960
12961 // Insert the new instruction into the basic block...
12962 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012963 BasicBlock::iterator InsertPos = I;
12964
12965 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12966 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12967 ++InsertPos;
12968
12969 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012970
Chris Lattner00d51312004-05-01 23:27:23 +000012971 // Make sure that we reprocess all operands now that we reduced their
12972 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012973 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000012974
Chris Lattnerf523d062004-06-09 05:08:07 +000012975 // Instructions can end up on the worklist more than once. Make sure
12976 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012977 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012978
12979 // Erase the old instruction.
12980 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000012981 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012982#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000012983 DOUT << "IC: Mod = " << OrigI
12984 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000012985#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012986
Chris Lattner90ac28c2002-08-02 19:29:35 +000012987 // If the instruction was modified, it's possible that it is now dead.
12988 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012989 if (isInstructionTriviallyDead(I)) {
12990 // Make sure we process all operands now that we are reducing their
12991 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000012992 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012993
Chris Lattner00d51312004-05-01 23:27:23 +000012994 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012995 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012996 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000012997 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000012998 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000012999 AddToWorkList(I);
13000 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013001 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013002 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013003 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013004 }
13005 }
13006
Chris Lattnerec9c3582007-03-03 02:04:50 +000013007 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013008
13009 // Do an explicit clear, this shrinks the map if needed.
13010 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013011 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013012}
13013
Chris Lattnerec9c3582007-03-03 02:04:50 +000013014
13015bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013016 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13017
Chris Lattnerec9c3582007-03-03 02:04:50 +000013018 bool EverMadeChange = false;
13019
13020 // Iterate while there is work to do.
13021 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013022 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013023 EverMadeChange = true;
13024 return EverMadeChange;
13025}
13026
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013027FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013028 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013029}