blob: c0fce65460d406b472cf540c494d3d9a86bb89c0 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner173234a2008-06-02 01:18:21 +000047#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000048#include "llvm/Target/TargetData.h"
49#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000051#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000052#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000053#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000054#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000055#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000056#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000057#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000058#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000059#include "llvm/Support/PatternMatch.h"
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000060#include "llvm/Support/TargetFolder.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000061#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000062#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000063#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000064#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000065#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000066#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000067#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000068#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000069using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000070using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072STATISTIC(NumCombined , "Number of insts combined");
73STATISTIC(NumConstProp, "Number of constant folds");
74STATISTIC(NumDeadInst , "Number of dead inst eliminated");
75STATISTIC(NumDeadStore, "Number of dead stores eliminated");
76STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000077
Chris Lattnerb109b5c2009-12-21 06:03:05 +000078/// SelectPatternFlavor - We can match a variety of different patterns for
79/// select operations.
80enum SelectPatternFlavor {
81 SPF_UNKNOWN = 0,
82 SPF_SMIN, SPF_UMIN,
83 SPF_SMAX, SPF_UMAX
84 //SPF_ABS - TODO.
85};
86
Chris Lattner0e5f4992006-12-19 21:40:18 +000087namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000088 /// InstCombineWorklist - This is the worklist management logic for
89 /// InstCombine.
90 class InstCombineWorklist {
91 SmallVector<Instruction*, 256> Worklist;
92 DenseMap<Instruction*, unsigned> WorklistMap;
93
94 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
95 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
96 public:
97 InstCombineWorklist() {}
98
99 bool isEmpty() const { return Worklist.empty(); }
100
101 /// Add - Add the specified instruction to the worklist if it isn't already
102 /// in it.
103 void Add(Instruction *I) {
Jeffrey Yasskin43069632009-10-08 00:12:24 +0000104 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
105 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +0000106 Worklist.push_back(I);
Jeffrey Yasskin43069632009-10-08 00:12:24 +0000107 }
Chris Lattner873ff012009-08-30 05:55:36 +0000108 }
109
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000110 void AddValue(Value *V) {
111 if (Instruction *I = dyn_cast<Instruction>(V))
112 Add(I);
113 }
114
Chris Lattner67f7d542009-10-12 03:58:40 +0000115 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
116 /// which should only be done when the worklist is empty and when the group
117 /// has no duplicates.
118 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
119 assert(Worklist.empty() && "Worklist must be empty to add initial group");
120 Worklist.reserve(NumEntries+16);
121 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
122 for (; NumEntries; --NumEntries) {
123 Instruction *I = List[NumEntries-1];
124 WorklistMap.insert(std::make_pair(I, Worklist.size()));
125 Worklist.push_back(I);
126 }
127 }
128
Chris Lattner7a1e9242009-08-30 06:13:40 +0000129 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000130 void Remove(Instruction *I) {
131 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
132 if (It == WorklistMap.end()) return; // Not in worklist.
133
134 // Don't bother moving everything down, just null out the slot.
135 Worklist[It->second] = 0;
136
137 WorklistMap.erase(It);
138 }
139
140 Instruction *RemoveOne() {
141 Instruction *I = Worklist.back();
142 Worklist.pop_back();
143 WorklistMap.erase(I);
144 return I;
145 }
146
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000147 /// AddUsersToWorkList - When an instruction is simplified, add all users of
148 /// the instruction to the work lists because they might get more simplified
149 /// now.
150 ///
151 void AddUsersToWorkList(Instruction &I) {
152 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
153 UI != UE; ++UI)
154 Add(cast<Instruction>(*UI));
155 }
156
Chris Lattner873ff012009-08-30 05:55:36 +0000157
158 /// Zap - check that the worklist is empty and nuke the backing store for
159 /// the map if it is large.
160 void Zap() {
161 assert(WorklistMap.empty() && "Worklist empty, but map not?");
162
163 // Do an explicit clear, this shrinks the map if needed.
164 WorklistMap.clear();
165 }
166 };
167} // end anonymous namespace.
168
169
170namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000171 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
172 /// just like the normal insertion helper, but also adds any new instructions
173 /// to the instcombine worklist.
174 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
175 InstCombineWorklist &Worklist;
176 public:
177 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
178
179 void InsertHelper(Instruction *I, const Twine &Name,
180 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
181 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
182 Worklist.Add(I);
183 }
184 };
185} // end anonymous namespace
186
187
188namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000189 class InstCombiner : public FunctionPass,
190 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000191 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000192 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000193 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000194 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000195 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000196 InstCombineWorklist Worklist;
197
Chris Lattner74381062009-08-30 07:44:24 +0000198 /// Builder - This is an IRBuilder that automatically inserts new
199 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +0000200 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000201 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000202
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000203 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000204 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000205
Owen Andersone922c022009-07-22 00:24:57 +0000206 LLVMContext *Context;
207 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000208
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000209 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000210 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000211
212 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000213
Chris Lattner97e52e42002-04-28 21:27:06 +0000214 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000215 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000216 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000217 }
218
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000219 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000220
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000221 // Visitation implementation - Implement instruction combining for different
222 // instruction types. The semantics are as follows:
223 // Return Value:
224 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000225 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000226 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000227 //
Chris Lattner7e708292002-06-25 16:13:24 +0000228 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000229 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner092543c2009-11-04 08:05:20 +0000230 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Chris Lattner7e708292002-06-25 16:13:24 +0000231 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000232 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000233 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000234 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000235 Instruction *visitURem(BinaryOperator &I);
236 Instruction *visitSRem(BinaryOperator &I);
237 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000238 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000239 Instruction *commonRemTransforms(BinaryOperator &I);
240 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000241 Instruction *commonDivTransforms(BinaryOperator &I);
242 Instruction *commonIDivTransforms(BinaryOperator &I);
243 Instruction *visitUDiv(BinaryOperator &I);
244 Instruction *visitSDiv(BinaryOperator &I);
245 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000246 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000247 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000248 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000249 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000250 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000251 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000252 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000253 Instruction *visitOr (BinaryOperator &I);
254 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000255 Instruction *visitShl(BinaryOperator &I);
256 Instruction *visitAShr(BinaryOperator &I);
257 Instruction *visitLShr(BinaryOperator &I);
258 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000259 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
260 Constant *RHSC);
Chris Lattner1f12e442010-01-02 08:12:04 +0000261 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
Chris Lattnerdf3d63b2010-01-02 22:08:28 +0000262 GlobalVariable *GV, CmpInst &ICI,
263 ConstantInt *AndCst = 0);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000264 Instruction *visitFCmpInst(FCmpInst &I);
265 Instruction *visitICmpInst(ICmpInst &I);
266 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000267 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
268 Instruction *LHS,
269 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000270 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
271 ConstantInt *DivRHS);
Chris Lattner2799baf2009-12-21 03:19:28 +0000272 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +0000273 ICmpInst::Predicate Pred, Value *TheAdd);
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000274 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000275 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000276 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000277 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000278 Instruction *commonCastTransforms(CastInst &CI);
279 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000280 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000281 Instruction *visitTrunc(TruncInst &CI);
282 Instruction *visitZExt(ZExtInst &CI);
283 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000284 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000285 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000286 Instruction *visitFPToUI(FPToUIInst &FI);
287 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000288 Instruction *visitUIToFP(CastInst &CI);
289 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000290 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000291 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000292 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000293 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
294 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000295 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000296 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
297 Value *A, Value *B, Instruction &Outer,
298 SelectPatternFlavor SPF2, Value *C);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000299 Instruction *visitSelectInst(SelectInst &SI);
300 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000301 Instruction *visitCallInst(CallInst &CI);
302 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner9956c052009-11-08 19:23:30 +0000303
304 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Chris Lattner7e708292002-06-25 16:13:24 +0000305 Instruction *visitPHINode(PHINode &PN);
306 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000307 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000308 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000309 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000310 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000311 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000312 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000313 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000314 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000315 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000316 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000317
318 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000319 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000320
Chris Lattner9fe38862003-06-19 17:00:31 +0000321 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000322 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000323 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000324 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000325 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
326 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000327 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000328 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
329
Chris Lattner9fe38862003-06-19 17:00:31 +0000330
Chris Lattner28977af2004-04-05 01:30:19 +0000331 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000332 // InsertNewInstBefore - insert an instruction New before instruction Old
333 // in the program. Add the new instruction to the worklist.
334 //
Chris Lattner955f3312004-09-28 21:48:02 +0000335 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000336 assert(New && New->getParent() == 0 &&
337 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000338 BasicBlock *BB = Old.getParent();
339 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000340 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000341 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000342 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000343
Chris Lattner8b170942002-08-09 23:47:40 +0000344 // ReplaceInstUsesWith - This method is to be used when an instruction is
345 // found to be dead, replacable with another preexisting expression. Here
346 // we add all uses of I to the worklist, replace all uses of I with the new
347 // value, then return I, so that the inst combiner will know that I was
348 // modified.
349 //
350 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000351 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000352
353 // If we are replacing the instruction with itself, this must be in a
354 // segment of unreachable code, so just clobber the instruction.
355 if (&I == V)
356 V = UndefValue::get(I.getType());
357
358 I.replaceAllUsesWith(V);
359 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000360 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000361
362 // EraseInstFromFunction - When dealing with an instruction that has side
363 // effects or produces a void value, we can't rely on DCE to delete the
364 // instruction. Instead, visit methods should return the value returned by
365 // this function.
366 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000367 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000368
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000369 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000370 // Make sure that we reprocess all operands now that we reduced their
371 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000372 if (I.getNumOperands() < 8) {
373 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
374 if (Instruction *Op = dyn_cast<Instruction>(*i))
375 Worklist.Add(Op);
376 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000377 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000378 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000379 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000380 return 0; // Don't do anything with FI
381 }
Chris Lattner173234a2008-06-02 01:18:21 +0000382
383 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
384 APInt &KnownOne, unsigned Depth = 0) const {
385 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
386 }
387
388 bool MaskedValueIsZero(Value *V, const APInt &Mask,
389 unsigned Depth = 0) const {
390 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
391 }
392 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
393 return llvm::ComputeNumSignBits(Op, TD, Depth);
394 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000395
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000396 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000397
Reid Spencere4d87aa2006-12-23 06:05:41 +0000398 /// SimplifyCommutative - This performs a few simplifications for
399 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000400 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000401
Chris Lattner886ab6c2009-01-31 08:15:18 +0000402 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
403 /// based on the demanded bits.
404 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
405 APInt& KnownZero, APInt& KnownOne,
406 unsigned Depth);
407 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000408 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000409 unsigned Depth=0);
410
411 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
412 /// SimplifyDemandedBits knows about. See if the instruction has any
413 /// properties that allow us to simplify its operands.
414 bool SimplifyDemandedInstructionBits(Instruction &Inst);
415
Evan Cheng388df622009-02-03 10:05:09 +0000416 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
417 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000418
Chris Lattner5d1704d2009-09-27 19:57:57 +0000419 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
420 // which has a PHI node as operand #0, see if we can fold the instruction
421 // into the PHI (which is only possible if all operands to the PHI are
422 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000423 //
424 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
425 // that would normally be unprofitable because they strongly encourage jump
426 // threading.
427 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000428
Chris Lattnerbac32862004-11-14 19:13:23 +0000429 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
430 // operator and they all are only used by the PHI, PHI together their
431 // inputs, and do the operation once, to the result of the PHI.
432 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000433 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000434 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner751a3622009-11-01 20:04:24 +0000435 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000436
Chris Lattner7da52b22006-11-01 04:51:18 +0000437
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000438 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
439 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000440
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000441 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000442 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000443 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000444 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000445 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000446 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000447 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000448 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000449 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000450
Chris Lattnerafe91a52006-06-15 19:07:26 +0000451
Reid Spencerc55b2432006-12-13 18:21:21 +0000452 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000453
Dan Gohman6de29f82009-06-15 22:12:54 +0000454 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000455 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000456 unsigned GetOrEnforceKnownAlignment(Value *V,
457 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000458
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000459 };
Chris Lattner873ff012009-08-30 05:55:36 +0000460} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000461
Dan Gohman844731a2008-05-13 00:00:25 +0000462char InstCombiner::ID = 0;
463static RegisterPass<InstCombiner>
464X("instcombine", "Combine redundant instructions");
465
Chris Lattner4f98c562003-03-10 21:43:22 +0000466// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000467// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000468static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000469 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000470 if (BinaryOperator::isNeg(V) ||
471 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000472 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000473 return 3;
474 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000475 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000476 if (isa<Argument>(V)) return 3;
477 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000478}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000479
Chris Lattnerc8802d22003-03-11 00:12:48 +0000480// isOnlyUse - Return true if this instruction will be deleted if we stop using
481// it.
482static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000483 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000484}
485
Chris Lattner4cb170c2004-02-23 06:38:22 +0000486// getPromotedType - Return the specified type promoted as it would be to pass
487// though a va_arg area...
488static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000489 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
490 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000491 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000492 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000493 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000494}
495
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000496/// ShouldChangeType - Return true if it is desirable to convert a computation
497/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
498/// type for example, or from a smaller to a larger illegal type.
499static bool ShouldChangeType(const Type *From, const Type *To,
500 const TargetData *TD) {
501 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
502
503 // If we don't have TD, we don't know if the source/dest are legal.
504 if (!TD) return false;
505
506 unsigned FromWidth = From->getPrimitiveSizeInBits();
507 unsigned ToWidth = To->getPrimitiveSizeInBits();
508 bool FromLegal = TD->isLegalInteger(FromWidth);
509 bool ToLegal = TD->isLegalInteger(ToWidth);
510
511 // If this is a legal integer from type, and the result would be an illegal
512 // type, don't do the transformation.
513 if (FromLegal && !ToLegal)
514 return false;
515
516 // Otherwise, if both are illegal, do not increase the size of the result. We
517 // do allow things like i160 -> i64, but not i64 -> i160.
518 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
519 return false;
520
521 return true;
522}
523
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000524/// getBitCastOperand - If the specified operand is a CastInst, a constant
525/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
526/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000527static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000528 if (Operator *O = dyn_cast<Operator>(V)) {
529 if (O->getOpcode() == Instruction::BitCast)
530 return O->getOperand(0);
531 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
532 if (GEP->hasAllZeroIndices())
533 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000534 }
Chris Lattnereed48272005-09-13 00:40:14 +0000535 return 0;
536}
537
Reid Spencer3da59db2006-11-27 01:05:10 +0000538/// This function is a wrapper around CastInst::isEliminableCastPair. It
539/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000540static Instruction::CastOps
541isEliminableCastPair(
542 const CastInst *CI, ///< The first cast instruction
543 unsigned opcode, ///< The opcode of the second cast instruction
544 const Type *DstTy, ///< The target type for the second cast instruction
545 TargetData *TD ///< The target data for pointer size
546) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000547
Reid Spencer3da59db2006-11-27 01:05:10 +0000548 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
549 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000550
Reid Spencer3da59db2006-11-27 01:05:10 +0000551 // Get the opcodes of the two Cast instructions
552 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
553 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000554
Chris Lattnera0e69692009-03-24 18:35:40 +0000555 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000556 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000557 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000558
559 // We don't want to form an inttoptr or ptrtoint that converts to an integer
560 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000561 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000562 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000563 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000564 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000565 Res = 0;
566
567 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000568}
569
570/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
571/// in any code being generated. It does not require codegen if V is simple
572/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000573static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
574 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000575 if (V->getType() == Ty || isa<Constant>(V)) return false;
576
Chris Lattner01575b72006-05-25 23:24:33 +0000577 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000578 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000579 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000580 return false;
581 return true;
582}
583
Chris Lattner4f98c562003-03-10 21:43:22 +0000584// SimplifyCommutative - This performs a few simplifications for commutative
585// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000586//
Chris Lattner4f98c562003-03-10 21:43:22 +0000587// 1. Order operands such that they are listed from right (least complex) to
588// left (most complex). This puts constants before unary operators before
589// binary operators.
590//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000591// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
592// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000593//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000594bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000595 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000596 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000597 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000598
Chris Lattner4f98c562003-03-10 21:43:22 +0000599 if (!I.isAssociative()) return Changed;
600 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000601 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
602 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
603 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000604 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000605 cast<Constant>(I.getOperand(1)),
606 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000607 I.setOperand(0, Op->getOperand(0));
608 I.setOperand(1, Folded);
609 return true;
610 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
611 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
612 isOnlyUse(Op) && isOnlyUse(Op1)) {
613 Constant *C1 = cast<Constant>(Op->getOperand(1));
614 Constant *C2 = cast<Constant>(Op1->getOperand(1));
615
616 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000617 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000618 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000619 Op1->getOperand(0),
620 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000621 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000622 I.setOperand(0, New);
623 I.setOperand(1, Folded);
624 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000625 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000626 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000627 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000628}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000629
Chris Lattner8d969642003-03-10 23:06:50 +0000630// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
631// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000632//
Dan Gohman186a6362009-08-12 16:04:34 +0000633static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000634 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000635 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000636
Chris Lattner0ce85802004-12-14 20:08:06 +0000637 // Constants can be considered to be negated values if they can be folded.
638 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000639 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000640
641 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
642 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000643 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000644
Chris Lattner8d969642003-03-10 23:06:50 +0000645 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000646}
647
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000648// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
649// instruction if the LHS is a constant negative zero (which is the 'negate'
650// form).
651//
Dan Gohman186a6362009-08-12 16:04:34 +0000652static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000653 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000654 return BinaryOperator::getFNegArgument(V);
655
656 // Constants can be considered to be negated values if they can be folded.
657 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000658 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000659
660 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
661 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000662 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000663
664 return 0;
665}
666
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000667/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
668/// returning the kind and providing the out parameter results if we
669/// successfully match.
670static SelectPatternFlavor
671MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
672 SelectInst *SI = dyn_cast<SelectInst>(V);
673 if (SI == 0) return SPF_UNKNOWN;
674
675 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
676 if (ICI == 0) return SPF_UNKNOWN;
677
678 LHS = ICI->getOperand(0);
679 RHS = ICI->getOperand(1);
680
681 // (icmp X, Y) ? X : Y
682 if (SI->getTrueValue() == ICI->getOperand(0) &&
683 SI->getFalseValue() == ICI->getOperand(1)) {
684 switch (ICI->getPredicate()) {
685 default: return SPF_UNKNOWN; // Equality.
686 case ICmpInst::ICMP_UGT:
687 case ICmpInst::ICMP_UGE: return SPF_UMAX;
688 case ICmpInst::ICMP_SGT:
689 case ICmpInst::ICMP_SGE: return SPF_SMAX;
690 case ICmpInst::ICMP_ULT:
691 case ICmpInst::ICMP_ULE: return SPF_UMIN;
692 case ICmpInst::ICMP_SLT:
693 case ICmpInst::ICMP_SLE: return SPF_SMIN;
694 }
695 }
696
697 // (icmp X, Y) ? Y : X
698 if (SI->getTrueValue() == ICI->getOperand(1) &&
699 SI->getFalseValue() == ICI->getOperand(0)) {
700 switch (ICI->getPredicate()) {
701 default: return SPF_UNKNOWN; // Equality.
702 case ICmpInst::ICMP_UGT:
703 case ICmpInst::ICMP_UGE: return SPF_UMIN;
704 case ICmpInst::ICMP_SGT:
705 case ICmpInst::ICMP_SGE: return SPF_SMIN;
706 case ICmpInst::ICMP_ULT:
707 case ICmpInst::ICMP_ULE: return SPF_UMAX;
708 case ICmpInst::ICMP_SLT:
709 case ICmpInst::ICMP_SLE: return SPF_SMAX;
710 }
711 }
712
713 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
714
715 return SPF_UNKNOWN;
716}
717
Chris Lattner48b59ec2009-10-26 15:40:07 +0000718/// isFreeToInvert - Return true if the specified value is free to invert (apply
719/// ~ to). This happens in cases where the ~ can be eliminated.
720static inline bool isFreeToInvert(Value *V) {
721 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000722 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000723 return true;
724
725 // Constants can be considered to be not'ed values.
726 if (isa<ConstantInt>(V))
727 return true;
728
729 // Compares can be inverted if they have a single use.
730 if (CmpInst *CI = dyn_cast<CmpInst>(V))
731 return CI->hasOneUse();
732
733 return false;
734}
735
736static inline Value *dyn_castNotVal(Value *V) {
737 // If this is not(not(x)) don't return that this is a not: we want the two
738 // not's to be folded first.
739 if (BinaryOperator::isNot(V)) {
740 Value *Operand = BinaryOperator::getNotArgument(V);
741 if (!isFreeToInvert(Operand))
742 return Operand;
743 }
Chris Lattner8d969642003-03-10 23:06:50 +0000744
745 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000746 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000747 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000748 return 0;
749}
750
Chris Lattner48b59ec2009-10-26 15:40:07 +0000751
752
Chris Lattnerc8802d22003-03-11 00:12:48 +0000753// dyn_castFoldableMul - If this value is a multiply that can be folded into
754// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000755// non-constant operand of the multiply, and set CST to point to the multiplier.
756// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000757//
Dan Gohman186a6362009-08-12 16:04:34 +0000758static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000759 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000760 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000761 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000762 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000763 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000764 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000765 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000766 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000767 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000768 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000769 CST = ConstantInt::get(V->getType()->getContext(),
770 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000771 return I->getOperand(0);
772 }
773 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000774 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000775}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000776
Reid Spencer7177c3a2007-03-25 05:33:51 +0000777/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000778static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000779 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000780 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000781}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000782/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000783static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000784 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000785 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000786}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000787/// MultiplyOverflows - True if the multiply can not be expressed in an int
788/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000789static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000790 uint32_t W = C1->getBitWidth();
791 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
792 if (sign) {
793 LHSExt.sext(W * 2);
794 RHSExt.sext(W * 2);
795 } else {
796 LHSExt.zext(W * 2);
797 RHSExt.zext(W * 2);
798 }
799
800 APInt MulExt = LHSExt * RHSExt;
801
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000802 if (!sign)
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000803 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000804
805 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
806 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
807 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000808}
Chris Lattner955f3312004-09-28 21:48:02 +0000809
Reid Spencere7816b52007-03-08 01:52:58 +0000810
Chris Lattner255d8912006-02-11 09:31:47 +0000811/// ShrinkDemandedConstant - Check to see if the specified operand of the
812/// specified instruction is a constant integer. If so, check to see if there
813/// are any bits set in the constant that are not demanded. If so, shrink the
814/// constant and return true.
815static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000816 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000817 assert(I && "No instruction?");
818 assert(OpNo < I->getNumOperands() && "Operand index too large");
819
820 // If the operand is not a constant integer, nothing to do.
821 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
822 if (!OpC) return false;
823
824 // If there are no bits set that aren't demanded, nothing to do.
825 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
826 if ((~Demanded & OpC->getValue()) == 0)
827 return false;
828
829 // This instruction is producing bits that are not demanded. Shrink the RHS.
830 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000831 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000832 return true;
833}
834
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000835// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
836// set of known zero and one bits, compute the maximum and minimum values that
837// could have the specified known zero and known one bits, returning them in
838// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000839static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000840 const APInt& KnownOne,
841 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000842 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
843 KnownZero.getBitWidth() == Min.getBitWidth() &&
844 KnownZero.getBitWidth() == Max.getBitWidth() &&
845 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000846 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000847
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000848 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
849 // bit if it is unknown.
850 Min = KnownOne;
851 Max = KnownOne|UnknownBits;
852
Dan Gohman1c8491e2009-04-25 17:12:48 +0000853 if (UnknownBits.isNegative()) { // Sign bit is unknown
854 Min.set(Min.getBitWidth()-1);
855 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000856 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000857}
858
859// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
860// a set of known zero and one bits, compute the maximum and minimum values that
861// could have the specified known zero and known one bits, returning them in
862// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000863static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000864 const APInt &KnownOne,
865 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000866 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
867 KnownZero.getBitWidth() == Min.getBitWidth() &&
868 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000869 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000870 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000871
872 // The minimum value is when the unknown bits are all zeros.
873 Min = KnownOne;
874 // The maximum value is when the unknown bits are all ones.
875 Max = KnownOne|UnknownBits;
876}
Chris Lattner255d8912006-02-11 09:31:47 +0000877
Chris Lattner886ab6c2009-01-31 08:15:18 +0000878/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
879/// SimplifyDemandedBits knows about. See if the instruction has any
880/// properties that allow us to simplify its operands.
881bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000882 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000883 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
884 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
885
886 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
887 KnownZero, KnownOne, 0);
888 if (V == 0) return false;
889 if (V == &Inst) return true;
890 ReplaceInstUsesWith(Inst, V);
891 return true;
892}
893
894/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
895/// specified instruction operand if possible, updating it in place. It returns
896/// true if it made any change and false otherwise.
897bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
898 APInt &KnownZero, APInt &KnownOne,
899 unsigned Depth) {
900 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
901 KnownZero, KnownOne, Depth);
902 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000903 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000904 return true;
905}
906
907
908/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
909/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000910/// that only the bits set in DemandedMask of the result of V are ever used
911/// downstream. Consequently, depending on the mask and V, it may be possible
912/// to replace V with a constant or one of its operands. In such cases, this
913/// function does the replacement and returns true. In all other cases, it
914/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000915/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000916/// to be zero in the expression. These are provided to potentially allow the
917/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
918/// the expression. KnownOne and KnownZero always follow the invariant that
919/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
920/// the bits in KnownOne and KnownZero may only be accurate for those bits set
921/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
922/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000923///
924/// This returns null if it did not change anything and it permits no
925/// simplification. This returns V itself if it did some simplification of V's
926/// operands based on the information about what bits are demanded. This returns
927/// some other non-null value if it found out that V is equal to another value
928/// in the context where the specified bits are demanded, but not for all users.
929Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
930 APInt &KnownZero, APInt &KnownOne,
931 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000932 assert(V != 0 && "Null pointer of Value???");
933 assert(Depth <= 6 && "Limit Search Depth");
934 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000935 const Type *VTy = V->getType();
936 assert((TD || !isa<PointerType>(VTy)) &&
937 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000938 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
939 (!VTy->isIntOrIntVector() ||
940 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000941 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000942 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000943 "Value *V, DemandedMask, KnownZero and KnownOne "
944 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000945 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
946 // We know all of the bits for a constant!
947 KnownOne = CI->getValue() & DemandedMask;
948 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000949 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000950 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000951 if (isa<ConstantPointerNull>(V)) {
952 // We know all of the bits for a constant!
953 KnownOne.clear();
954 KnownZero = DemandedMask;
955 return 0;
956 }
957
Chris Lattner08d2cc72009-01-31 07:26:06 +0000958 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000959 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000960 if (DemandedMask == 0) { // Not demanding any bits from V.
961 if (isa<UndefValue>(V))
962 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000963 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000964 }
965
Chris Lattner4598c942009-01-31 08:24:16 +0000966 if (Depth == 6) // Limit search depth.
967 return 0;
968
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000969 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
970 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
971
Dan Gohman1c8491e2009-04-25 17:12:48 +0000972 Instruction *I = dyn_cast<Instruction>(V);
973 if (!I) {
974 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
975 return 0; // Only analyze instructions.
976 }
977
Chris Lattner4598c942009-01-31 08:24:16 +0000978 // If there are multiple uses of this value and we aren't at the root, then
979 // we can't do any simplifications of the operands, because DemandedMask
980 // only reflects the bits demanded by *one* of the users.
981 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000982 // Despite the fact that we can't simplify this instruction in all User's
983 // context, we can at least compute the knownzero/knownone bits, and we can
984 // do simplifications that apply to *just* the one user if we know that
985 // this instruction has a simpler value in that context.
986 if (I->getOpcode() == Instruction::And) {
987 // If either the LHS or the RHS are Zero, the result is zero.
988 ComputeMaskedBits(I->getOperand(1), DemandedMask,
989 RHSKnownZero, RHSKnownOne, Depth+1);
990 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
991 LHSKnownZero, LHSKnownOne, Depth+1);
992
993 // If all of the demanded bits are known 1 on one side, return the other.
994 // These bits cannot contribute to the result of the 'and' in this
995 // context.
996 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
997 (DemandedMask & ~LHSKnownZero))
998 return I->getOperand(0);
999 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1000 (DemandedMask & ~RHSKnownZero))
1001 return I->getOperand(1);
1002
1003 // If all of the demanded bits in the inputs are known zeros, return zero.
1004 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +00001005 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +00001006
1007 } else if (I->getOpcode() == Instruction::Or) {
1008 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1009 // only bits from X or Y are demanded.
1010
1011 // If either the LHS or the RHS are One, the result is One.
1012 ComputeMaskedBits(I->getOperand(1), DemandedMask,
1013 RHSKnownZero, RHSKnownOne, Depth+1);
1014 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1015 LHSKnownZero, LHSKnownOne, Depth+1);
1016
1017 // If all of the demanded bits are known zero on one side, return the
1018 // other. These bits cannot contribute to the result of the 'or' in this
1019 // context.
1020 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1021 (DemandedMask & ~LHSKnownOne))
1022 return I->getOperand(0);
1023 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1024 (DemandedMask & ~RHSKnownOne))
1025 return I->getOperand(1);
1026
1027 // If all of the potentially set bits on one side are known to be set on
1028 // the other side, just use the 'other' side.
1029 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1030 (DemandedMask & (~RHSKnownZero)))
1031 return I->getOperand(0);
1032 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1033 (DemandedMask & (~LHSKnownZero)))
1034 return I->getOperand(1);
1035 }
1036
Chris Lattner4598c942009-01-31 08:24:16 +00001037 // Compute the KnownZero/KnownOne bits to simplify things downstream.
1038 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
1039 return 0;
1040 }
1041
1042 // If this is the root being simplified, allow it to have multiple uses,
1043 // just set the DemandedMask to all bits so that we can try to simplify the
1044 // operands. This allows visitTruncInst (for example) to simplify the
1045 // operand of a trunc without duplicating all the logic below.
1046 if (Depth == 0 && !V->hasOneUse())
1047 DemandedMask = APInt::getAllOnesValue(BitWidth);
1048
Reid Spencer8cb68342007-03-12 17:25:59 +00001049 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001050 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001051 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +00001052 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001053 case Instruction::And:
1054 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001055 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1056 RHSKnownZero, RHSKnownOne, Depth+1) ||
1057 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +00001058 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001059 return I;
1060 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1061 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001062
1063 // If all of the demanded bits are known 1 on one side, return the other.
1064 // These bits cannot contribute to the result of the 'and'.
1065 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1066 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001068 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1069 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001070 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001071
1072 // If all of the demanded bits in the inputs are known zeros, return zero.
1073 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +00001074 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +00001075
1076 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001077 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001079
1080 // Output known-1 bits are only known if set in both the LHS & RHS.
1081 RHSKnownOne &= LHSKnownOne;
1082 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1083 RHSKnownZero |= LHSKnownZero;
1084 break;
1085 case Instruction::Or:
1086 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001087 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1088 RHSKnownZero, RHSKnownOne, Depth+1) ||
1089 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +00001090 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001091 return I;
1092 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1093 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001094
1095 // If all of the demanded bits are known zero on one side, return the other.
1096 // These bits cannot contribute to the result of the 'or'.
1097 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1098 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001099 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001100 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1101 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001102 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001103
1104 // If all of the potentially set bits on one side are known to be set on
1105 // the other side, just use the 'other' side.
1106 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1107 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001108 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001109 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1110 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001111 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001112
1113 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001114 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001115 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001116
1117 // Output known-0 bits are only known if clear in both the LHS & RHS.
1118 RHSKnownZero &= LHSKnownZero;
1119 // Output known-1 are known to be set if set in either the LHS | RHS.
1120 RHSKnownOne |= LHSKnownOne;
1121 break;
1122 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001123 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1124 RHSKnownZero, RHSKnownOne, Depth+1) ||
1125 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001126 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001127 return I;
1128 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1129 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001130
1131 // If all of the demanded bits are known zero on one side, return the other.
1132 // These bits cannot contribute to the result of the 'xor'.
1133 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001134 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001136 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001137
1138 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1139 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1140 (RHSKnownOne & LHSKnownOne);
1141 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1142 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1143 (RHSKnownOne & LHSKnownZero);
1144
1145 // If all of the demanded bits are known to be zero on one side or the
1146 // other, turn this into an *inclusive* or.
1147 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001148 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1149 Instruction *Or =
1150 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1151 I->getName());
1152 return InsertNewInstBefore(Or, *I);
1153 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001154
1155 // If all of the demanded bits on one side are known, and all of the set
1156 // bits on that side are also known to be set on the other side, turn this
1157 // into an AND, as we know the bits will be cleared.
1158 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1159 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1160 // all known
1161 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001162 Constant *AndC = Constant::getIntegerValue(VTy,
1163 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001164 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001165 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001166 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001167 }
1168 }
1169
1170 // If the RHS is a constant, see if we can simplify it.
1171 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001172 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001173 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001174
Chris Lattnerd0883142009-10-11 22:22:13 +00001175 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1176 // are flipping are known to be set, then the xor is just resetting those
1177 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1178 // simplifying both of them.
1179 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1180 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1181 isa<ConstantInt>(I->getOperand(1)) &&
1182 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1183 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1184 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1185 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1186 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1187
1188 Constant *AndC =
1189 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1190 Instruction *NewAnd =
1191 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1192 InsertNewInstBefore(NewAnd, *I);
1193
1194 Constant *XorC =
1195 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1196 Instruction *NewXor =
1197 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1198 return InsertNewInstBefore(NewXor, *I);
1199 }
1200
1201
Reid Spencer8cb68342007-03-12 17:25:59 +00001202 RHSKnownZero = KnownZeroOut;
1203 RHSKnownOne = KnownOneOut;
1204 break;
1205 }
1206 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001207 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1208 RHSKnownZero, RHSKnownOne, Depth+1) ||
1209 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001210 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001211 return I;
1212 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1213 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001214
1215 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001216 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1217 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001218 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001219
1220 // Only known if known in both the LHS and RHS.
1221 RHSKnownOne &= LHSKnownOne;
1222 RHSKnownZero &= LHSKnownZero;
1223 break;
1224 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001225 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001226 DemandedMask.zext(truncBf);
1227 RHSKnownZero.zext(truncBf);
1228 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001229 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001230 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001231 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 DemandedMask.trunc(BitWidth);
1233 RHSKnownZero.trunc(BitWidth);
1234 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001235 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001236 break;
1237 }
1238 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001239 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001240 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001241
1242 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1243 if (const VectorType *SrcVTy =
1244 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1245 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1246 // Don't touch a bitcast between vectors of different element counts.
1247 return false;
1248 } else
1249 // Don't touch a scalar-to-vector bitcast.
1250 return false;
1251 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1252 // Don't touch a vector-to-scalar bitcast.
1253 return false;
1254
Chris Lattner886ab6c2009-01-31 08:15:18 +00001255 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001256 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001257 return I;
1258 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 break;
1260 case Instruction::ZExt: {
1261 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001262 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001263
Zhou Shengd48653a2007-03-29 04:45:55 +00001264 DemandedMask.trunc(SrcBitWidth);
1265 RHSKnownZero.trunc(SrcBitWidth);
1266 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001267 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001268 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001269 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 DemandedMask.zext(BitWidth);
1271 RHSKnownZero.zext(BitWidth);
1272 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001273 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001274 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001275 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001276 break;
1277 }
1278 case Instruction::SExt: {
1279 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001280 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001281
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001283 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001284
Zhou Sheng01542f32007-03-29 02:26:30 +00001285 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001286 // If any of the sign extended bits are demanded, we know that the sign
1287 // bit is demanded.
1288 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001289 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001290
Zhou Shengd48653a2007-03-29 04:45:55 +00001291 InputDemandedBits.trunc(SrcBitWidth);
1292 RHSKnownZero.trunc(SrcBitWidth);
1293 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001294 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001295 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001296 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001297 InputDemandedBits.zext(BitWidth);
1298 RHSKnownZero.zext(BitWidth);
1299 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001300 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001301
1302 // If the sign bit of the input is known set or clear, then we know the
1303 // top bits of the result.
1304
1305 // If the input sign bit is known zero, or if the NewBits are not demanded
1306 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001307 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001308 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001309 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1310 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001311 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001312 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001313 }
1314 break;
1315 }
1316 case Instruction::Add: {
1317 // Figure out what the input bits are. If the top bits of the and result
1318 // are not demanded, then the add doesn't demand them from its input
1319 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001320 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001321
1322 // If there is a constant on the RHS, there are a variety of xformations
1323 // we can do.
1324 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1325 // If null, this should be simplified elsewhere. Some of the xforms here
1326 // won't work if the RHS is zero.
1327 if (RHS->isZero())
1328 break;
1329
1330 // If the top bit of the output is demanded, demand everything from the
1331 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001332 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001333
1334 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001335 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001336 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001337 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001338
1339 // If the RHS of the add has bits set that can't affect the input, reduce
1340 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001341 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001342 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001343
1344 // Avoid excess work.
1345 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1346 break;
1347
1348 // Turn it into OR if input bits are zero.
1349 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1350 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001351 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001352 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001353 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001354 }
1355
1356 // We can say something about the output known-zero and known-one bits,
1357 // depending on potential carries from the input constant and the
1358 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1359 // bits set and the RHS constant is 0x01001, then we know we have a known
1360 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1361
1362 // To compute this, we first compute the potential carry bits. These are
1363 // the bits which may be modified. I'm not aware of a better way to do
1364 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001365 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001366 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001367
1368 // Now that we know which bits have carries, compute the known-1/0 sets.
1369
1370 // Bits are known one if they are known zero in one operand and one in the
1371 // other, and there is no input carry.
1372 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1373 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1374
1375 // Bits are known zero if they are known zero in both operands and there
1376 // is no input carry.
1377 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1378 } else {
1379 // If the high-bits of this ADD are not demanded, then it does not demand
1380 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001381 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001382 // Right fill the mask of bits for this ADD to demand the most
1383 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001384 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001385 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1386 LHSKnownZero, LHSKnownOne, Depth+1) ||
1387 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001388 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001389 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001390 }
1391 }
1392 break;
1393 }
1394 case Instruction::Sub:
1395 // If the high-bits of this SUB are not demanded, then it does not demand
1396 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001397 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001398 // Right fill the mask of bits for this SUB to demand the most
1399 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001400 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001401 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001402 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1403 LHSKnownZero, LHSKnownOne, Depth+1) ||
1404 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001405 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001406 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001407 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001408 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1409 // the known zeros and ones.
1410 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001411 break;
1412 case Instruction::Shl:
1413 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001414 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001415 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001416 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001417 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001418 return I;
1419 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001420 RHSKnownZero <<= ShiftAmt;
1421 RHSKnownOne <<= ShiftAmt;
1422 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001423 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001424 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001425 }
1426 break;
1427 case Instruction::LShr:
1428 // For a logical shift right
1429 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001430 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001431
Reid Spencer8cb68342007-03-12 17:25:59 +00001432 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001433 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001434 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001435 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001436 return I;
1437 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001438 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1439 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001440 if (ShiftAmt) {
1441 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001442 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001443 RHSKnownZero |= HighBits; // high bits known zero.
1444 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001445 }
1446 break;
1447 case Instruction::AShr:
1448 // If this is an arithmetic shift right and only the low-bit is set, we can
1449 // always convert this into a logical shr, even if the shift amount is
1450 // variable. The low bit of the shift cannot be an input sign bit unless
1451 // the shift amount is >= the size of the datatype, which is undefined.
1452 if (DemandedMask == 1) {
1453 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001454 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001455 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001456 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001457 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001458
1459 // If the sign bit is the only bit demanded by this ashr, then there is no
1460 // need to do it, the shift doesn't change the high bit.
1461 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001462 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001463
1464 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001465 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001466
Reid Spencer8cb68342007-03-12 17:25:59 +00001467 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001468 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001469 // If any of the "high bits" are demanded, we should set the sign bit as
1470 // demanded.
1471 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1472 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001473 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001474 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001475 return I;
1476 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001477 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001478 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001479 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1480 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1481
1482 // Handle the sign bits.
1483 APInt SignBit(APInt::getSignBit(BitWidth));
1484 // Adjust to where it is now in the mask.
1485 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1486
1487 // If the input sign bit is known to be zero, or if none of the top bits
1488 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001489 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001490 (HighBits & ~DemandedMask) == HighBits) {
1491 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001492 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001493 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001494 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001495 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1496 RHSKnownOne |= HighBits;
1497 }
1498 }
1499 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001500 case Instruction::SRem:
1501 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001502 APInt RA = Rem->getValue().abs();
1503 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001504 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001505 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001506
Nick Lewycky8e394322008-11-02 02:41:50 +00001507 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001508 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001509 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001510 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001511 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001512
1513 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1514 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001515
1516 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001517
Chris Lattner886ab6c2009-01-31 08:15:18 +00001518 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001519 }
1520 }
1521 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001522 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001523 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1524 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001525 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1526 KnownZero2, KnownOne2, Depth+1) ||
1527 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001528 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001529 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001530
Chris Lattner455e9ab2009-01-21 18:09:24 +00001531 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001532 Leaders = std::max(Leaders,
1533 KnownZero2.countLeadingOnes());
1534 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001535 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001536 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001537 case Instruction::Call:
1538 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1539 switch (II->getIntrinsicID()) {
1540 default: break;
1541 case Intrinsic::bswap: {
1542 // If the only bits demanded come from one byte of the bswap result,
1543 // just shift the input byte into position to eliminate the bswap.
1544 unsigned NLZ = DemandedMask.countLeadingZeros();
1545 unsigned NTZ = DemandedMask.countTrailingZeros();
1546
1547 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1548 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1549 // have 14 leading zeros, round to 8.
1550 NLZ &= ~7;
1551 NTZ &= ~7;
1552 // If we need exactly one byte, we can do this transformation.
1553 if (BitWidth-NLZ-NTZ == 8) {
1554 unsigned ResultBit = NTZ;
1555 unsigned InputBit = BitWidth-NTZ-8;
1556
1557 // Replace this with either a left or right shift to get the byte into
1558 // the right place.
1559 Instruction *NewVal;
1560 if (InputBit > ResultBit)
1561 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001562 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001563 else
1564 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001565 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001566 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001567 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001568 }
1569
1570 // TODO: Could compute known zero/one bits based on the input.
1571 break;
1572 }
1573 }
1574 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001575 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001576 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001577 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001578
1579 // If the client is only demanding bits that we know, return the known
1580 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001581 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1582 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001583 return false;
1584}
1585
Chris Lattner867b99f2006-10-05 06:55:50 +00001586
Mon P Wangaeb06d22008-11-10 04:46:22 +00001587/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001588/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001589/// actually used by the caller. This method analyzes which elements of the
1590/// operand are undef and returns that information in UndefElts.
1591///
1592/// If the information about demanded elements can be used to simplify the
1593/// operation, the operation is simplified, then the resultant value is
1594/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001595Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1596 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001597 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001598 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001599 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001600 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001601
1602 if (isa<UndefValue>(V)) {
1603 // If the entire vector is undefined, just return this info.
1604 UndefElts = EltMask;
1605 return 0;
1606 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1607 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001608 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001609 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001610
Chris Lattner867b99f2006-10-05 06:55:50 +00001611 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001612 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1613 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001614 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001615
1616 std::vector<Constant*> Elts;
1617 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001618 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001619 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001620 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001621 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1622 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001623 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001624 } else { // Otherwise, defined.
1625 Elts.push_back(CP->getOperand(i));
1626 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001627
Chris Lattner867b99f2006-10-05 06:55:50 +00001628 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001629 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001630 return NewCP != CP ? NewCP : 0;
1631 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001632 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001633 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001634
1635 // Check if this is identity. If so, return 0 since we are not simplifying
1636 // anything.
1637 if (DemandedElts == ((1ULL << VWidth) -1))
1638 return 0;
1639
Reid Spencer9d6565a2007-02-15 02:26:10 +00001640 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001641 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001642 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001643 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001644 for (unsigned i = 0; i != VWidth; ++i) {
1645 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1646 Elts.push_back(Elt);
1647 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001648 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001649 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001650 }
1651
Dan Gohman488fbfc2008-09-09 18:11:14 +00001652 // Limit search depth.
1653 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001654 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001655
1656 // If multiple users are using the root value, procede with
1657 // simplification conservatively assuming that all elements
1658 // are needed.
1659 if (!V->hasOneUse()) {
1660 // Quit if we find multiple users of a non-root value though.
1661 // They'll be handled when it's their turn to be visited by
1662 // the main instcombine process.
1663 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001664 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001665 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001666
1667 // Conservatively assume that all elements are needed.
1668 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001669 }
1670
1671 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001672 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001673
1674 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001675 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001676 Value *TmpV;
1677 switch (I->getOpcode()) {
1678 default: break;
1679
1680 case Instruction::InsertElement: {
1681 // If this is a variable index, we don't know which element it overwrites.
1682 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001683 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001684 if (Idx == 0) {
1685 // Note that we can't propagate undef elt info, because we don't know
1686 // which elt is getting updated.
1687 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1688 UndefElts2, Depth+1);
1689 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1690 break;
1691 }
1692
1693 // If this is inserting an element that isn't demanded, remove this
1694 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001695 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001696 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1697 Worklist.Add(I);
1698 return I->getOperand(0);
1699 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001700
1701 // Otherwise, the element inserted overwrites whatever was there, so the
1702 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001703 APInt DemandedElts2 = DemandedElts;
1704 DemandedElts2.clear(IdxNo);
1705 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001706 UndefElts, Depth+1);
1707 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1708
1709 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001710 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001711 break;
1712 }
1713 case Instruction::ShuffleVector: {
1714 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001715 uint64_t LHSVWidth =
1716 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001717 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001718 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001719 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001720 unsigned MaskVal = Shuffle->getMaskValue(i);
1721 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001722 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001723 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001724 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001725 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001726 else
Evan Cheng388df622009-02-03 10:05:09 +00001727 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001728 }
1729 }
1730 }
1731
Nate Begeman7b254672009-02-11 22:36:25 +00001732 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001733 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001734 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001735 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1736
Nate Begeman7b254672009-02-11 22:36:25 +00001737 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001738 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1739 UndefElts3, Depth+1);
1740 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1741
1742 bool NewUndefElts = false;
1743 for (unsigned i = 0; i < VWidth; i++) {
1744 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001745 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001746 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001747 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001748 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001749 NewUndefElts = true;
1750 UndefElts.set(i);
1751 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001752 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001753 if (UndefElts3[MaskVal - LHSVWidth]) {
1754 NewUndefElts = true;
1755 UndefElts.set(i);
1756 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001757 }
1758 }
1759
1760 if (NewUndefElts) {
1761 // Add additional discovered undefs.
1762 std::vector<Constant*> Elts;
1763 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001764 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001765 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001766 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001767 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001768 Shuffle->getMaskValue(i)));
1769 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001770 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001771 MadeChange = true;
1772 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001773 break;
1774 }
Chris Lattner69878332007-04-14 22:29:23 +00001775 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001776 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001777 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1778 if (!VTy) break;
1779 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001780 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001781 unsigned Ratio;
1782
1783 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001784 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001785 // elements as are demanded of us.
1786 Ratio = 1;
1787 InputDemandedElts = DemandedElts;
1788 } else if (VWidth > InVWidth) {
1789 // Untested so far.
1790 break;
1791
1792 // If there are more elements in the result than there are in the source,
1793 // then an input element is live if any of the corresponding output
1794 // elements are live.
1795 Ratio = VWidth/InVWidth;
1796 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001797 if (DemandedElts[OutIdx])
1798 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001799 }
1800 } else {
1801 // Untested so far.
1802 break;
1803
1804 // If there are more elements in the source than there are in the result,
1805 // then an input element is live if the corresponding output element is
1806 // live.
1807 Ratio = InVWidth/VWidth;
1808 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001809 if (DemandedElts[InIdx/Ratio])
1810 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001811 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001812
Chris Lattner69878332007-04-14 22:29:23 +00001813 // div/rem demand all inputs, because they don't want divide by zero.
1814 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1815 UndefElts2, Depth+1);
1816 if (TmpV) {
1817 I->setOperand(0, TmpV);
1818 MadeChange = true;
1819 }
1820
1821 UndefElts = UndefElts2;
1822 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001823 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001824 // If there are more elements in the result than there are in the source,
1825 // then an output element is undef if the corresponding input element is
1826 // undef.
1827 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001828 if (UndefElts2[OutIdx/Ratio])
1829 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001830 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001831 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001832 // If there are more elements in the source than there are in the result,
1833 // then a result element is undef if all of the corresponding input
1834 // elements are undef.
1835 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1836 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001837 if (!UndefElts2[InIdx]) // Not undef?
1838 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001839 }
1840 break;
1841 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001842 case Instruction::And:
1843 case Instruction::Or:
1844 case Instruction::Xor:
1845 case Instruction::Add:
1846 case Instruction::Sub:
1847 case Instruction::Mul:
1848 // div/rem demand all inputs, because they don't want divide by zero.
1849 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1850 UndefElts, Depth+1);
1851 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1852 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1853 UndefElts2, Depth+1);
1854 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1855
1856 // Output elements are undefined if both are undefined. Consider things
1857 // like undef&0. The result is known zero, not undef.
1858 UndefElts &= UndefElts2;
1859 break;
1860
1861 case Instruction::Call: {
1862 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1863 if (!II) break;
1864 switch (II->getIntrinsicID()) {
1865 default: break;
1866
1867 // Binary vector operations that work column-wise. A dest element is a
1868 // function of the corresponding input elements from the two inputs.
1869 case Intrinsic::x86_sse_sub_ss:
1870 case Intrinsic::x86_sse_mul_ss:
1871 case Intrinsic::x86_sse_min_ss:
1872 case Intrinsic::x86_sse_max_ss:
1873 case Intrinsic::x86_sse2_sub_sd:
1874 case Intrinsic::x86_sse2_mul_sd:
1875 case Intrinsic::x86_sse2_min_sd:
1876 case Intrinsic::x86_sse2_max_sd:
1877 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1878 UndefElts, Depth+1);
1879 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1880 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1881 UndefElts2, Depth+1);
1882 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1883
1884 // If only the low elt is demanded and this is a scalarizable intrinsic,
1885 // scalarize it now.
1886 if (DemandedElts == 1) {
1887 switch (II->getIntrinsicID()) {
1888 default: break;
1889 case Intrinsic::x86_sse_sub_ss:
1890 case Intrinsic::x86_sse_mul_ss:
1891 case Intrinsic::x86_sse2_sub_sd:
1892 case Intrinsic::x86_sse2_mul_sd:
1893 // TODO: Lower MIN/MAX/ABS/etc
1894 Value *LHS = II->getOperand(1);
1895 Value *RHS = II->getOperand(2);
1896 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001897 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001898 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001899 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001900 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001901
1902 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001903 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001904 case Intrinsic::x86_sse_sub_ss:
1905 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001906 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001907 II->getName()), *II);
1908 break;
1909 case Intrinsic::x86_sse_mul_ss:
1910 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001911 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001912 II->getName()), *II);
1913 break;
1914 }
1915
1916 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001917 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001918 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001919 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001920 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001921 return New;
1922 }
1923 }
1924
1925 // Output elements are undefined if both are undefined. Consider things
1926 // like undef&0. The result is known zero, not undef.
1927 UndefElts &= UndefElts2;
1928 break;
1929 }
1930 break;
1931 }
1932 }
1933 return MadeChange ? I : 0;
1934}
1935
Dan Gohman45b4e482008-05-19 22:14:15 +00001936
Chris Lattner564a7272003-08-13 19:01:45 +00001937/// AssociativeOpt - Perform an optimization on an associative operator. This
1938/// function is designed to check a chain of associative operators for a
1939/// potential to apply a certain optimization. Since the optimization may be
1940/// applicable if the expression was reassociated, this checks the chain, then
1941/// reassociates the expression as necessary to expose the optimization
1942/// opportunity. This makes use of a special Functor, which must define
1943/// 'shouldApply' and 'apply' methods.
1944///
1945template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001946static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001947 unsigned Opcode = Root.getOpcode();
1948 Value *LHS = Root.getOperand(0);
1949
1950 // Quick check, see if the immediate LHS matches...
1951 if (F.shouldApply(LHS))
1952 return F.apply(Root);
1953
1954 // Otherwise, if the LHS is not of the same opcode as the root, return.
1955 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001956 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001957 // Should we apply this transform to the RHS?
1958 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1959
1960 // If not to the RHS, check to see if we should apply to the LHS...
1961 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1962 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1963 ShouldApply = true;
1964 }
1965
1966 // If the functor wants to apply the optimization to the RHS of LHSI,
1967 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1968 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001969 // Now all of the instructions are in the current basic block, go ahead
1970 // and perform the reassociation.
1971 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1972
1973 // First move the selected RHS to the LHS of the root...
1974 Root.setOperand(0, LHSI->getOperand(1));
1975
1976 // Make what used to be the LHS of the root be the user of the root...
1977 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001978 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001979 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001980 return 0;
1981 }
Chris Lattner65725312004-04-16 18:08:07 +00001982 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001983 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001984 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001985 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001986 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001987
1988 // Now propagate the ExtraOperand down the chain of instructions until we
1989 // get to LHSI.
1990 while (TmpLHSI != LHSI) {
1991 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001992 // Move the instruction to immediately before the chain we are
1993 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001994 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001995 ARI = NextLHSI;
1996
Chris Lattner564a7272003-08-13 19:01:45 +00001997 Value *NextOp = NextLHSI->getOperand(1);
1998 NextLHSI->setOperand(1, ExtraOperand);
1999 TmpLHSI = NextLHSI;
2000 ExtraOperand = NextOp;
2001 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002002
Chris Lattner564a7272003-08-13 19:01:45 +00002003 // Now that the instructions are reassociated, have the functor perform
2004 // the transformation...
2005 return F.apply(Root);
2006 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002007
Chris Lattner564a7272003-08-13 19:01:45 +00002008 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2009 }
2010 return 0;
2011}
2012
Dan Gohman844731a2008-05-13 00:00:25 +00002013namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002014
Nick Lewycky02d639f2008-05-23 04:34:58 +00002015// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00002016struct AddRHS {
2017 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00002018 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00002019 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2020 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00002021 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00002022 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002023 }
2024};
2025
2026// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2027// iff C1&C2 == 0
2028struct AddMaskingAnd {
2029 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00002030 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00002031 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002032 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00002033 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002034 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002035 }
2036 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002037 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002038 }
2039};
2040
Dan Gohman844731a2008-05-13 00:00:25 +00002041}
2042
Chris Lattner6e7ba452005-01-01 16:22:27 +00002043static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002044 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00002045 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00002046 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00002047
Chris Lattner2eefe512004-04-09 19:05:30 +00002048 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002049 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2050 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002051
Chris Lattner2eefe512004-04-09 19:05:30 +00002052 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2053 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00002054 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2055 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002056 }
2057
2058 Value *Op0 = SO, *Op1 = ConstOperand;
2059 if (!ConstIsRHS)
2060 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00002061
Chris Lattner6e7ba452005-01-01 16:22:27 +00002062 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00002063 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
2064 SO->getName()+".op");
2065 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
2066 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2067 SO->getName()+".cmp");
2068 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2069 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2070 SO->getName()+".cmp");
2071 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00002072}
2073
2074// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2075// constant as the other operand, try to fold the binary operator into the
2076// select arguments. This also works for Cast instructions, which obviously do
2077// not have a second operand.
2078static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2079 InstCombiner *IC) {
2080 // Don't modify shared select instructions
2081 if (!SI->hasOneUse()) return 0;
2082 Value *TV = SI->getOperand(1);
2083 Value *FV = SI->getOperand(2);
2084
2085 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002086 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00002087 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002088
Chris Lattner6e7ba452005-01-01 16:22:27 +00002089 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2090 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2091
Gabor Greif051a9502008-04-06 20:25:17 +00002092 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2093 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002094 }
2095 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002096}
2097
Chris Lattner4e998b22004-09-29 05:07:12 +00002098
Chris Lattner5d1704d2009-09-27 19:57:57 +00002099/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2100/// has a PHI node as operand #0, see if we can fold the instruction into the
2101/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002102///
2103/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2104/// that would normally be unprofitable because they strongly encourage jump
2105/// threading.
2106Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2107 bool AllowAggressive) {
2108 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002109 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002110 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002111 if (NumPHIValues == 0 ||
2112 // We normally only transform phis with a single use, unless we're trying
2113 // hard to make jump threading happen.
2114 (!PN->hasOneUse() && !AllowAggressive))
2115 return 0;
2116
2117
Chris Lattner5d1704d2009-09-27 19:57:57 +00002118 // Check to see if all of the operands of the PHI are simple constants
2119 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002120 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2121 // bail out. We don't do arbitrary constant expressions here because moving
2122 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002123 BasicBlock *NonConstBB = 0;
2124 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002125 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2126 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002127 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002128 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002129 NonConstBB = PN->getIncomingBlock(i);
2130
2131 // If the incoming non-constant value is in I's block, we have an infinite
2132 // loop.
2133 if (NonConstBB == I.getParent())
2134 return 0;
2135 }
2136
2137 // If there is exactly one non-constant value, we can insert a copy of the
2138 // operation in that block. However, if this is a critical edge, we would be
2139 // inserting the computation one some other paths (e.g. inside a loop). Only
2140 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002141 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002142 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2143 if (!BI || !BI->isUnconditional()) return 0;
2144 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002145
2146 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002147 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002148 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002149 InsertNewInstBefore(NewPN, *PN);
2150 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002151
2152 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002153 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2154 // We only currently try to fold the condition of a select when it is a phi,
2155 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002156 Value *TrueV = SI->getTrueValue();
2157 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002158 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002159 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002160 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002161 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2162 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002163 Value *InV = 0;
2164 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002165 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002166 } else {
2167 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002168 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2169 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002170 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002171 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002172 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002173 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002174 }
2175 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002176 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002177 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002178 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002179 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002180 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002181 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002182 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002183 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002184 } else {
2185 assert(PN->getIncomingBlock(i) == NonConstBB);
2186 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002187 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002188 PN->getIncomingValue(i), C, "phitmp",
2189 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002190 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002191 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002192 CI->getPredicate(),
2193 PN->getIncomingValue(i), C, "phitmp",
2194 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002195 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002196 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002197
2198 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002199 }
2200 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002201 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002202 } else {
2203 CastInst *CI = cast<CastInst>(&I);
2204 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002205 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002206 Value *InV;
2207 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002208 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002209 } else {
2210 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002211 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002212 I.getType(), "phitmp",
2213 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002214 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002215 }
2216 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002217 }
2218 }
2219 return ReplaceInstUsesWith(I, NewPN);
2220}
2221
Chris Lattner2454a2e2008-01-29 06:52:45 +00002222
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002223/// WillNotOverflowSignedAdd - Return true if we can prove that:
2224/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2225/// This basically requires proving that the add in the original type would not
2226/// overflow to change the sign bit or have a carry out.
2227bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2228 // There are different heuristics we can use for this. Here are some simple
2229 // ones.
2230
2231 // Add has the property that adding any two 2's complement numbers can only
2232 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002233 // have at least two sign bits, we know that the addition of the two values
2234 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002235 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2236 return true;
2237
2238
2239 // If one of the operands only has one non-zero bit, and if the other operand
2240 // has a known-zero bit in a more significant place than it (not including the
2241 // sign bit) the ripple may go up to and fill the zero, but won't change the
2242 // sign. For example, (X & ~4) + 1.
2243
2244 // TODO: Implement.
2245
2246 return false;
2247}
2248
Chris Lattner2454a2e2008-01-29 06:52:45 +00002249
Chris Lattner7e708292002-06-25 16:13:24 +00002250Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002251 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002252 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002253
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002254 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2255 I.hasNoUnsignedWrap(), TD))
2256 return ReplaceInstUsesWith(I, V);
2257
2258
Chris Lattner66331a42004-04-10 22:01:55 +00002259 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +00002260 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002261 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002262 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002263 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002264 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002265 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002266
2267 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2268 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002269 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002270 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002271
Eli Friedman709b33d2009-07-13 22:27:52 +00002272 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002273 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002274 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002275 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002276 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002277
2278 if (isa<PHINode>(LHS))
2279 if (Instruction *NV = FoldOpIntoPhi(I))
2280 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002281
Chris Lattner4f637d42006-01-06 17:59:59 +00002282 ConstantInt *XorRHS = 0;
2283 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002284 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002285 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002286 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002287 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002288
Zhou Sheng4351c642007-04-02 08:20:41 +00002289 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002290 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2291 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002292 do {
2293 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002294 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2295 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002296 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2297 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002298 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002299 if (!MaskedValueIsZero(XorLHS,
2300 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002301 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002302 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002303 }
2304 }
2305 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002306 C0080Val = APIntOps::lshr(C0080Val, Size);
2307 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2308 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002309
Reid Spencer35c38852007-03-28 01:36:16 +00002310 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002311 // with funny bit widths then this switch statement should be removed. It
2312 // is just here to get the size of the "middle" type back up to something
2313 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002314 const Type *MiddleType = 0;
2315 switch (Size) {
2316 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002317 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2318 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2319 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002320 }
2321 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002322 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002323 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002324 }
2325 }
Chris Lattner66331a42004-04-10 22:01:55 +00002326 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002327
Owen Anderson1d0be152009-08-13 21:58:54 +00002328 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002329 return BinaryOperator::CreateXor(LHS, RHS);
2330
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002331 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002332 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002333 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002334 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002335
2336 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2337 if (RHSI->getOpcode() == Instruction::Sub)
2338 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2339 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2340 }
2341 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2342 if (LHSI->getOpcode() == Instruction::Sub)
2343 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2344 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2345 }
Robert Bocchino71698282004-07-27 21:02:21 +00002346 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002347
Chris Lattner5c4afb92002-05-08 22:46:53 +00002348 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002349 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002350 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002351 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002352 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002353 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002354 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002355 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002356 }
2357
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002358 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002359 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002360
2361 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002362 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002363 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002364 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002365
Misha Brukmanfd939082005-04-21 23:48:37 +00002366
Chris Lattner50af16a2004-11-13 19:50:12 +00002367 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002368 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002369 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002370 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002371
2372 // X*C1 + X*C2 --> X * (C1+C2)
2373 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002374 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002375 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002376 }
2377
2378 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002379 if (dyn_castFoldableMul(RHS, C2) == LHS)
2380 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002381
Chris Lattnere617c9e2007-01-05 02:17:46 +00002382 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002383 if (dyn_castNotVal(LHS) == RHS ||
2384 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002385 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002386
Chris Lattnerad3448c2003-02-18 19:57:07 +00002387
Chris Lattner564a7272003-08-13 19:01:45 +00002388 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002389 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2390 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002391 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002392
2393 // A+B --> A|B iff A and B have no bits set in common.
2394 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2395 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2396 APInt LHSKnownOne(IT->getBitWidth(), 0);
2397 APInt LHSKnownZero(IT->getBitWidth(), 0);
2398 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2399 if (LHSKnownZero != 0) {
2400 APInt RHSKnownOne(IT->getBitWidth(), 0);
2401 APInt RHSKnownZero(IT->getBitWidth(), 0);
2402 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2403
2404 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002405 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002406 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002407 }
2408 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002409
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002410 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002411 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002412 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002413 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2414 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002415 if (W != Y) {
2416 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002417 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002418 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002419 std::swap(W, X);
2420 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002421 std::swap(Y, Z);
2422 std::swap(W, X);
2423 }
2424 }
2425
2426 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002427 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002428 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002429 }
2430 }
2431 }
2432
Chris Lattner6b032052003-10-02 15:11:26 +00002433 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002434 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002435 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002436 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002437
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002438 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002439 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002440 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002441 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002442 if (Anded == CRHS) {
2443 // See if all bits from the first bit set in the Add RHS up are included
2444 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002445 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002446
2447 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002448 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002449
2450 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002451 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002452
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002453 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2454 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002455 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002456 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002457 }
2458 }
2459 }
2460
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002461 // Try to fold constant add into select arguments.
2462 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002463 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002464 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002465 }
2466
Chris Lattner42790482007-12-20 01:56:58 +00002467 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002468 {
2469 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002470 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002471 if (!SI) {
2472 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002473 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002474 }
Chris Lattner42790482007-12-20 01:56:58 +00002475 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002476 Value *TV = SI->getTrueValue();
2477 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002478 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002479
2480 // Can we fold the add into the argument of the select?
2481 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002482 if (match(FV, m_Zero()) &&
2483 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002484 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002485 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002486 if (match(TV, m_Zero()) &&
2487 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002488 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002489 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002490 }
2491 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002492
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002493 // Check for (add (sext x), y), see if we can merge this into an
2494 // integer add followed by a sext.
2495 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2496 // (add (sext x), cst) --> (sext (add x, cst'))
2497 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2498 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002499 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002500 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002501 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002502 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2503 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002504 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2505 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002506 return new SExtInst(NewAdd, I.getType());
2507 }
2508 }
2509
2510 // (add (sext x), (sext y)) --> (sext (add int x, y))
2511 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2512 // Only do this if x/y have the same type, if at last one of them has a
2513 // single use (so we don't increase the number of sexts), and if the
2514 // integer add will not overflow.
2515 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2516 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2517 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2518 RHSConv->getOperand(0))) {
2519 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002520 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2521 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002522 return new SExtInst(NewAdd, I.getType());
2523 }
2524 }
2525 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002526
2527 return Changed ? &I : 0;
2528}
2529
2530Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2531 bool Changed = SimplifyCommutative(I);
2532 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2533
2534 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2535 // X + 0 --> X
2536 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002537 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002538 (I.getType())->getValueAPF()))
2539 return ReplaceInstUsesWith(I, LHS);
2540 }
2541
2542 if (isa<PHINode>(LHS))
2543 if (Instruction *NV = FoldOpIntoPhi(I))
2544 return NV;
2545 }
2546
2547 // -A + B --> B - A
2548 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002549 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002550 return BinaryOperator::CreateFSub(RHS, LHSV);
2551
2552 // A + -B --> A - B
2553 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002554 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002555 return BinaryOperator::CreateFSub(LHS, V);
2556
2557 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2558 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2559 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2560 return ReplaceInstUsesWith(I, LHS);
2561
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002562 // Check for (add double (sitofp x), y), see if we can merge this into an
2563 // integer add followed by a promotion.
2564 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2565 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2566 // ... if the constant fits in the integer value. This is useful for things
2567 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2568 // requires a constant pool load, and generally allows the add to be better
2569 // instcombined.
2570 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2571 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002572 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002573 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002574 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002575 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2576 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002577 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2578 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002579 return new SIToFPInst(NewAdd, I.getType());
2580 }
2581 }
2582
2583 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2584 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2585 // Only do this if x/y have the same type, if at last one of them has a
2586 // single use (so we don't increase the number of int->fp conversions),
2587 // and if the integer add will not overflow.
2588 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2589 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2590 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2591 RHSConv->getOperand(0))) {
2592 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002593 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002594 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002595 return new SIToFPInst(NewAdd, I.getType());
2596 }
2597 }
2598 }
2599
Chris Lattner7e708292002-06-25 16:13:24 +00002600 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002601}
2602
Chris Lattner092543c2009-11-04 08:05:20 +00002603
2604/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2605/// code necessary to compute the offset from the base pointer (without adding
2606/// in the base pointer). Return the result as a signed integer of intptr size.
2607static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2608 TargetData &TD = *IC.getTargetData();
2609 gep_type_iterator GTI = gep_type_begin(GEP);
2610 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2611 Value *Result = Constant::getNullValue(IntPtrTy);
2612
2613 // Build a mask for high order bits.
2614 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2615 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2616
2617 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2618 ++i, ++GTI) {
2619 Value *Op = *i;
2620 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2621 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2622 if (OpC->isZero()) continue;
2623
2624 // Handle a struct index, which adds its field offset to the pointer.
2625 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2626 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2627
2628 Result = IC.Builder->CreateAdd(Result,
2629 ConstantInt::get(IntPtrTy, Size),
2630 GEP->getName()+".offs");
2631 continue;
2632 }
2633
2634 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2635 Constant *OC =
2636 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2637 Scale = ConstantExpr::getMul(OC, Scale);
2638 // Emit an add instruction.
2639 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2640 continue;
2641 }
2642 // Convert to correct type.
2643 if (Op->getType() != IntPtrTy)
2644 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2645 if (Size != 1) {
2646 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2647 // We'll let instcombine(mul) convert this to a shl if possible.
2648 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2649 }
2650
2651 // Emit an add instruction.
2652 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2653 }
2654 return Result;
2655}
2656
2657
2658/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2659/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2660/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2661/// be complex, and scales are involved. The above expression would also be
2662/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2663/// This later form is less amenable to optimization though, and we are allowed
2664/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2665///
2666/// If we can't emit an optimized form for this expression, this returns null.
2667///
2668static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2669 InstCombiner &IC) {
2670 TargetData &TD = *IC.getTargetData();
2671 gep_type_iterator GTI = gep_type_begin(GEP);
2672
2673 // Check to see if this gep only has a single variable index. If so, and if
2674 // any constant indices are a multiple of its scale, then we can compute this
2675 // in terms of the scale of the variable index. For example, if the GEP
2676 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2677 // because the expression will cross zero at the same point.
2678 unsigned i, e = GEP->getNumOperands();
2679 int64_t Offset = 0;
2680 for (i = 1; i != e; ++i, ++GTI) {
2681 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2682 // Compute the aggregate offset of constant indices.
2683 if (CI->isZero()) continue;
2684
2685 // Handle a struct index, which adds its field offset to the pointer.
2686 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2687 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2688 } else {
2689 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2690 Offset += Size*CI->getSExtValue();
2691 }
2692 } else {
2693 // Found our variable index.
2694 break;
2695 }
2696 }
2697
2698 // If there are no variable indices, we must have a constant offset, just
2699 // evaluate it the general way.
2700 if (i == e) return 0;
2701
2702 Value *VariableIdx = GEP->getOperand(i);
2703 // Determine the scale factor of the variable element. For example, this is
2704 // 4 if the variable index is into an array of i32.
2705 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2706
2707 // Verify that there are no other variable indices. If so, emit the hard way.
2708 for (++i, ++GTI; i != e; ++i, ++GTI) {
2709 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2710 if (!CI) return 0;
2711
2712 // Compute the aggregate offset of constant indices.
2713 if (CI->isZero()) continue;
2714
2715 // Handle a struct index, which adds its field offset to the pointer.
2716 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2717 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2718 } else {
2719 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2720 Offset += Size*CI->getSExtValue();
2721 }
2722 }
2723
2724 // Okay, we know we have a single variable index, which must be a
2725 // pointer/array/vector index. If there is no offset, life is simple, return
2726 // the index.
2727 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2728 if (Offset == 0) {
2729 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2730 // we don't need to bother extending: the extension won't affect where the
2731 // computation crosses zero.
2732 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2733 VariableIdx = new TruncInst(VariableIdx,
2734 TD.getIntPtrType(VariableIdx->getContext()),
2735 VariableIdx->getName(), &I);
2736 return VariableIdx;
2737 }
2738
2739 // Otherwise, there is an index. The computation we will do will be modulo
2740 // the pointer size, so get it.
2741 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2742
2743 Offset &= PtrSizeMask;
2744 VariableScale &= PtrSizeMask;
2745
2746 // To do this transformation, any constant index must be a multiple of the
2747 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2748 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2749 // multiple of the variable scale.
2750 int64_t NewOffs = Offset / (int64_t)VariableScale;
2751 if (Offset != NewOffs*(int64_t)VariableScale)
2752 return 0;
2753
2754 // Okay, we can do this evaluation. Start by converting the index to intptr.
2755 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2756 if (VariableIdx->getType() != IntPtrTy)
2757 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2758 true /*SExt*/,
2759 VariableIdx->getName(), &I);
2760 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2761 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2762}
2763
2764
2765/// Optimize pointer differences into the same array into a size. Consider:
2766/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2767/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2768///
2769Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2770 const Type *Ty) {
2771 assert(TD && "Must have target data info for this");
2772
2773 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2774 // this.
2775 bool Swapped;
Chris Lattner85c1c962010-01-01 22:42:29 +00002776 GetElementPtrInst *GEP = 0;
2777 ConstantExpr *CstGEP = 0;
Chris Lattner092543c2009-11-04 08:05:20 +00002778
Chris Lattner85c1c962010-01-01 22:42:29 +00002779 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
2780 // For now we require one side to be the base pointer "A" or a constant
2781 // expression derived from it.
2782 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
2783 // (gep X, ...) - X
2784 if (LHSGEP->getOperand(0) == RHS) {
2785 GEP = LHSGEP;
2786 Swapped = false;
2787 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
2788 // (gep X, ...) - (ce_gep X, ...)
2789 if (CE->getOpcode() == Instruction::GetElementPtr &&
2790 LHSGEP->getOperand(0) == CE->getOperand(0)) {
2791 CstGEP = CE;
2792 GEP = LHSGEP;
2793 Swapped = false;
2794 }
2795 }
2796 }
2797
2798 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
2799 // X - (gep X, ...)
2800 if (RHSGEP->getOperand(0) == LHS) {
2801 GEP = RHSGEP;
2802 Swapped = true;
2803 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
2804 // (ce_gep X, ...) - (gep X, ...)
2805 if (CE->getOpcode() == Instruction::GetElementPtr &&
2806 RHSGEP->getOperand(0) == CE->getOperand(0)) {
2807 CstGEP = CE;
2808 GEP = RHSGEP;
2809 Swapped = true;
2810 }
2811 }
2812 }
2813
2814 if (GEP == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00002815 return 0;
2816
Chris Lattner092543c2009-11-04 08:05:20 +00002817 // Emit the offset of the GEP and an intptr_t.
2818 Value *Result = EmitGEPOffset(GEP, *this);
Chris Lattner85c1c962010-01-01 22:42:29 +00002819
2820 // If we had a constant expression GEP on the other side offsetting the
2821 // pointer, subtract it from the offset we have.
2822 if (CstGEP) {
2823 Value *CstOffset = EmitGEPOffset(CstGEP, *this);
2824 Result = Builder->CreateSub(Result, CstOffset);
2825 }
2826
Chris Lattner092543c2009-11-04 08:05:20 +00002827
2828 // If we have p - gep(p, ...) then we have to negate the result.
2829 if (Swapped)
2830 Result = Builder->CreateNeg(Result, "diff.neg");
2831
2832 return Builder->CreateIntCast(Result, Ty, true);
2833}
2834
2835
Chris Lattner7e708292002-06-25 16:13:24 +00002836Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002837 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002838
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002839 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002840 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002841
Chris Lattner3bf68152009-12-21 04:04:05 +00002842 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
2843 if (Value *V = dyn_castNegVal(Op1)) {
2844 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2845 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2846 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2847 return Res;
2848 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002849
Chris Lattnere87597f2004-10-16 18:11:37 +00002850 if (isa<UndefValue>(Op0))
2851 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2852 if (isa<UndefValue>(Op1))
2853 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner092543c2009-11-04 08:05:20 +00002854 if (I.getType() == Type::getInt1Ty(*Context))
2855 return BinaryOperator::CreateXor(Op0, Op1);
2856
Chris Lattnerd65460f2003-11-05 01:06:05 +00002857 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002858 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002859 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002860 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002861
Chris Lattnerd65460f2003-11-05 01:06:05 +00002862 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002863 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002864 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002865 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002866
Chris Lattner76b7a062007-01-15 07:02:54 +00002867 // -(X >>u 31) -> (X >>s 31)
2868 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002869 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002870 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002871 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002872 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002873 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002874 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002875 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002876 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002877 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002878 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002879 }
2880 }
Chris Lattner092543c2009-11-04 08:05:20 +00002881 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002882 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2883 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002884 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002885 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002886 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002887 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002888 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002889 }
2890 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002891 }
2892 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002893 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002894
2895 // Try to fold constant sub into select arguments.
2896 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002897 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002898 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002899
2900 // C - zext(bool) -> bool ? C - 1 : C
2901 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002902 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002903 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002904 }
2905
Chris Lattner43d84d62005-04-07 16:15:25 +00002906 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002907 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002908 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002909 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002910 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002911 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002912 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002913 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002914 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2915 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2916 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002917 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002918 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002919 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002920 }
2921
Chris Lattnerfd059242003-10-15 16:48:29 +00002922 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002923 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2924 // is not used by anyone else...
2925 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002926 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002927 // Swap the two operands of the subexpr...
2928 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2929 Op1I->setOperand(0, IIOp1);
2930 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002931
Chris Lattnera2881962003-02-18 19:28:33 +00002932 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002933 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002934 }
2935
2936 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2937 //
2938 if (Op1I->getOpcode() == Instruction::And &&
2939 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2940 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2941
Chris Lattner74381062009-08-30 07:44:24 +00002942 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002943 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002944 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002945
Reid Spencerac5209e2006-10-16 23:08:08 +00002946 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002947 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002948 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002949 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002950 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002951 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002952 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002953
Chris Lattnerad3448c2003-02-18 19:57:07 +00002954 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002955 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002956 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002957 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002958 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002959 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002960 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002961 }
Chris Lattner40371712002-05-09 01:29:19 +00002962 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002963 }
Chris Lattnera2881962003-02-18 19:28:33 +00002964
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002965 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2966 if (Op0I->getOpcode() == Instruction::Add) {
2967 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2968 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2969 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2970 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2971 } else if (Op0I->getOpcode() == Instruction::Sub) {
2972 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002973 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002974 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002975 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002976 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002977
Chris Lattner50af16a2004-11-13 19:50:12 +00002978 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002979 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002980 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002981 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002982
Chris Lattner50af16a2004-11-13 19:50:12 +00002983 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002984 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002985 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002986 }
Chris Lattner092543c2009-11-04 08:05:20 +00002987
2988 // Optimize pointer differences into the same array into a size. Consider:
2989 // &A[10] - &A[0]: we should compile this to "10".
2990 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00002991 Value *LHSOp, *RHSOp;
Chris Lattnerf2ebc682010-01-01 22:29:12 +00002992 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
2993 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattner33767182010-01-01 22:12:03 +00002994 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2995 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00002996
2997 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerf2ebc682010-01-01 22:29:12 +00002998 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
2999 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
3000 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
3001 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00003002 }
3003
Chris Lattner3f5b8772002-05-06 16:14:14 +00003004 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003005}
3006
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003007Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
3008 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3009
3010 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00003011 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003012 return BinaryOperator::CreateFAdd(Op0, V);
3013
3014 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
3015 if (Op1I->getOpcode() == Instruction::FAdd) {
3016 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00003017 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00003018 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003019 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00003020 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00003021 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003022 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003023 }
3024
3025 return 0;
3026}
3027
Chris Lattnera0141b92007-07-15 20:42:37 +00003028/// isSignBitCheck - Given an exploded icmp instruction, return true if the
3029/// comparison only checks the sign bit. If it only checks the sign bit, set
3030/// TrueIfSigned if the result of the comparison is true when the input value is
3031/// signed.
3032static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3033 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003034 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003035 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3036 TrueIfSigned = true;
3037 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003038 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3039 TrueIfSigned = true;
3040 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00003041 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3042 TrueIfSigned = false;
3043 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003044 case ICmpInst::ICMP_UGT:
3045 // True if LHS u> RHS and RHS == high-bit-mask - 1
3046 TrueIfSigned = true;
3047 return RHS->getValue() ==
3048 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3049 case ICmpInst::ICMP_UGE:
3050 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3051 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00003052 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00003053 default:
3054 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00003055 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00003056}
3057
Chris Lattner7e708292002-06-25 16:13:24 +00003058Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003059 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003060 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003061
Chris Lattnera2498472009-10-11 21:36:10 +00003062 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003063 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003064
Chris Lattner8af304a2009-10-11 07:53:15 +00003065 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00003066 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3067 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00003068
3069 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00003070 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00003071 if (SI->getOpcode() == Instruction::Shl)
3072 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003073 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003074 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00003075
Zhou Sheng843f07672007-04-19 05:39:12 +00003076 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00003077 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00003078 if (CI->equalsInt(1)) // X * 1 == X
3079 return ReplaceInstUsesWith(I, Op0);
3080 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00003081 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003082
Zhou Sheng97b52c22007-03-29 01:57:21 +00003083 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003084 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003085 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003086 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003087 }
Chris Lattnera2498472009-10-11 21:36:10 +00003088 } else if (isa<VectorType>(Op1C->getType())) {
3089 if (Op1C->isNullValue())
3090 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00003091
Chris Lattnera2498472009-10-11 21:36:10 +00003092 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003093 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00003094 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00003095
3096 // As above, vector X*splat(1.0) -> X in all defined cases.
3097 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003098 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3099 if (CI->equalsInt(1))
3100 return ReplaceInstUsesWith(I, Op0);
3101 }
3102 }
Chris Lattnera2881962003-02-18 19:28:33 +00003103 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003104
3105 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3106 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003107 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003108 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00003109 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3110 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003111 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003112
3113 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003114
3115 // Try to fold constant mul into select arguments.
3116 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003117 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003118 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003119
3120 if (isa<PHINode>(Op0))
3121 if (Instruction *NV = FoldOpIntoPhi(I))
3122 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003123 }
3124
Dan Gohman186a6362009-08-12 16:04:34 +00003125 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003126 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003127 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003128
Nick Lewycky0c730792008-11-21 07:33:58 +00003129 // (X / Y) * Y = X - (X % Y)
3130 // (X / Y) * -Y = (X % Y) - X
3131 {
Chris Lattnera2498472009-10-11 21:36:10 +00003132 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00003133 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3134 if (!BO ||
3135 (BO->getOpcode() != Instruction::UDiv &&
3136 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00003137 Op1C = Op0;
3138 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00003139 }
Chris Lattnera2498472009-10-11 21:36:10 +00003140 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00003141 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003142 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00003143 (BO->getOpcode() == Instruction::UDiv ||
3144 BO->getOpcode() == Instruction::SDiv)) {
3145 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3146
Dan Gohmanfa94b942009-08-12 16:33:09 +00003147 // If the division is exact, X % Y is zero.
3148 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3149 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00003150 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00003151 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00003152 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00003153 }
3154
Chris Lattner74381062009-08-30 07:44:24 +00003155 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00003156 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00003157 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003158 else
Chris Lattner74381062009-08-30 07:44:24 +00003159 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003160 Rem->takeName(BO);
3161
Chris Lattnera2498472009-10-11 21:36:10 +00003162 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00003163 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00003164 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003165 }
3166 }
3167
Chris Lattner8af304a2009-10-11 07:53:15 +00003168 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00003169 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00003170 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003171
Chris Lattner8af304a2009-10-11 07:53:15 +00003172 // X*(1 << Y) --> X << Y
3173 // (1 << Y)*X --> X << Y
3174 {
3175 Value *Y;
3176 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00003177 return BinaryOperator::CreateShl(Op1, Y);
3178 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00003179 return BinaryOperator::CreateShl(Op0, Y);
3180 }
3181
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003182 // If one of the operands of the multiply is a cast from a boolean value, then
3183 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00003184 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3185 if (!isa<VectorType>(I.getType())) {
3186 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00003187 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00003188
Chris Lattnerd2c58362009-10-11 21:29:45 +00003189 Value *BoolCast = 0, *OtherOp = 0;
3190 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00003191 BoolCast = Op0, OtherOp = Op1;
3192 else if (MaskedValueIsZero(Op1, Negative2))
3193 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00003194
Chris Lattner0036e3a2009-10-11 21:22:21 +00003195 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00003196 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3197 BoolCast, "tmp");
3198 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003199 }
3200 }
3201
Chris Lattner7e708292002-06-25 16:13:24 +00003202 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003203}
3204
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003205Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3206 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003207 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003208
3209 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00003210 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3211 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003212 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3213 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3214 if (Op1F->isExactlyValue(1.0))
3215 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00003216 } else if (isa<VectorType>(Op1C->getType())) {
3217 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003218 // As above, vector X*splat(1.0) -> X in all defined cases.
3219 if (Constant *Splat = Op1V->getSplatValue()) {
3220 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3221 if (F->isExactlyValue(1.0))
3222 return ReplaceInstUsesWith(I, Op0);
3223 }
3224 }
3225 }
3226
3227 // Try to fold constant mul into select arguments.
3228 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3229 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3230 return R;
3231
3232 if (isa<PHINode>(Op0))
3233 if (Instruction *NV = FoldOpIntoPhi(I))
3234 return NV;
3235 }
3236
Dan Gohman186a6362009-08-12 16:04:34 +00003237 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003238 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003239 return BinaryOperator::CreateFMul(Op0v, Op1v);
3240
3241 return Changed ? &I : 0;
3242}
3243
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003244/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3245/// instruction.
3246bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3247 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3248
3249 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3250 int NonNullOperand = -1;
3251 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3252 if (ST->isNullValue())
3253 NonNullOperand = 2;
3254 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3255 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3256 if (ST->isNullValue())
3257 NonNullOperand = 1;
3258
3259 if (NonNullOperand == -1)
3260 return false;
3261
3262 Value *SelectCond = SI->getOperand(0);
3263
3264 // Change the div/rem to use 'Y' instead of the select.
3265 I.setOperand(1, SI->getOperand(NonNullOperand));
3266
3267 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3268 // problem. However, the select, or the condition of the select may have
3269 // multiple uses. Based on our knowledge that the operand must be non-zero,
3270 // propagate the known value for the select into other uses of it, and
3271 // propagate a known value of the condition into its other users.
3272
3273 // If the select and condition only have a single use, don't bother with this,
3274 // early exit.
3275 if (SI->use_empty() && SelectCond->hasOneUse())
3276 return true;
3277
3278 // Scan the current block backward, looking for other uses of SI.
3279 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3280
3281 while (BBI != BBFront) {
3282 --BBI;
3283 // If we found a call to a function, we can't assume it will return, so
3284 // information from below it cannot be propagated above it.
3285 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3286 break;
3287
3288 // Replace uses of the select or its condition with the known values.
3289 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3290 I != E; ++I) {
3291 if (*I == SI) {
3292 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003293 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003294 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00003295 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3296 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003297 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003298 }
3299 }
3300
3301 // If we past the instruction, quit looking for it.
3302 if (&*BBI == SI)
3303 SI = 0;
3304 if (&*BBI == SelectCond)
3305 SelectCond = 0;
3306
3307 // If we ran out of things to eliminate, break out of the loop.
3308 if (SelectCond == 0 && SI == 0)
3309 break;
3310
3311 }
3312 return true;
3313}
3314
3315
Reid Spencer1628cec2006-10-26 06:15:43 +00003316/// This function implements the transforms on div instructions that work
3317/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3318/// used by the visitors to those instructions.
3319/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003320Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003321 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003322
Chris Lattner50b2ca42008-02-19 06:12:18 +00003323 // undef / X -> 0 for integer.
3324 // undef / X -> undef for FP (the undef could be a snan).
3325 if (isa<UndefValue>(Op0)) {
3326 if (Op0->getType()->isFPOrFPVector())
3327 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003328 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003329 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003330
3331 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003332 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003333 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003334
Reid Spencer1628cec2006-10-26 06:15:43 +00003335 return 0;
3336}
Misha Brukmanfd939082005-04-21 23:48:37 +00003337
Reid Spencer1628cec2006-10-26 06:15:43 +00003338/// This function implements the transforms common to both integer division
3339/// instructions (udiv and sdiv). It is called by the visitors to those integer
3340/// division instructions.
3341/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003342Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003343 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3344
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003345 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003346 if (Op0 == Op1) {
3347 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003348 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003349 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003350 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003351 }
3352
Owen Andersoneed707b2009-07-24 23:12:02 +00003353 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003354 return ReplaceInstUsesWith(I, CI);
3355 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003356
Reid Spencer1628cec2006-10-26 06:15:43 +00003357 if (Instruction *Common = commonDivTransforms(I))
3358 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003359
3360 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3361 // This does not apply for fdiv.
3362 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3363 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003364
3365 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3366 // div X, 1 == X
3367 if (RHS->equalsInt(1))
3368 return ReplaceInstUsesWith(I, Op0);
3369
3370 // (X / C1) / C2 -> X / (C1*C2)
3371 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3372 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3373 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003374 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003375 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003376 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003377 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003378 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003379 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003380 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003381
Reid Spencerbca0e382007-03-23 20:05:17 +00003382 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003383 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3384 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3385 return R;
3386 if (isa<PHINode>(Op0))
3387 if (Instruction *NV = FoldOpIntoPhi(I))
3388 return NV;
3389 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003390 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003391
Chris Lattnera2881962003-02-18 19:28:33 +00003392 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003393 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003394 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003395 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003396
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003397 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003398 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003399 return ReplaceInstUsesWith(I, Op0);
3400
Nick Lewycky895f0852008-11-27 20:21:08 +00003401 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3402 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3403 // div X, 1 == X
3404 if (X->isOne())
3405 return ReplaceInstUsesWith(I, Op0);
3406 }
3407
Reid Spencer1628cec2006-10-26 06:15:43 +00003408 return 0;
3409}
3410
3411Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3412 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3413
3414 // Handle the integer div common cases
3415 if (Instruction *Common = commonIDivTransforms(I))
3416 return Common;
3417
Reid Spencer1628cec2006-10-26 06:15:43 +00003418 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003419 // X udiv C^2 -> X >> C
3420 // Check to see if this is an unsigned division with an exact power of 2,
3421 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003422 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003423 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003424 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003425
3426 // X udiv C, where C >= signbit
3427 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003428 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003429 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003430 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003431 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003432 }
3433
3434 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003435 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003436 if (RHSI->getOpcode() == Instruction::Shl &&
3437 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003438 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003439 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003440 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003441 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003442 if (uint32_t C2 = C1.logBase2())
3443 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003444 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003445 }
3446 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003447 }
3448
Reid Spencer1628cec2006-10-26 06:15:43 +00003449 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3450 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003451 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003452 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003453 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003454 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003455 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003456 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003457 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003458 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003459 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003460 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003461
3462 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003463 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003464 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003465
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003466 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003467 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003468 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003469 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003470 return 0;
3471}
3472
Reid Spencer1628cec2006-10-26 06:15:43 +00003473Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3474 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3475
3476 // Handle the integer div common cases
3477 if (Instruction *Common = commonIDivTransforms(I))
3478 return Common;
3479
3480 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3481 // sdiv X, -1 == -X
3482 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003483 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003484
Dan Gohmanfa94b942009-08-12 16:33:09 +00003485 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003486 if (cast<SDivOperator>(&I)->isExact() &&
3487 RHS->getValue().isNonNegative() &&
3488 RHS->getValue().isPowerOf2()) {
3489 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3490 RHS->getValue().exactLogBase2());
3491 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3492 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003493
3494 // -X/C --> X/-C provided the negation doesn't overflow.
3495 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3496 if (isa<Constant>(Sub->getOperand(0)) &&
3497 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003498 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003499 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3500 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003501 }
3502
3503 // If the sign bits of both operands are zero (i.e. we can prove they are
3504 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003505 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003506 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003507 if (MaskedValueIsZero(Op0, Mask)) {
3508 if (MaskedValueIsZero(Op1, Mask)) {
3509 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3510 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3511 }
3512 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003513 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003514 ShiftedInt->getValue().isPowerOf2()) {
3515 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3516 // Safe because the only negative value (1 << Y) can take on is
3517 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3518 // the sign bit set.
3519 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3520 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003521 }
Eli Friedman8be17392009-07-18 09:53:21 +00003522 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003523
3524 return 0;
3525}
3526
3527Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3528 return commonDivTransforms(I);
3529}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003530
Reid Spencer0a783f72006-11-02 01:53:59 +00003531/// This function implements the transforms on rem instructions that work
3532/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3533/// is used by the visitors to those instructions.
3534/// @brief Transforms common to all three rem instructions
3535Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003536 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003537
Chris Lattner50b2ca42008-02-19 06:12:18 +00003538 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3539 if (I.getType()->isFPOrFPVector())
3540 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003541 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003542 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003543 if (isa<UndefValue>(Op1))
3544 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003545
3546 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003547 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3548 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003549
Reid Spencer0a783f72006-11-02 01:53:59 +00003550 return 0;
3551}
3552
3553/// This function implements the transforms common to both integer remainder
3554/// instructions (urem and srem). It is called by the visitors to those integer
3555/// remainder instructions.
3556/// @brief Common integer remainder transforms
3557Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3558 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3559
3560 if (Instruction *common = commonRemTransforms(I))
3561 return common;
3562
Dale Johannesened6af242009-01-21 00:35:19 +00003563 // 0 % X == 0 for integer, we don't need to preserve faults!
3564 if (Constant *LHS = dyn_cast<Constant>(Op0))
3565 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003566 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003567
Chris Lattner857e8cd2004-12-12 21:48:58 +00003568 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003569 // X % 0 == undef, we don't need to preserve faults!
3570 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003571 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003572
Chris Lattnera2881962003-02-18 19:28:33 +00003573 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003574 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003575
Chris Lattner97943922006-02-28 05:49:21 +00003576 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3577 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3578 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3579 return R;
3580 } else if (isa<PHINode>(Op0I)) {
3581 if (Instruction *NV = FoldOpIntoPhi(I))
3582 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003583 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003584
3585 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003586 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003587 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003588 }
Chris Lattnera2881962003-02-18 19:28:33 +00003589 }
3590
Reid Spencer0a783f72006-11-02 01:53:59 +00003591 return 0;
3592}
3593
3594Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3595 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3596
3597 if (Instruction *common = commonIRemTransforms(I))
3598 return common;
3599
3600 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3601 // X urem C^2 -> X and C
3602 // Check to see if this is an unsigned remainder with an exact power of 2,
3603 // if so, convert to a bitwise and.
3604 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003605 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003606 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003607 }
3608
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003609 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003610 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3611 if (RHSI->getOpcode() == Instruction::Shl &&
3612 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003613 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003614 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003615 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003616 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003617 }
3618 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003619 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003620
Reid Spencer0a783f72006-11-02 01:53:59 +00003621 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3622 // where C1&C2 are powers of two.
3623 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3624 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3625 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3626 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003627 if ((STO->getValue().isPowerOf2()) &&
3628 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003629 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3630 SI->getName()+".t");
3631 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3632 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003633 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003634 }
3635 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003636 }
3637
Chris Lattner3f5b8772002-05-06 16:14:14 +00003638 return 0;
3639}
3640
Reid Spencer0a783f72006-11-02 01:53:59 +00003641Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3642 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3643
Dan Gohmancff55092007-11-05 23:16:33 +00003644 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003645 if (Instruction *Common = commonIRemTransforms(I))
3646 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003647
Dan Gohman186a6362009-08-12 16:04:34 +00003648 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003649 if (!isa<Constant>(RHSNeg) ||
3650 (isa<ConstantInt>(RHSNeg) &&
3651 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003652 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003653 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003654 I.setOperand(1, RHSNeg);
3655 return &I;
3656 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003657
Dan Gohmancff55092007-11-05 23:16:33 +00003658 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003659 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003660 if (I.getType()->isInteger()) {
3661 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3662 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3663 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003664 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003665 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003666 }
3667
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003668 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003669 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3670 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003671
Nick Lewycky9dce8732008-12-20 16:48:00 +00003672 bool hasNegative = false;
3673 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3674 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3675 if (RHS->getValue().isNegative())
3676 hasNegative = true;
3677
3678 if (hasNegative) {
3679 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003680 for (unsigned i = 0; i != VWidth; ++i) {
3681 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3682 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003683 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003684 else
3685 Elts[i] = RHS;
3686 }
3687 }
3688
Owen Andersonaf7ec972009-07-28 21:19:26 +00003689 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003690 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003691 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003692 I.setOperand(1, NewRHSV);
3693 return &I;
3694 }
3695 }
3696 }
3697
Reid Spencer0a783f72006-11-02 01:53:59 +00003698 return 0;
3699}
3700
3701Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003702 return commonRemTransforms(I);
3703}
3704
Chris Lattner457dd822004-06-09 07:59:58 +00003705// isOneBitSet - Return true if there is exactly one bit set in the specified
3706// constant.
3707static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003708 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003709}
3710
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003711// isHighOnes - Return true if the constant is of the form 1+0+.
3712// This is the same as lowones(~X).
3713static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003714 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003715}
3716
Reid Spencere4d87aa2006-12-23 06:05:41 +00003717/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003718/// are carefully arranged to allow folding of expressions such as:
3719///
3720/// (A < B) | (A > B) --> (A != B)
3721///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003722/// Note that this is only valid if the first and second predicates have the
3723/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003724///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003725/// Three bits are used to represent the condition, as follows:
3726/// 0 A > B
3727/// 1 A == B
3728/// 2 A < B
3729///
3730/// <=> Value Definition
3731/// 000 0 Always false
3732/// 001 1 A > B
3733/// 010 2 A == B
3734/// 011 3 A >= B
3735/// 100 4 A < B
3736/// 101 5 A != B
3737/// 110 6 A <= B
3738/// 111 7 Always true
3739///
3740static unsigned getICmpCode(const ICmpInst *ICI) {
3741 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003742 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003743 case ICmpInst::ICMP_UGT: return 1; // 001
3744 case ICmpInst::ICMP_SGT: return 1; // 001
3745 case ICmpInst::ICMP_EQ: return 2; // 010
3746 case ICmpInst::ICMP_UGE: return 3; // 011
3747 case ICmpInst::ICMP_SGE: return 3; // 011
3748 case ICmpInst::ICMP_ULT: return 4; // 100
3749 case ICmpInst::ICMP_SLT: return 4; // 100
3750 case ICmpInst::ICMP_NE: return 5; // 101
3751 case ICmpInst::ICMP_ULE: return 6; // 110
3752 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003753 // True -> 7
3754 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003755 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003756 return 0;
3757 }
3758}
3759
Evan Cheng8db90722008-10-14 17:15:11 +00003760/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3761/// predicate into a three bit mask. It also returns whether it is an ordered
3762/// predicate by reference.
3763static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3764 isOrdered = false;
3765 switch (CC) {
3766 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3767 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003768 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3769 case FCmpInst::FCMP_UGT: return 1; // 001
3770 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3771 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003772 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3773 case FCmpInst::FCMP_UGE: return 3; // 011
3774 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3775 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003776 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3777 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003778 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3779 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003780 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003781 default:
3782 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003783 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003784 return 0;
3785 }
3786}
3787
Reid Spencere4d87aa2006-12-23 06:05:41 +00003788/// getICmpValue - This is the complement of getICmpCode, which turns an
3789/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003790/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003791/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003792static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003793 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003794 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003795 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003796 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003797 case 1:
3798 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003799 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003800 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003801 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3802 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003803 case 3:
3804 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003805 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003806 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003807 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003808 case 4:
3809 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003810 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003811 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003812 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3813 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003814 case 6:
3815 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003816 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003817 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003818 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003819 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003820 }
3821}
3822
Evan Cheng8db90722008-10-14 17:15:11 +00003823/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3824/// opcode and two operands into either a FCmp instruction. isordered is passed
3825/// in to determine which kind of predicate to use in the new fcmp instruction.
3826static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003827 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003828 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003829 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003830 case 0:
3831 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003832 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003833 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003834 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003835 case 1:
3836 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003837 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003838 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003839 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003840 case 2:
3841 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003842 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003843 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003844 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003845 case 3:
3846 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003847 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003848 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003849 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003850 case 4:
3851 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003852 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003853 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003854 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003855 case 5:
3856 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003857 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003858 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003859 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003860 case 6:
3861 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003862 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003863 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003864 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003865 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003866 }
3867}
3868
Chris Lattnerb9553d62008-11-16 04:55:20 +00003869/// PredicatesFoldable - Return true if both predicates match sign or if at
3870/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003871static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003872 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3873 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3874 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003875}
3876
3877namespace {
3878// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3879struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003880 InstCombiner &IC;
3881 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003882 ICmpInst::Predicate pred;
3883 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3884 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3885 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003886 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003887 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3888 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003889 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3890 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003891 return false;
3892 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003893 Instruction *apply(Instruction &Log) const {
3894 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3895 if (ICI->getOperand(0) != LHS) {
3896 assert(ICI->getOperand(1) == LHS);
3897 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003898 }
3899
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003900 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003901 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003902 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003903 unsigned Code;
3904 switch (Log.getOpcode()) {
3905 case Instruction::And: Code = LHSCode & RHSCode; break;
3906 case Instruction::Or: Code = LHSCode | RHSCode; break;
3907 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003908 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003909 }
3910
Nick Lewycky4a134af2009-10-25 05:20:17 +00003911 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003912 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003913 if (Instruction *I = dyn_cast<Instruction>(RV))
3914 return I;
3915 // Otherwise, it's a constant boolean value...
3916 return IC.ReplaceInstUsesWith(Log, RV);
3917 }
3918};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003919} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003920
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003921// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3922// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003923// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003924Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003925 ConstantInt *OpRHS,
3926 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003927 BinaryOperator &TheAnd) {
3928 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003929 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003930 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003931 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003932
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003933 switch (Op->getOpcode()) {
3934 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003935 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003936 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003937 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003938 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003939 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003940 }
3941 break;
3942 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003943 if (Together == AndRHS) // (X | C) & C --> C
3944 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003945
Chris Lattner6e7ba452005-01-01 16:22:27 +00003946 if (Op->hasOneUse() && Together != OpRHS) {
3947 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003948 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003949 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003950 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003951 }
3952 break;
3953 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003954 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003955 // Adding a one to a single bit bit-field should be turned into an XOR
3956 // of the bit. First thing to check is to see if this AND is with a
3957 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003958 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003959
3960 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003961 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003962 // Ok, at this point, we know that we are masking the result of the
3963 // ADD down to exactly one bit. If the constant we are adding has
3964 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003965 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003966
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003967 // Check to see if any bits below the one bit set in AndRHSV are set.
3968 if ((AddRHS & (AndRHSV-1)) == 0) {
3969 // If not, the only thing that can effect the output of the AND is
3970 // the bit specified by AndRHSV. If that bit is set, the effect of
3971 // the XOR is to toggle the bit. If it is clear, then the ADD has
3972 // no effect.
3973 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3974 TheAnd.setOperand(0, X);
3975 return &TheAnd;
3976 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003977 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003978 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003979 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003980 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003981 }
3982 }
3983 }
3984 }
3985 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003986
3987 case Instruction::Shl: {
3988 // We know that the AND will not produce any of the bits shifted in, so if
3989 // the anded constant includes them, clear them now!
3990 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003991 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003992 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003993 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003994 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003995
Zhou Sheng290bec52007-03-29 08:15:12 +00003996 if (CI->getValue() == ShlMask) {
3997 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003998 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3999 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00004000 TheAnd.setOperand(1, CI);
4001 return &TheAnd;
4002 }
4003 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00004004 }
Reid Spencer3822ff52006-11-08 06:47:33 +00004005 case Instruction::LShr:
4006 {
Chris Lattner62a355c2003-09-19 19:05:02 +00004007 // We know that the AND will not produce any of the bits shifted in, so if
4008 // the anded constant includes them, clear them now! This only applies to
4009 // unsigned shifts, because a signed shr may bring in set bits!
4010 //
Zhou Sheng290bec52007-03-29 08:15:12 +00004011 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004012 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00004013 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00004014 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00004015
Zhou Sheng290bec52007-03-29 08:15:12 +00004016 if (CI->getValue() == ShrMask) {
4017 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00004018 return ReplaceInstUsesWith(TheAnd, Op);
4019 } else if (CI != AndRHS) {
4020 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
4021 return &TheAnd;
4022 }
4023 break;
4024 }
4025 case Instruction::AShr:
4026 // Signed shr.
4027 // See if this is shifting in some sign extension, then masking it out
4028 // with an and.
4029 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00004030 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004031 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00004032 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00004033 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00004034 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00004035 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00004036 // Make the argument unsigned.
4037 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00004038 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004039 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00004040 }
Chris Lattner62a355c2003-09-19 19:05:02 +00004041 }
4042 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004043 }
4044 return 0;
4045}
4046
Chris Lattner8b170942002-08-09 23:47:40 +00004047
Chris Lattnera96879a2004-09-29 17:40:11 +00004048/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
4049/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00004050/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
4051/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00004052/// insert new instructions.
4053Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004054 bool isSigned, bool Inside,
4055 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004056 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00004057 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00004058 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004059
Chris Lattnera96879a2004-09-29 17:40:11 +00004060 if (Inside) {
4061 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004062 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00004063
Reid Spencere4d87aa2006-12-23 06:05:41 +00004064 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004065 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00004066 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00004067 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004068 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004069 }
4070
4071 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00004072 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00004073 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00004074 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004075 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004076 }
4077
4078 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004079 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00004080
Reid Spencere4e40032007-03-21 23:19:50 +00004081 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00004082 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004083 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004084 ICmpInst::Predicate pred = (isSigned ?
4085 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004086 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004087 }
Reid Spencerb83eb642006-10-20 07:07:24 +00004088
Reid Spencere4e40032007-03-21 23:19:50 +00004089 // Emit V-Lo >u Hi-1-Lo
4090 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00004091 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00004092 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00004093 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004094 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004095}
4096
Chris Lattner7203e152005-09-18 07:22:02 +00004097// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
4098// any number of 0s on either side. The 1s are allowed to wrap from LSB to
4099// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
4100// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00004101static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004102 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00004103 uint32_t BitWidth = Val->getType()->getBitWidth();
4104 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00004105
4106 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00004107 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00004108 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00004109 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00004110 return true;
4111}
4112
Chris Lattner7203e152005-09-18 07:22:02 +00004113/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4114/// where isSub determines whether the operator is a sub. If we can fold one of
4115/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00004116///
4117/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4118/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4119/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4120///
4121/// return (A +/- B).
4122///
4123Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004124 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00004125 Instruction &I) {
4126 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4127 if (!LHSI || LHSI->getNumOperands() != 2 ||
4128 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4129
4130 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4131
4132 switch (LHSI->getOpcode()) {
4133 default: return 0;
4134 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00004135 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004136 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004137 if ((Mask->getValue().countLeadingZeros() +
4138 Mask->getValue().countPopulation()) ==
4139 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004140 break;
4141
4142 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4143 // part, we don't need any explicit masks to take them out of A. If that
4144 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004145 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004146 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004147 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004148 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004149 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004150 break;
4151 }
4152 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004153 return 0;
4154 case Instruction::Or:
4155 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004156 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004157 if ((Mask->getValue().countLeadingZeros() +
4158 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00004159 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004160 break;
4161 return 0;
4162 }
4163
Chris Lattnerc8e77562005-09-18 04:24:45 +00004164 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00004165 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4166 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004167}
4168
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004169/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4170Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4171 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00004172 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004173 ConstantInt *LHSCst, *RHSCst;
4174 ICmpInst::Predicate LHSCC, RHSCC;
4175
Chris Lattnerea065fb2008-11-16 05:10:52 +00004176 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004177 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004178 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004179 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004180 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004181 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00004182
Chris Lattner3f40e232009-11-29 00:51:17 +00004183 if (LHSCst == RHSCst && LHSCC == RHSCC) {
4184 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4185 // where C is a power of 2
4186 if (LHSCC == ICmpInst::ICMP_ULT &&
4187 LHSCst->getValue().isPowerOf2()) {
4188 Value *NewOr = Builder->CreateOr(Val, Val2);
4189 return new ICmpInst(LHSCC, NewOr, LHSCst);
4190 }
4191
4192 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4193 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4194 Value *NewOr = Builder->CreateOr(Val, Val2);
4195 return new ICmpInst(LHSCC, NewOr, LHSCst);
4196 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00004197 }
4198
4199 // From here on, we only handle:
4200 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4201 if (Val != Val2) return 0;
4202
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004203 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4204 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4205 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4206 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4207 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4208 return 0;
4209
4210 // We can't fold (ugt x, C) & (sgt x, C2).
4211 if (!PredicatesFoldable(LHSCC, RHSCC))
4212 return 0;
4213
4214 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00004215 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004216 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004217 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004218 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00004219 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004220 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00004221 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4222
4223 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004224 std::swap(LHS, RHS);
4225 std::swap(LHSCst, RHSCst);
4226 std::swap(LHSCC, RHSCC);
4227 }
4228
4229 // At this point, we know we have have two icmp instructions
4230 // comparing a value against two constants and and'ing the result
4231 // together. Because of the above check, we know that we only have
4232 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4233 // (from the FoldICmpLogical check above), that the two constants
4234 // are not equal and that the larger constant is on the RHS
4235 assert(LHSCst != RHSCst && "Compares not folded above?");
4236
4237 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004238 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004239 case ICmpInst::ICMP_EQ:
4240 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004241 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004242 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4243 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4244 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004245 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004246 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4247 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4248 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4249 return ReplaceInstUsesWith(I, LHS);
4250 }
4251 case ICmpInst::ICMP_NE:
4252 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004253 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004254 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00004255 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004256 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004257 break; // (X != 13 & X u< 15) -> no change
4258 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00004259 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004260 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004261 break; // (X != 13 & X s< 15) -> no change
4262 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4263 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4264 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4265 return ReplaceInstUsesWith(I, RHS);
4266 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004267 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00004268 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004269 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004270 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00004271 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004272 }
4273 break; // (X != 13 & X != 15) -> no change
4274 }
4275 break;
4276 case ICmpInst::ICMP_ULT:
4277 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004278 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004279 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4280 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004281 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004282 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4283 break;
4284 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4285 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4286 return ReplaceInstUsesWith(I, LHS);
4287 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4288 break;
4289 }
4290 break;
4291 case ICmpInst::ICMP_SLT:
4292 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004293 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004294 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4295 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004296 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004297 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4298 break;
4299 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4300 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4301 return ReplaceInstUsesWith(I, LHS);
4302 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4303 break;
4304 }
4305 break;
4306 case ICmpInst::ICMP_UGT:
4307 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004308 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004309 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4310 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4311 return ReplaceInstUsesWith(I, RHS);
4312 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4313 break;
4314 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004315 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004316 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004317 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004318 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004319 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004320 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004321 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4322 break;
4323 }
4324 break;
4325 case ICmpInst::ICMP_SGT:
4326 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004327 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004328 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4329 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4330 return ReplaceInstUsesWith(I, RHS);
4331 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4332 break;
4333 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004334 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004335 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004336 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004337 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004338 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004339 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004340 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4341 break;
4342 }
4343 break;
4344 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004345
4346 return 0;
4347}
4348
Chris Lattner42d1be02009-07-23 05:14:02 +00004349Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4350 FCmpInst *RHS) {
4351
4352 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4353 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4354 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4355 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4356 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4357 // If either of the constants are nans, then the whole thing returns
4358 // false.
4359 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004360 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004361 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004362 LHS->getOperand(0), RHS->getOperand(0));
4363 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004364
4365 // Handle vector zeros. This occurs because the canonical form of
4366 // "fcmp ord x,x" is "fcmp ord x, 0".
4367 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4368 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004369 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004370 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004371 return 0;
4372 }
4373
4374 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4375 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4376 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4377
4378
4379 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4380 // Swap RHS operands to match LHS.
4381 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4382 std::swap(Op1LHS, Op1RHS);
4383 }
4384
4385 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4386 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4387 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004388 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004389
4390 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004391 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004392 if (Op0CC == FCmpInst::FCMP_TRUE)
4393 return ReplaceInstUsesWith(I, RHS);
4394 if (Op1CC == FCmpInst::FCMP_TRUE)
4395 return ReplaceInstUsesWith(I, LHS);
4396
4397 bool Op0Ordered;
4398 bool Op1Ordered;
4399 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4400 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4401 if (Op1Pred == 0) {
4402 std::swap(LHS, RHS);
4403 std::swap(Op0Pred, Op1Pred);
4404 std::swap(Op0Ordered, Op1Ordered);
4405 }
4406 if (Op0Pred == 0) {
4407 // uno && ueq -> uno && (uno || eq) -> ueq
4408 // ord && olt -> ord && (ord && lt) -> olt
4409 if (Op0Ordered == Op1Ordered)
4410 return ReplaceInstUsesWith(I, RHS);
4411
4412 // uno && oeq -> uno && (ord && eq) -> false
4413 // uno && ord -> false
4414 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004415 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004416 // ord && ueq -> ord && (uno || eq) -> oeq
4417 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4418 Op0LHS, Op0RHS, Context));
4419 }
4420 }
4421
4422 return 0;
4423}
4424
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004425
Chris Lattner7e708292002-06-25 16:13:24 +00004426Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004427 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004428 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004429
Chris Lattnerd06094f2009-11-10 00:55:12 +00004430 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4431 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004432
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004433 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004434 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004435 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00004436 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00004437
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004438 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004439 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004440 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004441
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004442 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004443 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004444 Value *Op0LHS = Op0I->getOperand(0);
4445 Value *Op0RHS = Op0I->getOperand(1);
4446 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004447 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004448 case Instruction::Xor:
4449 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004450 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004451 if (!Op0I->hasOneUse()) break;
4452
4453 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4454 // Not masking anything out for the LHS, move to RHS.
4455 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4456 Op0RHS->getName()+".masked");
4457 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4458 }
4459 if (!isa<Constant>(Op0RHS) &&
4460 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4461 // Not masking anything out for the RHS, move to LHS.
4462 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4463 Op0LHS->getName()+".masked");
4464 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004465 }
4466
Chris Lattner6e7ba452005-01-01 16:22:27 +00004467 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004468 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004469 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4470 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4471 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4472 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004473 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004474 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004475 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004476 break;
4477
4478 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004479 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4480 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4481 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4482 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004483 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004484
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004485 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4486 // has 1's for all bits that the subtraction with A might affect.
4487 if (Op0I->hasOneUse()) {
4488 uint32_t BitWidth = AndRHSMask.getBitWidth();
4489 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4490 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4491
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004492 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004493 if (!(A && A->isZero()) && // avoid infinite recursion.
4494 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004495 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004496 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4497 }
4498 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004499 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004500
4501 case Instruction::Shl:
4502 case Instruction::LShr:
4503 // (1 << x) & 1 --> zext(x == 0)
4504 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004505 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004506 Value *NewICmp =
4507 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004508 return new ZExtInst(NewICmp, I.getType());
4509 }
4510 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004511 }
4512
Chris Lattner58403262003-07-23 19:25:52 +00004513 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004514 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004515 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004516 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004517 // If this is an integer truncation or change from signed-to-unsigned, and
4518 // if the source is an and/or with immediate, transform it. This
4519 // frequently occurs for bitfield accesses.
4520 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004521 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004522 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004523 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004524 if (CastOp->getOpcode() == Instruction::And) {
4525 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004526 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4527 // This will fold the two constants together, which may allow
4528 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004529 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004530 CastOp->getOperand(0), I.getType(),
4531 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004532 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004533 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004534 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004535 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004536 } else if (CastOp->getOpcode() == Instruction::Or) {
4537 // Change: and (cast (or X, C1) to T), C2
4538 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004539 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004540 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004541 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004542 return ReplaceInstUsesWith(I, AndRHS);
4543 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004544 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004545 }
Chris Lattner06782f82003-07-23 19:36:21 +00004546 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004547
4548 // Try to fold constant and into select arguments.
4549 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004550 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004551 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004552 if (isa<PHINode>(Op0))
4553 if (Instruction *NV = FoldOpIntoPhi(I))
4554 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004555 }
4556
Chris Lattner5b62aa72004-06-18 06:07:51 +00004557
Misha Brukmancb6267b2004-07-30 12:50:08 +00004558 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00004559 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4560 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4561 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4562 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4563 I.getName()+".demorgan");
4564 return BinaryOperator::CreateNot(Or);
4565 }
4566
Chris Lattner2082ad92006-02-13 23:07:23 +00004567 {
Chris Lattner003b6202007-06-15 05:58:24 +00004568 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004569 // (A|B) & ~(A&B) -> A^B
4570 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4571 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4572 ((A == C && B == D) || (A == D && B == C)))
4573 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004574
Chris Lattnerd06094f2009-11-10 00:55:12 +00004575 // ~(A&B) & (A|B) -> A^B
4576 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4577 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4578 ((A == C && B == D) || (A == D && B == C)))
4579 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00004580
4581 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004582 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004583 if (A == Op1) { // (A^B)&A -> A&(A^B)
4584 I.swapOperands(); // Simplify below
4585 std::swap(Op0, Op1);
4586 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4587 cast<BinaryOperator>(Op0)->swapOperands();
4588 I.swapOperands(); // Simplify below
4589 std::swap(Op0, Op1);
4590 }
4591 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004592
Chris Lattner64daab52006-04-01 08:03:55 +00004593 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004594 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004595 if (B == Op0) { // B&(A^B) -> B&(B^A)
4596 cast<BinaryOperator>(Op1)->swapOperands();
4597 std::swap(A, B);
4598 }
Chris Lattner74381062009-08-30 07:44:24 +00004599 if (A == Op0) // A&(A^B) -> A & ~B
4600 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004601 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004602
4603 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004604 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4605 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004606 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004607 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4608 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004609 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004610 }
4611
Reid Spencere4d87aa2006-12-23 06:05:41 +00004612 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4613 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004614 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004615 return R;
4616
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004617 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4618 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4619 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004620 }
4621
Chris Lattner6fc205f2006-05-05 06:39:07 +00004622 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004623 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4624 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4625 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4626 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004627 if (SrcTy == Op1C->getOperand(0)->getType() &&
4628 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004629 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004630 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4631 I.getType(), TD) &&
4632 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4633 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004634 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4635 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004636 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004637 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004638 }
Chris Lattnere511b742006-11-14 07:46:50 +00004639
4640 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004641 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4642 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4643 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004644 SI0->getOperand(1) == SI1->getOperand(1) &&
4645 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004646 Value *NewOp =
4647 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4648 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004649 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004650 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004651 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004652 }
4653
Evan Cheng8db90722008-10-14 17:15:11 +00004654 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004655 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004656 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4657 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4658 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004659 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004660
Chris Lattner7e708292002-06-25 16:13:24 +00004661 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004662}
4663
Chris Lattner8c34cd22008-10-05 02:13:19 +00004664/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4665/// capable of providing pieces of a bswap. The subexpression provides pieces
4666/// of a bswap if it is proven that each of the non-zero bytes in the output of
4667/// the expression came from the corresponding "byte swapped" byte in some other
4668/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4669/// we know that the expression deposits the low byte of %X into the high byte
4670/// of the bswap result and that all other bytes are zero. This expression is
4671/// accepted, the high byte of ByteValues is set to X to indicate a correct
4672/// match.
4673///
4674/// This function returns true if the match was unsuccessful and false if so.
4675/// On entry to the function the "OverallLeftShift" is a signed integer value
4676/// indicating the number of bytes that the subexpression is later shifted. For
4677/// example, if the expression is later right shifted by 16 bits, the
4678/// OverallLeftShift value would be -2 on entry. This is used to specify which
4679/// byte of ByteValues is actually being set.
4680///
4681/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4682/// byte is masked to zero by a user. For example, in (X & 255), X will be
4683/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4684/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4685/// always in the local (OverallLeftShift) coordinate space.
4686///
4687static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4688 SmallVector<Value*, 8> &ByteValues) {
4689 if (Instruction *I = dyn_cast<Instruction>(V)) {
4690 // If this is an or instruction, it may be an inner node of the bswap.
4691 if (I->getOpcode() == Instruction::Or) {
4692 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4693 ByteValues) ||
4694 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4695 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004696 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004697
4698 // If this is a logical shift by a constant multiple of 8, recurse with
4699 // OverallLeftShift and ByteMask adjusted.
4700 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4701 unsigned ShAmt =
4702 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4703 // Ensure the shift amount is defined and of a byte value.
4704 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4705 return true;
4706
4707 unsigned ByteShift = ShAmt >> 3;
4708 if (I->getOpcode() == Instruction::Shl) {
4709 // X << 2 -> collect(X, +2)
4710 OverallLeftShift += ByteShift;
4711 ByteMask >>= ByteShift;
4712 } else {
4713 // X >>u 2 -> collect(X, -2)
4714 OverallLeftShift -= ByteShift;
4715 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004716 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004717 }
4718
4719 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4720 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4721
4722 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4723 ByteValues);
4724 }
4725
4726 // If this is a logical 'and' with a mask that clears bytes, clear the
4727 // corresponding bytes in ByteMask.
4728 if (I->getOpcode() == Instruction::And &&
4729 isa<ConstantInt>(I->getOperand(1))) {
4730 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4731 unsigned NumBytes = ByteValues.size();
4732 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4733 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4734
4735 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4736 // If this byte is masked out by a later operation, we don't care what
4737 // the and mask is.
4738 if ((ByteMask & (1 << i)) == 0)
4739 continue;
4740
4741 // If the AndMask is all zeros for this byte, clear the bit.
4742 APInt MaskB = AndMask & Byte;
4743 if (MaskB == 0) {
4744 ByteMask &= ~(1U << i);
4745 continue;
4746 }
4747
4748 // If the AndMask is not all ones for this byte, it's not a bytezap.
4749 if (MaskB != Byte)
4750 return true;
4751
4752 // Otherwise, this byte is kept.
4753 }
4754
4755 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4756 ByteValues);
4757 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004758 }
4759
Chris Lattner8c34cd22008-10-05 02:13:19 +00004760 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4761 // the input value to the bswap. Some observations: 1) if more than one byte
4762 // is demanded from this input, then it could not be successfully assembled
4763 // into a byteswap. At least one of the two bytes would not be aligned with
4764 // their ultimate destination.
4765 if (!isPowerOf2_32(ByteMask)) return true;
4766 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004767
Chris Lattner8c34cd22008-10-05 02:13:19 +00004768 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4769 // is demanded, it needs to go into byte 0 of the result. This means that the
4770 // byte needs to be shifted until it lands in the right byte bucket. The
4771 // shift amount depends on the position: if the byte is coming from the high
4772 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4773 // low part, it must be shifted left.
4774 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4775 if (InputByteNo < ByteValues.size()/2) {
4776 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4777 return true;
4778 } else {
4779 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4780 return true;
4781 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004782
4783 // If the destination byte value is already defined, the values are or'd
4784 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004785 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004786 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004787 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004788 return false;
4789}
4790
4791/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4792/// If so, insert the new bswap intrinsic and return it.
4793Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004794 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004795 if (!ITy || ITy->getBitWidth() % 16 ||
4796 // ByteMask only allows up to 32-byte values.
4797 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004798 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004799
4800 /// ByteValues - For each byte of the result, we keep track of which value
4801 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004802 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004803 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004804
4805 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004806 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4807 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004808 return 0;
4809
4810 // Check to see if all of the bytes come from the same value.
4811 Value *V = ByteValues[0];
4812 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4813
4814 // Check to make sure that all of the bytes come from the same value.
4815 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4816 if (ByteValues[i] != V)
4817 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004818 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004819 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004820 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004821 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004822}
4823
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004824/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4825/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4826/// we can simplify this expression to "cond ? C : D or B".
4827static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004828 Value *C, Value *D,
4829 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004830 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004831 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004832 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004833 return 0;
4834
Chris Lattnera6a474d2008-11-16 04:26:55 +00004835 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004836 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004837 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004838 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004839 return SelectInst::Create(Cond, C, B);
4840 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004841 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004842 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004843 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004844 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004845 return 0;
4846}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004847
Chris Lattner69d4ced2008-11-16 05:20:07 +00004848/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4849Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4850 ICmpInst *LHS, ICmpInst *RHS) {
4851 Value *Val, *Val2;
4852 ConstantInt *LHSCst, *RHSCst;
4853 ICmpInst::Predicate LHSCC, RHSCC;
4854
4855 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00004856 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4857 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004858 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00004859
4860
4861 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4862 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4863 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4864 Value *NewOr = Builder->CreateOr(Val, Val2);
4865 return new ICmpInst(LHSCC, NewOr, LHSCst);
4866 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00004867
4868 // From here on, we only handle:
4869 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4870 if (Val != Val2) return 0;
4871
4872 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4873 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4874 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4875 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4876 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4877 return 0;
4878
4879 // We can't fold (ugt x, C) | (sgt x, C2).
4880 if (!PredicatesFoldable(LHSCC, RHSCC))
4881 return 0;
4882
4883 // Ensure that the larger constant is on the RHS.
4884 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004885 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004886 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004887 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004888 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4889 else
4890 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4891
4892 if (ShouldSwap) {
4893 std::swap(LHS, RHS);
4894 std::swap(LHSCst, RHSCst);
4895 std::swap(LHSCC, RHSCC);
4896 }
4897
4898 // At this point, we know we have have two icmp instructions
4899 // comparing a value against two constants and or'ing the result
4900 // together. Because of the above check, we know that we only have
4901 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4902 // FoldICmpLogical check above), that the two constants are not
4903 // equal.
4904 assert(LHSCst != RHSCst && "Compares not folded above?");
4905
4906 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004907 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004908 case ICmpInst::ICMP_EQ:
4909 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004910 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004911 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004912 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004913 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004914 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004915 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004916 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004917 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004918 }
4919 break; // (X == 13 | X == 15) -> no change
4920 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4921 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4922 break;
4923 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4924 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4925 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4926 return ReplaceInstUsesWith(I, RHS);
4927 }
4928 break;
4929 case ICmpInst::ICMP_NE:
4930 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004931 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004932 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4933 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4934 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4935 return ReplaceInstUsesWith(I, LHS);
4936 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4937 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4938 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004939 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004940 }
4941 break;
4942 case ICmpInst::ICMP_ULT:
4943 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004944 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004945 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4946 break;
4947 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4948 // If RHSCst is [us]MAXINT, it is always false. Not handling
4949 // this can cause overflow.
4950 if (RHSCst->isMaxValue(false))
4951 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004952 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004953 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004954 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4955 break;
4956 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4957 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4958 return ReplaceInstUsesWith(I, RHS);
4959 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4960 break;
4961 }
4962 break;
4963 case ICmpInst::ICMP_SLT:
4964 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004965 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004966 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4967 break;
4968 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4969 // If RHSCst is [us]MAXINT, it is always false. Not handling
4970 // this can cause overflow.
4971 if (RHSCst->isMaxValue(true))
4972 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004973 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004974 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004975 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4976 break;
4977 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4978 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4979 return ReplaceInstUsesWith(I, RHS);
4980 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4981 break;
4982 }
4983 break;
4984 case ICmpInst::ICMP_UGT:
4985 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004986 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004987 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4988 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4989 return ReplaceInstUsesWith(I, LHS);
4990 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4991 break;
4992 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4993 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004994 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004995 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4996 break;
4997 }
4998 break;
4999 case ICmpInst::ICMP_SGT:
5000 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005001 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00005002 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
5003 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
5004 return ReplaceInstUsesWith(I, LHS);
5005 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
5006 break;
5007 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
5008 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005009 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00005010 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
5011 break;
5012 }
5013 break;
5014 }
5015 return 0;
5016}
5017
Chris Lattner5414cc52009-07-23 05:46:22 +00005018Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
5019 FCmpInst *RHS) {
5020 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
5021 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
5022 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
5023 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
5024 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
5025 // If either of the constants are nans, then the whole thing returns
5026 // true.
5027 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00005028 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00005029
5030 // Otherwise, no need to compare the two constants, compare the
5031 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005032 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00005033 LHS->getOperand(0), RHS->getOperand(0));
5034 }
5035
5036 // Handle vector zeros. This occurs because the canonical form of
5037 // "fcmp uno x,x" is "fcmp uno x, 0".
5038 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
5039 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005040 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00005041 LHS->getOperand(0), RHS->getOperand(0));
5042
5043 return 0;
5044 }
5045
5046 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
5047 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
5048 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
5049
5050 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
5051 // Swap RHS operands to match LHS.
5052 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
5053 std::swap(Op1LHS, Op1RHS);
5054 }
5055 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
5056 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
5057 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005058 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00005059 Op0LHS, Op0RHS);
5060 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005061 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00005062 if (Op0CC == FCmpInst::FCMP_FALSE)
5063 return ReplaceInstUsesWith(I, RHS);
5064 if (Op1CC == FCmpInst::FCMP_FALSE)
5065 return ReplaceInstUsesWith(I, LHS);
5066 bool Op0Ordered;
5067 bool Op1Ordered;
5068 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
5069 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
5070 if (Op0Ordered == Op1Ordered) {
5071 // If both are ordered or unordered, return a new fcmp with
5072 // or'ed predicates.
5073 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5074 Op0LHS, Op0RHS, Context);
5075 if (Instruction *I = dyn_cast<Instruction>(RV))
5076 return I;
5077 // Otherwise, it's a constant boolean value...
5078 return ReplaceInstUsesWith(I, RV);
5079 }
5080 }
5081 return 0;
5082}
5083
Bill Wendlinga698a472008-12-01 08:23:25 +00005084/// FoldOrWithConstants - This helper function folds:
5085///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005086/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00005087///
5088/// into:
5089///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005090/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00005091///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005092/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00005093Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00005094 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00005095 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5096 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005097
Bill Wendling286a0542008-12-02 06:24:20 +00005098 Value *V1 = 0;
5099 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005100 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005101
Bill Wendling29976b92008-12-02 06:18:11 +00005102 APInt Xor = CI1->getValue() ^ CI2->getValue();
5103 if (!Xor.isAllOnesValue()) return 0;
5104
Bill Wendling286a0542008-12-02 06:24:20 +00005105 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00005106 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00005107 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00005108 }
5109
5110 return 0;
5111}
5112
Chris Lattner7e708292002-06-25 16:13:24 +00005113Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005114 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005115 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005116
Chris Lattnerd06094f2009-11-10 00:55:12 +00005117 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5118 return ReplaceInstUsesWith(I, V);
5119
5120
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005121 // See if we can simplify any instructions used by the instruction whose sole
5122 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005123 if (SimplifyDemandedInstructionBits(I))
5124 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00005125
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005126 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00005127 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005128 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005129 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005130 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005131 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005132 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005133 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005134 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005135 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005136
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005137 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005138 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005139 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005140 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005141 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005142 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005143 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005144 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005145
5146 // Try to fold constant and into select arguments.
5147 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005148 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005149 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005150 if (isa<PHINode>(Op0))
5151 if (Instruction *NV = FoldOpIntoPhi(I))
5152 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005153 }
5154
Chris Lattner4f637d42006-01-06 17:59:59 +00005155 Value *A = 0, *B = 0;
5156 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005157
Chris Lattner6423d4c2006-07-10 20:25:24 +00005158 // (A | B) | C and A | (B | C) -> bswap if possible.
5159 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00005160 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5161 match(Op1, m_Or(m_Value(), m_Value())) ||
5162 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5163 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00005164 if (Instruction *BSwap = MatchBSwap(I))
5165 return BSwap;
5166 }
5167
Chris Lattner6e4c6492005-05-09 04:58:36 +00005168 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005169 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005170 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005171 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005172 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00005173 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005174 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005175 }
5176
5177 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005178 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005179 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005180 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005181 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00005182 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005183 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005184 }
5185
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005186 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00005187 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005188 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5189 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005190 Value *V1 = 0, *V2 = 0, *V3 = 0;
5191 C1 = dyn_cast<ConstantInt>(C);
5192 C2 = dyn_cast<ConstantInt>(D);
5193 if (C1 && C2) { // (A & C1)|(B & C2)
5194 // If we have: ((V + N) & C1) | (V & C2)
5195 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5196 // replace with V+N.
5197 if (C1->getValue() == ~C2->getValue()) {
5198 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00005199 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005200 // Add commutes, try both ways.
5201 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5202 return ReplaceInstUsesWith(I, A);
5203 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5204 return ReplaceInstUsesWith(I, A);
5205 }
5206 // Or commutes, try both ways.
5207 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005208 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005209 // Add commutes, try both ways.
5210 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5211 return ReplaceInstUsesWith(I, B);
5212 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5213 return ReplaceInstUsesWith(I, B);
5214 }
5215 }
Chris Lattnere4412c12010-01-04 06:03:59 +00005216
5217 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
5218 // iff (C1&C2) == 0 and (N&~C1) == 0
5219 if ((C1->getValue() & C2->getValue()) == 0) {
5220 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
5221 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
5222 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
5223 return BinaryOperator::CreateAnd(A,
5224 ConstantInt::get(A->getContext(),
5225 C1->getValue()|C2->getValue()));
5226 // Or commutes, try both ways.
5227 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
5228 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
5229 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
5230 return BinaryOperator::CreateAnd(B,
5231 ConstantInt::get(B->getContext(),
5232 C1->getValue()|C2->getValue()));
5233 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00005234 }
5235
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005236 // Check to see if we have any common things being and'ed. If so, find the
5237 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005238 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
Chris Lattnere4412c12010-01-04 06:03:59 +00005239 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005240 if (A == B) // (A & C)|(A & D) == A & (C|D)
5241 V1 = A, V2 = C, V3 = D;
5242 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5243 V1 = A, V2 = B, V3 = C;
5244 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5245 V1 = C, V2 = A, V3 = D;
5246 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5247 V1 = C, V2 = A, V3 = B;
5248
5249 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00005250 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005251 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00005252 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005253 }
Dan Gohmanb493b272008-10-28 22:38:57 +00005254
Dan Gohman1975d032008-10-30 20:40:10 +00005255 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005256 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005257 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005258 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005259 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005260 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005261 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005262 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005263 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00005264
Bill Wendlingb01865c2008-11-30 13:52:49 +00005265 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005266 if ((match(C, m_Not(m_Specific(D))) &&
5267 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005268 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005269 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005270 if ((match(A, m_Not(m_Specific(D))) &&
5271 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005272 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005273 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005274 if ((match(C, m_Not(m_Specific(B))) &&
5275 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005276 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005277 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005278 if ((match(A, m_Not(m_Specific(B))) &&
5279 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005280 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005281 }
Chris Lattnere511b742006-11-14 07:46:50 +00005282
5283 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00005284 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5285 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5286 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00005287 SI0->getOperand(1) == SI1->getOperand(1) &&
5288 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005289 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5290 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005291 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005292 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005293 }
5294 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005295
Bill Wendlingb3833d12008-12-01 01:07:11 +00005296 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005297 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5298 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005299 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005300 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005301 }
5302 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005303 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5304 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005305 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005306 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005307 }
5308
Chris Lattnerd06094f2009-11-10 00:55:12 +00005309 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5310 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5311 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5312 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5313 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5314 I.getName()+".demorgan");
5315 return BinaryOperator::CreateNot(And);
5316 }
Chris Lattnera2881962003-02-18 19:28:33 +00005317
Reid Spencere4d87aa2006-12-23 06:05:41 +00005318 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5319 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005320 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005321 return R;
5322
Chris Lattner69d4ced2008-11-16 05:20:07 +00005323 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5324 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5325 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005326 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005327
5328 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005329 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005330 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005331 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005332 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5333 !isa<ICmpInst>(Op1C->getOperand(0))) {
5334 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005335 if (SrcTy == Op1C->getOperand(0)->getType() &&
5336 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005337 // Only do this if the casts both really cause code to be
5338 // generated.
5339 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5340 I.getType(), TD) &&
5341 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5342 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005343 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5344 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005345 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005346 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005347 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005348 }
Chris Lattner99c65742007-10-24 05:38:08 +00005349 }
5350
5351
5352 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5353 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005354 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5355 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5356 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005357 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005358
Chris Lattner7e708292002-06-25 16:13:24 +00005359 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005360}
5361
Dan Gohman844731a2008-05-13 00:00:25 +00005362namespace {
5363
Chris Lattnerc317d392004-02-16 01:20:27 +00005364// XorSelf - Implements: X ^ X --> 0
5365struct XorSelf {
5366 Value *RHS;
5367 XorSelf(Value *rhs) : RHS(rhs) {}
5368 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5369 Instruction *apply(BinaryOperator &Xor) const {
5370 return &Xor;
5371 }
5372};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005373
Dan Gohman844731a2008-05-13 00:00:25 +00005374}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005375
Chris Lattner7e708292002-06-25 16:13:24 +00005376Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005377 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005378 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005379
Evan Chengd34af782008-03-25 20:07:13 +00005380 if (isa<UndefValue>(Op1)) {
5381 if (isa<UndefValue>(Op0))
5382 // Handle undef ^ undef -> 0 special case. This is a common
5383 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005384 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005385 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005386 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005387
Chris Lattnerc317d392004-02-16 01:20:27 +00005388 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005389 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005390 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005391 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005392 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005393
5394 // See if we can simplify any instructions used by the instruction whose sole
5395 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005396 if (SimplifyDemandedInstructionBits(I))
5397 return &I;
5398 if (isa<VectorType>(I.getType()))
5399 if (isa<ConstantAggregateZero>(Op1))
5400 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005401
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005402 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005403 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005404 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5405 if (Op0I->getOpcode() == Instruction::And ||
5406 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005407 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5408 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5409 if (dyn_castNotVal(Op0I->getOperand(1)))
5410 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005411 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005412 Value *NotY =
5413 Builder->CreateNot(Op0I->getOperand(1),
5414 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005415 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005416 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005417 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005418 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005419
5420 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5421 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5422 if (isFreeToInvert(Op0I->getOperand(0)) &&
5423 isFreeToInvert(Op0I->getOperand(1))) {
5424 Value *NotX =
5425 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5426 Value *NotY =
5427 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5428 if (Op0I->getOpcode() == Instruction::And)
5429 return BinaryOperator::CreateOr(NotX, NotY);
5430 return BinaryOperator::CreateAnd(NotX, NotY);
5431 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005432 }
5433 }
5434 }
5435
5436
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005437 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005438 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005439 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005440 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005441 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005442 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005443
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005444 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005445 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005446 FCI->getOperand(0), FCI->getOperand(1));
5447 }
5448
Nick Lewycky517e1f52008-05-31 19:01:33 +00005449 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5450 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5451 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5452 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5453 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005454 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5455 (RHS == ConstantExpr::getCast(Opcode,
5456 ConstantInt::getTrue(*Context),
5457 Op0C->getDestTy()))) {
5458 CI->setPredicate(CI->getInversePredicate());
5459 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005460 }
5461 }
5462 }
5463 }
5464
Reid Spencere4d87aa2006-12-23 06:05:41 +00005465 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005466 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005467 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5468 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005469 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5470 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005471 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005472 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005473 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005474
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005475 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005476 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005477 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005478 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005479 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005480 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005481 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005482 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005483 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005484 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005485 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005486 Constant *C = ConstantInt::get(*Context,
5487 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005488 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005489
Chris Lattner7c4049c2004-01-12 19:35:11 +00005490 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005491 } else if (Op0I->getOpcode() == Instruction::Or) {
5492 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005493 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005494 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005495 // Anything in both C1 and C2 is known to be zero, remove it from
5496 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005497 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5498 NewRHS = ConstantExpr::getAnd(NewRHS,
5499 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005500 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005501 I.setOperand(0, Op0I->getOperand(0));
5502 I.setOperand(1, NewRHS);
5503 return &I;
5504 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005505 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005506 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005507 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005508
5509 // Try to fold constant and into select arguments.
5510 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005511 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005512 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005513 if (isa<PHINode>(Op0))
5514 if (Instruction *NV = FoldOpIntoPhi(I))
5515 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005516 }
5517
Dan Gohman186a6362009-08-12 16:04:34 +00005518 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005519 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005520 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005521
Dan Gohman186a6362009-08-12 16:04:34 +00005522 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005523 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005524 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005525
Chris Lattner318bf792007-03-18 22:51:34 +00005526
5527 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5528 if (Op1I) {
5529 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005530 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005531 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005532 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005533 I.swapOperands();
5534 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005535 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005536 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005537 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005538 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005539 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005540 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005541 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005542 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005543 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005544 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005545 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005546 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005547 std::swap(A, B);
5548 }
Chris Lattner318bf792007-03-18 22:51:34 +00005549 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005550 I.swapOperands(); // Simplified below.
5551 std::swap(Op0, Op1);
5552 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005553 }
Chris Lattner318bf792007-03-18 22:51:34 +00005554 }
5555
5556 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5557 if (Op0I) {
5558 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005559 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005560 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005561 if (A == Op1) // (B|A)^B == (A|B)^B
5562 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005563 if (B == Op1) // (A|B)^B == A & ~B
5564 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005565 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005566 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005567 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005568 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005569 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005570 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005571 if (A == Op1) // (A&B)^A -> (B&A)^A
5572 std::swap(A, B);
5573 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005574 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005575 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005576 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005577 }
Chris Lattner318bf792007-03-18 22:51:34 +00005578 }
5579
5580 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5581 if (Op0I && Op1I && Op0I->isShift() &&
5582 Op0I->getOpcode() == Op1I->getOpcode() &&
5583 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5584 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005585 Value *NewOp =
5586 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5587 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005588 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005589 Op1I->getOperand(1));
5590 }
5591
5592 if (Op0I && Op1I) {
5593 Value *A, *B, *C, *D;
5594 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005595 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5596 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005597 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005598 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005599 }
5600 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005601 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5602 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005603 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005604 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005605 }
5606
5607 // (A & B)^(C & D)
5608 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005609 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5610 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005611 // (X & Y)^(X & Y) -> (Y^Z) & X
5612 Value *X = 0, *Y = 0, *Z = 0;
5613 if (A == C)
5614 X = A, Y = B, Z = D;
5615 else if (A == D)
5616 X = A, Y = B, Z = C;
5617 else if (B == C)
5618 X = B, Y = A, Z = D;
5619 else if (B == D)
5620 X = B, Y = A, Z = C;
5621
5622 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005623 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005624 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005625 }
5626 }
5627 }
5628
Reid Spencere4d87aa2006-12-23 06:05:41 +00005629 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5630 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005631 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005632 return R;
5633
Chris Lattner6fc205f2006-05-05 06:39:07 +00005634 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005635 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005636 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005637 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5638 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005639 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005640 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005641 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5642 I.getType(), TD) &&
5643 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5644 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005645 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5646 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005647 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005648 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005649 }
Chris Lattner99c65742007-10-24 05:38:08 +00005650 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005651
Chris Lattner7e708292002-06-25 16:13:24 +00005652 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005653}
5654
Owen Andersond672ecb2009-07-03 00:17:18 +00005655static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005656 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005657 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005658}
Chris Lattnera96879a2004-09-29 17:40:11 +00005659
Dan Gohman6de29f82009-06-15 22:12:54 +00005660static bool HasAddOverflow(ConstantInt *Result,
5661 ConstantInt *In1, ConstantInt *In2,
5662 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005663 if (IsSigned)
5664 if (In2->getValue().isNegative())
5665 return Result->getValue().sgt(In1->getValue());
5666 else
5667 return Result->getValue().slt(In1->getValue());
5668 else
5669 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005670}
5671
Dan Gohman6de29f82009-06-15 22:12:54 +00005672/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005673/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005674static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005675 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005676 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005677 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005678
Dan Gohman6de29f82009-06-15 22:12:54 +00005679 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5680 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005681 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005682 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5683 ExtractElement(In1, Idx, Context),
5684 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005685 IsSigned))
5686 return true;
5687 }
5688 return false;
5689 }
5690
5691 return HasAddOverflow(cast<ConstantInt>(Result),
5692 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5693 IsSigned);
5694}
5695
5696static bool HasSubOverflow(ConstantInt *Result,
5697 ConstantInt *In1, ConstantInt *In2,
5698 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005699 if (IsSigned)
5700 if (In2->getValue().isNegative())
5701 return Result->getValue().slt(In1->getValue());
5702 else
5703 return Result->getValue().sgt(In1->getValue());
5704 else
5705 return Result->getValue().ugt(In1->getValue());
5706}
5707
Dan Gohman6de29f82009-06-15 22:12:54 +00005708/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5709/// overflowed for this type.
5710static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005711 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005712 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005713 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005714
5715 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5716 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005717 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005718 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5719 ExtractElement(In1, Idx, Context),
5720 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005721 IsSigned))
5722 return true;
5723 }
5724 return false;
5725 }
5726
5727 return HasSubOverflow(cast<ConstantInt>(Result),
5728 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5729 IsSigned);
5730}
5731
Chris Lattner10c0d912008-04-22 02:53:33 +00005732
Reid Spencere4d87aa2006-12-23 06:05:41 +00005733/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005734/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005735Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005736 ICmpInst::Predicate Cond,
5737 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005738 // Look through bitcasts.
5739 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5740 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005741
Chris Lattner574da9b2005-01-13 20:14:25 +00005742 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005743 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005744 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005745 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005746 // know pointers can't overflow since the gep is inbounds. See if we can
5747 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005748 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5749
5750 // If not, synthesize the offset the hard way.
5751 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005752 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005753 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005754 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005755 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005756 // If the base pointers are different, but the indices are the same, just
5757 // compare the base pointer.
5758 if (PtrBase != GEPRHS->getOperand(0)) {
5759 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005760 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005761 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005762 if (IndicesTheSame)
5763 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5764 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5765 IndicesTheSame = false;
5766 break;
5767 }
5768
5769 // If all indices are the same, just compare the base pointers.
5770 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005771 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005772 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005773
5774 // Otherwise, the base pointers are different and the indices are
5775 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005776 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005777 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005778
Chris Lattnere9d782b2005-01-13 22:25:21 +00005779 // If one of the GEPs has all zero indices, recurse.
5780 bool AllZeros = true;
5781 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5782 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5783 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5784 AllZeros = false;
5785 break;
5786 }
5787 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005788 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5789 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005790
5791 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005792 AllZeros = true;
5793 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5794 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5795 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5796 AllZeros = false;
5797 break;
5798 }
5799 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005800 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005801
Chris Lattner4401c9c2005-01-14 00:20:05 +00005802 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5803 // If the GEPs only differ by one index, compare it.
5804 unsigned NumDifferences = 0; // Keep track of # differences.
5805 unsigned DiffOperand = 0; // The operand that differs.
5806 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5807 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005808 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5809 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005810 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005811 NumDifferences = 2;
5812 break;
5813 } else {
5814 if (NumDifferences++) break;
5815 DiffOperand = i;
5816 }
5817 }
5818
5819 if (NumDifferences == 0) // SAME GEP?
5820 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005821 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005822 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005823
Chris Lattner4401c9c2005-01-14 00:20:05 +00005824 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005825 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5826 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005827 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005828 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005829 }
5830 }
5831
Reid Spencere4d87aa2006-12-23 06:05:41 +00005832 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005833 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005834 if (TD &&
5835 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005836 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5837 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005838 Value *L = EmitGEPOffset(GEPLHS, *this);
5839 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005840 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005841 }
5842 }
5843 return 0;
5844}
5845
Chris Lattnera5406232008-05-19 20:18:56 +00005846/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5847///
5848Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5849 Instruction *LHSI,
5850 Constant *RHSC) {
5851 if (!isa<ConstantFP>(RHSC)) return 0;
5852 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5853
5854 // Get the width of the mantissa. We don't want to hack on conversions that
5855 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005856 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005857 if (MantissaWidth == -1) return 0; // Unknown.
5858
5859 // Check to see that the input is converted from an integer type that is small
5860 // enough that preserves all bits. TODO: check here for "known" sign bits.
5861 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00005862 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005863
5864 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005865 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5866 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005867 ++InputSize;
5868
5869 // If the conversion would lose info, don't hack on this.
5870 if ((int)InputSize > MantissaWidth)
5871 return 0;
5872
5873 // Otherwise, we can potentially simplify the comparison. We know that it
5874 // will always come through as an integer value and we know the constant is
5875 // not a NAN (it would have been previously simplified).
5876 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5877
5878 ICmpInst::Predicate Pred;
5879 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005880 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005881 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005882 case FCmpInst::FCMP_OEQ:
5883 Pred = ICmpInst::ICMP_EQ;
5884 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005885 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005886 case FCmpInst::FCMP_OGT:
5887 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5888 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005889 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005890 case FCmpInst::FCMP_OGE:
5891 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5892 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005893 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005894 case FCmpInst::FCMP_OLT:
5895 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5896 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005897 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005898 case FCmpInst::FCMP_OLE:
5899 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5900 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005901 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005902 case FCmpInst::FCMP_ONE:
5903 Pred = ICmpInst::ICMP_NE;
5904 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005905 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005906 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005907 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005908 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005909 }
5910
5911 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5912
5913 // Now we know that the APFloat is a normal number, zero or inf.
5914
Chris Lattner85162782008-05-20 03:50:52 +00005915 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005916 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005917 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005918
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005919 if (!LHSUnsigned) {
5920 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5921 // and large values.
5922 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5923 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5924 APFloat::rmNearestTiesToEven);
5925 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5926 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5927 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005928 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5929 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005930 }
5931 } else {
5932 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5933 // +INF and large values.
5934 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5935 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5936 APFloat::rmNearestTiesToEven);
5937 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5938 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5939 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005940 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5941 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005942 }
Chris Lattnera5406232008-05-19 20:18:56 +00005943 }
5944
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005945 if (!LHSUnsigned) {
5946 // See if the RHS value is < SignedMin.
5947 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5948 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5949 APFloat::rmNearestTiesToEven);
5950 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5951 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5952 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005953 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5954 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005955 }
Chris Lattnera5406232008-05-19 20:18:56 +00005956 }
5957
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005958 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5959 // [0, UMAX], but it may still be fractional. See if it is fractional by
5960 // casting the FP value to the integer value and back, checking for equality.
5961 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005962 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005963 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5964 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005965 if (!RHS.isZero()) {
5966 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005967 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5968 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005969 if (!Equal) {
5970 // If we had a comparison against a fractional value, we have to adjust
5971 // the compare predicate and sometimes the value. RHSC is rounded towards
5972 // zero at this point.
5973 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005974 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005975 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005976 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005977 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005978 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005979 case ICmpInst::ICMP_ULE:
5980 // (float)int <= 4.4 --> int <= 4
5981 // (float)int <= -4.4 --> false
5982 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005983 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005984 break;
5985 case ICmpInst::ICMP_SLE:
5986 // (float)int <= 4.4 --> int <= 4
5987 // (float)int <= -4.4 --> int < -4
5988 if (RHS.isNegative())
5989 Pred = ICmpInst::ICMP_SLT;
5990 break;
5991 case ICmpInst::ICMP_ULT:
5992 // (float)int < -4.4 --> false
5993 // (float)int < 4.4 --> int <= 4
5994 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005995 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005996 Pred = ICmpInst::ICMP_ULE;
5997 break;
5998 case ICmpInst::ICMP_SLT:
5999 // (float)int < -4.4 --> int < -4
6000 // (float)int < 4.4 --> int <= 4
6001 if (!RHS.isNegative())
6002 Pred = ICmpInst::ICMP_SLE;
6003 break;
6004 case ICmpInst::ICMP_UGT:
6005 // (float)int > 4.4 --> int > 4
6006 // (float)int > -4.4 --> true
6007 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00006008 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00006009 break;
6010 case ICmpInst::ICMP_SGT:
6011 // (float)int > 4.4 --> int > 4
6012 // (float)int > -4.4 --> int >= -4
6013 if (RHS.isNegative())
6014 Pred = ICmpInst::ICMP_SGE;
6015 break;
6016 case ICmpInst::ICMP_UGE:
6017 // (float)int >= -4.4 --> true
6018 // (float)int >= 4.4 --> int > 4
6019 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00006020 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00006021 Pred = ICmpInst::ICMP_UGT;
6022 break;
6023 case ICmpInst::ICMP_SGE:
6024 // (float)int >= -4.4 --> int >= -4
6025 // (float)int >= 4.4 --> int > 4
6026 if (!RHS.isNegative())
6027 Pred = ICmpInst::ICMP_SGT;
6028 break;
6029 }
Chris Lattnera5406232008-05-19 20:18:56 +00006030 }
6031 }
6032
6033 // Lower this FP comparison into an appropriate integer version of the
6034 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006035 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00006036}
6037
Chris Lattner1f12e442010-01-02 08:12:04 +00006038/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
6039/// cmp pred (load (gep GV, ...)), cmpcst
6040/// where GV is a global variable with a constant initializer. Try to simplify
Chris Lattner82602bc2010-01-02 20:20:33 +00006041/// this into some simple computation that does not need the load. For example
6042/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006043///
6044/// If AndCst is non-null, then the loaded value is masked with that constant
6045/// before doing the comparison. This handles cases like "A[i]&4 == 0".
Chris Lattner1f12e442010-01-02 08:12:04 +00006046Instruction *InstCombiner::
6047FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006048 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattner56ba7a72010-01-03 03:03:27 +00006049 ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer());
6050 if (Init == 0 || Init->getNumOperands() > 1024) return 0;
Chris Lattner1f12e442010-01-02 08:12:04 +00006051
6052 // There are many forms of this optimization we can handle, for now, just do
6053 // the simple index into a single-dimensional array.
6054 //
Chris Lattner56ba7a72010-01-03 03:03:27 +00006055 // Require: GEP GV, 0, i {{, constant indices}}
6056 if (GEP->getNumOperands() < 3 ||
Chris Lattner1f12e442010-01-02 08:12:04 +00006057 !isa<ConstantInt>(GEP->getOperand(1)) ||
Chris Lattner56ba7a72010-01-03 03:03:27 +00006058 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
6059 isa<Constant>(GEP->getOperand(2)))
Chris Lattner1f12e442010-01-02 08:12:04 +00006060 return 0;
Chris Lattner56ba7a72010-01-03 03:03:27 +00006061
6062 // Check that indices after the variable are constants and in-range for the
6063 // type they index. Collect the indices. This is typically for arrays of
6064 // structs.
6065 SmallVector<unsigned, 4> LaterIndices;
Chris Lattner1f12e442010-01-02 08:12:04 +00006066
Chris Lattner56ba7a72010-01-03 03:03:27 +00006067 const Type *EltTy = cast<ArrayType>(Init->getType())->getElementType();
6068 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
6069 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
6070 if (Idx == 0) return 0; // Variable index.
6071
6072 uint64_t IdxVal = Idx->getZExtValue();
6073 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
6074
6075 if (const StructType *STy = dyn_cast<StructType>(EltTy))
6076 EltTy = STy->getElementType(IdxVal);
6077 else if (const ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
6078 if (IdxVal >= ATy->getNumElements()) return 0;
6079 EltTy = ATy->getElementType();
6080 } else {
6081 return 0; // Unknown type.
6082 }
6083
6084 LaterIndices.push_back(IdxVal);
6085 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006086
Chris Lattner82602bc2010-01-02 20:20:33 +00006087 enum { Overdefined = -3, Undefined = -2 };
6088
Chris Lattner1f12e442010-01-02 08:12:04 +00006089 // Variables for our state machines.
6090
Chris Lattnerbef37372010-01-02 09:35:17 +00006091 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
6092 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
Chris Lattner82602bc2010-01-02 20:20:33 +00006093 // and 87 is the second (and last) index. FirstTrueElement is -2 when
Chris Lattnerbef37372010-01-02 09:35:17 +00006094 // undefined, otherwise set to the first true element. SecondTrueElement is
Chris Lattner82602bc2010-01-02 20:20:33 +00006095 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
6096 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
Chris Lattner1f12e442010-01-02 08:12:04 +00006097
Chris Lattnerbef37372010-01-02 09:35:17 +00006098 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
6099 // form "i != 47 & i != 87". Same state transitions as for true elements.
Chris Lattner82602bc2010-01-02 20:20:33 +00006100 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Chris Lattner1f12e442010-01-02 08:12:04 +00006101
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006102 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
6103 /// define a state machine that triggers for ranges of values that the index
6104 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
6105 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
6106 /// index in the range (inclusive). We use -2 for undefined here because we
6107 /// use relative comparisons and don't want 0-1 to match -1.
6108 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
6109
Chris Lattner10d514e2010-01-02 08:56:52 +00006110 // MagicBitvector - This is a magic bitvector where we set a bit if the
6111 // comparison is true for element 'i'. If there are 64 elements or less in
6112 // the array, this will fully represent all the comparison results.
6113 uint64_t MagicBitvector = 0;
6114
6115
Chris Lattner1f12e442010-01-02 08:12:04 +00006116 // Scan the array and see if one of our patterns matches.
6117 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
6118 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006119 Constant *Elt = Init->getOperand(i);
6120
Chris Lattner56ba7a72010-01-03 03:03:27 +00006121 // If this is indexing an array of structures, get the structure element.
6122 if (!LaterIndices.empty())
6123 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices.data(),
6124 LaterIndices.size());
6125
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006126 // If the element is masked, handle it.
6127 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
6128
Chris Lattner1f12e442010-01-02 08:12:04 +00006129 // Find out if the comparison would be true or false for the i'th element.
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006130 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Chris Lattner1f12e442010-01-02 08:12:04 +00006131 CompareRHS, TD);
6132 // If the result is undef for this element, ignore it.
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006133 if (isa<UndefValue>(C)) {
6134 // Extend range state machines to cover this element in case there is an
6135 // undef in the middle of the range.
6136 if (TrueRangeEnd == (int)i-1)
6137 TrueRangeEnd = i;
6138 if (FalseRangeEnd == (int)i-1)
6139 FalseRangeEnd = i;
6140 continue;
6141 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006142
6143 // If we can't compute the result for any of the elements, we have to give
6144 // up evaluating the entire conditional.
6145 if (!isa<ConstantInt>(C)) return 0;
6146
6147 // Otherwise, we know if the comparison is true or false for this element,
6148 // update our state machines.
6149 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
6150
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006151 // State machine for single/double/range index comparison.
Chris Lattner1f12e442010-01-02 08:12:04 +00006152 if (IsTrueForElt) {
Chris Lattnerbef37372010-01-02 09:35:17 +00006153 // Update the TrueElement state machine.
Chris Lattner82602bc2010-01-02 20:20:33 +00006154 if (FirstTrueElement == Undefined)
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006155 FirstTrueElement = TrueRangeEnd = i; // First true element.
6156 else {
6157 // Update double-compare state machine.
6158 if (SecondTrueElement == Undefined)
6159 SecondTrueElement = i;
6160 else
6161 SecondTrueElement = Overdefined;
6162
6163 // Update range state machine.
6164 if (TrueRangeEnd == (int)i-1)
6165 TrueRangeEnd = i;
6166 else
6167 TrueRangeEnd = Overdefined;
6168 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006169 } else {
Chris Lattnerbef37372010-01-02 09:35:17 +00006170 // Update the FalseElement state machine.
Chris Lattner82602bc2010-01-02 20:20:33 +00006171 if (FirstFalseElement == Undefined)
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006172 FirstFalseElement = FalseRangeEnd = i; // First false element.
6173 else {
6174 // Update double-compare state machine.
6175 if (SecondFalseElement == Undefined)
6176 SecondFalseElement = i;
6177 else
6178 SecondFalseElement = Overdefined;
6179
6180 // Update range state machine.
6181 if (FalseRangeEnd == (int)i-1)
6182 FalseRangeEnd = i;
6183 else
6184 FalseRangeEnd = Overdefined;
6185 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006186 }
6187
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006188
Chris Lattner10d514e2010-01-02 08:56:52 +00006189 // If this element is in range, update our magic bitvector.
6190 if (i < 64 && IsTrueForElt)
Chris Lattner33a1ec72010-01-02 09:22:13 +00006191 MagicBitvector |= 1ULL << i;
Chris Lattner10d514e2010-01-02 08:56:52 +00006192
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006193 // If all of our states become overdefined, bail out early. Since the
6194 // predicate is expensive, only check it every 8 elements. This is only
6195 // really useful for really huge arrays.
6196 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
6197 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
6198 FalseRangeEnd == Overdefined)
Chris Lattner1f12e442010-01-02 08:12:04 +00006199 return 0;
6200 }
6201
6202 // Now that we've scanned the entire array, emit our new comparison(s). We
6203 // order the state machines in complexity of the generated code.
Chris Lattnerbef37372010-01-02 09:35:17 +00006204 Value *Idx = GEP->getOperand(2);
6205
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006206
Chris Lattnerbef37372010-01-02 09:35:17 +00006207 // If the comparison is only true for one or two elements, emit direct
6208 // comparisons.
Chris Lattner82602bc2010-01-02 20:20:33 +00006209 if (SecondTrueElement != Overdefined) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006210 // None true -> false.
Chris Lattner82602bc2010-01-02 20:20:33 +00006211 if (FirstTrueElement == Undefined)
Chris Lattner1f12e442010-01-02 08:12:04 +00006212 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6213
Chris Lattnerbef37372010-01-02 09:35:17 +00006214 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
6215
Chris Lattner1f12e442010-01-02 08:12:04 +00006216 // True for one element -> 'i == 47'.
Chris Lattner82602bc2010-01-02 20:20:33 +00006217 if (SecondTrueElement == Undefined)
Chris Lattnerbef37372010-01-02 09:35:17 +00006218 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
6219
6220 // True for two elements -> 'i == 47 | i == 72'.
6221 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
6222 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
6223 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
6224 return BinaryOperator::CreateOr(C1, C2);
Chris Lattner1f12e442010-01-02 08:12:04 +00006225 }
6226
Chris Lattnerbef37372010-01-02 09:35:17 +00006227 // If the comparison is only false for one or two elements, emit direct
6228 // comparisons.
Chris Lattner82602bc2010-01-02 20:20:33 +00006229 if (SecondFalseElement != Overdefined) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006230 // None false -> true.
Chris Lattner82602bc2010-01-02 20:20:33 +00006231 if (FirstFalseElement == Undefined)
Chris Lattner1f12e442010-01-02 08:12:04 +00006232 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6233
Chris Lattnerbef37372010-01-02 09:35:17 +00006234 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
6235
6236 // False for one element -> 'i != 47'.
Chris Lattner82602bc2010-01-02 20:20:33 +00006237 if (SecondFalseElement == Undefined)
Chris Lattnerbef37372010-01-02 09:35:17 +00006238 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
6239
6240 // False for two elements -> 'i != 47 & i != 72'.
6241 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
6242 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
6243 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
6244 return BinaryOperator::CreateAnd(C1, C2);
Chris Lattner1f12e442010-01-02 08:12:04 +00006245 }
6246
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006247 // If the comparison can be replaced with a range comparison for the elements
6248 // where it is true, emit the range check.
6249 if (TrueRangeEnd != Overdefined) {
6250 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
6251
6252 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
6253 if (FirstTrueElement) {
6254 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
6255 Idx = Builder->CreateAdd(Idx, Offs);
6256 }
6257
6258 Value *End = ConstantInt::get(Idx->getType(),
6259 TrueRangeEnd-FirstTrueElement+1);
6260 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
6261 }
6262
6263 // False range check.
6264 if (FalseRangeEnd != Overdefined) {
6265 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
6266 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
6267 if (FirstFalseElement) {
6268 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
6269 Idx = Builder->CreateAdd(Idx, Offs);
6270 }
6271
6272 Value *End = ConstantInt::get(Idx->getType(),
6273 FalseRangeEnd-FirstFalseElement);
6274 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
6275 }
6276
6277
Chris Lattner10d514e2010-01-02 08:56:52 +00006278 // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
6279 // of this load, replace it with computation that does:
6280 // ((magic_cst >> i) & 1) != 0
6281 if (Init->getNumOperands() <= 32 ||
6282 (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) {
6283 const Type *Ty;
6284 if (Init->getNumOperands() <= 32)
6285 Ty = Type::getInt32Ty(Init->getContext());
6286 else
6287 Ty = Type::getInt64Ty(Init->getContext());
Chris Lattnerbef37372010-01-02 09:35:17 +00006288 Value *V = Builder->CreateIntCast(Idx, Ty, false);
Chris Lattner10d514e2010-01-02 08:56:52 +00006289 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
6290 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
6291 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
6292 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006293
Chris Lattner1f12e442010-01-02 08:12:04 +00006294 return 0;
6295}
6296
6297
Reid Spencere4d87aa2006-12-23 06:05:41 +00006298Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006299 bool Changed = false;
6300
6301 /// Orders the operands of the compare so that they are listed from most
6302 /// complex to least complex. This puts constants before unary operators,
6303 /// before binary operators.
6304 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6305 I.swapOperands();
6306 Changed = true;
6307 }
6308
Chris Lattner8b170942002-08-09 23:47:40 +00006309 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner58e97462007-01-14 19:42:17 +00006310
Chris Lattner210c5d42009-11-09 23:55:12 +00006311 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
6312 return ReplaceInstUsesWith(I, V);
6313
Chris Lattner58e97462007-01-14 19:42:17 +00006314 // Simplify 'fcmp pred X, X'
6315 if (Op0 == Op1) {
6316 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006317 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00006318 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
6319 case FCmpInst::FCMP_ULT: // True if unordered or less than
6320 case FCmpInst::FCMP_UGT: // True if unordered or greater than
6321 case FCmpInst::FCMP_UNE: // True if unordered or not equal
6322 // Canonicalize these to be 'fcmp uno %X, 0.0'.
6323 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00006324 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00006325 return &I;
6326
6327 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
6328 case FCmpInst::FCMP_OEQ: // True if ordered and equal
6329 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
6330 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
6331 // Canonicalize these to be 'fcmp ord %X, 0.0'.
6332 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00006333 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00006334 return &I;
6335 }
6336 }
6337
Reid Spencere4d87aa2006-12-23 06:05:41 +00006338 // Handle fcmp with constant RHS
6339 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6340 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6341 switch (LHSI->getOpcode()) {
6342 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006343 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6344 // block. If in the same block, we're encouraging jump threading. If
6345 // not, we are just pessimizing the code by making an i1 phi.
6346 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006347 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006348 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006349 break;
Chris Lattnera5406232008-05-19 20:18:56 +00006350 case Instruction::SIToFP:
6351 case Instruction::UIToFP:
6352 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6353 return NV;
6354 break;
Chris Lattner34e0c762010-01-02 08:20:51 +00006355 case Instruction::Select: {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006356 // If either operand of the select is a constant, we can fold the
6357 // comparison into the select arms, which will cause one to be
6358 // constant folded and the select turned into a bitwise or.
6359 Value *Op1 = 0, *Op2 = 0;
6360 if (LHSI->hasOneUse()) {
6361 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6362 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006363 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006364 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006365 Op2 = Builder->CreateFCmp(I.getPredicate(),
6366 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006367 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6368 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006369 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006370 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006371 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6372 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006373 }
6374 }
6375
6376 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006377 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006378 break;
6379 }
Chris Lattner34e0c762010-01-02 08:20:51 +00006380 case Instruction::Load:
6381 if (GetElementPtrInst *GEP =
6382 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
6383 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6384 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Chris Lattnera0085af2010-01-03 06:58:48 +00006385 !cast<LoadInst>(LHSI)->isVolatile())
Chris Lattner34e0c762010-01-02 08:20:51 +00006386 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6387 return Res;
Chris Lattner34e0c762010-01-02 08:20:51 +00006388 }
6389 break;
6390 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006391 }
6392
6393 return Changed ? &I : 0;
6394}
6395
6396Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006397 bool Changed = false;
6398
6399 /// Orders the operands of the compare so that they are listed from most
6400 /// complex to least complex. This puts constants before unary operators,
6401 /// before binary operators.
6402 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6403 I.swapOperands();
6404 Changed = true;
6405 }
6406
Reid Spencere4d87aa2006-12-23 06:05:41 +00006407 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006408
Chris Lattner210c5d42009-11-09 23:55:12 +00006409 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6410 return ReplaceInstUsesWith(I, V);
6411
6412 const Type *Ty = Op0->getType();
Chris Lattner8b170942002-08-09 23:47:40 +00006413
Reid Spencere4d87aa2006-12-23 06:05:41 +00006414 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006415 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006416 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006417 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006418 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006419 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006420 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006421 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006422 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006423 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006424
Reid Spencere4d87aa2006-12-23 06:05:41 +00006425 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006426 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006427 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006428 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006429 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006430 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006431 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006432 case ICmpInst::ICMP_SGT:
6433 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006434 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006435 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006436 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006437 return BinaryOperator::CreateAnd(Not, Op0);
6438 }
6439 case ICmpInst::ICMP_UGE:
6440 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6441 // FALL THROUGH
6442 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006443 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006444 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006445 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006446 case ICmpInst::ICMP_SGE:
6447 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6448 // FALL THROUGH
6449 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006450 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006451 return BinaryOperator::CreateOr(Not, Op0);
6452 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006453 }
Chris Lattner8b170942002-08-09 23:47:40 +00006454 }
6455
Dan Gohman1c8491e2009-04-25 17:12:48 +00006456 unsigned BitWidth = 0;
6457 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006458 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6459 else if (Ty->isIntOrIntVector())
6460 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006461
6462 bool isSignBit = false;
6463
Dan Gohman81b28ce2008-09-16 18:46:06 +00006464 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006465 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006466 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006467
Chris Lattnerb6566012008-01-05 01:18:20 +00006468 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
Chris Lattner1f12e442010-01-02 08:12:04 +00006469 if (I.isEquality() && CI->isZero() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006470 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006471 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006472 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006473 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006474
Dan Gohman81b28ce2008-09-16 18:46:06 +00006475 // If we have an icmp le or icmp ge instruction, turn it into the
6476 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner210c5d42009-11-09 23:55:12 +00006477 // them being folded in the code below. The SimplifyICmpInst code has
6478 // already handled the edge cases for us, so we just assert on them.
Chris Lattner84dff672008-07-11 05:08:55 +00006479 switch (I.getPredicate()) {
6480 default: break;
6481 case ICmpInst::ICMP_ULE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006482 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006483 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006484 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006485 case ICmpInst::ICMP_SLE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006486 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006487 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006488 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006489 case ICmpInst::ICMP_UGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006490 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006491 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006492 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006493 case ICmpInst::ICMP_SGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006494 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006495 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006496 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006497 }
6498
Chris Lattner183661e2008-07-11 05:40:05 +00006499 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006500 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006501 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006502 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6503 }
6504
6505 // See if we can fold the comparison based on range information we can get
6506 // by checking whether bits are known to be zero or one in the input.
6507 if (BitWidth != 0) {
6508 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6509 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6510
6511 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006512 isSignBit ? APInt::getSignBit(BitWidth)
6513 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006514 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006515 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006516 if (SimplifyDemandedBits(I.getOperandUse(1),
6517 APInt::getAllOnesValue(BitWidth),
6518 Op1KnownZero, Op1KnownOne, 0))
6519 return &I;
6520
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006521 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006522 // in. Compute the Min, Max and RHS values based on the known bits. For the
6523 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006524 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6525 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006526 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006527 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6528 Op0Min, Op0Max);
6529 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6530 Op1Min, Op1Max);
6531 } else {
6532 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6533 Op0Min, Op0Max);
6534 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6535 Op1Min, Op1Max);
6536 }
6537
Chris Lattner183661e2008-07-11 05:40:05 +00006538 // If Min and Max are known to be the same, then SimplifyDemandedBits
6539 // figured out that the LHS is a constant. Just constant fold this now so
6540 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006541 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006542 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006543 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006544 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006545 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006546 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006547
Chris Lattner183661e2008-07-11 05:40:05 +00006548 // Based on the range information we know about the LHS, see if we can
6549 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006550 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006551 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006552 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006553 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006554 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006555 break;
6556 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006557 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006558 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006559 break;
6560 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006561 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006562 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006563 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006564 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006565 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006566 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006567 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6568 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006569 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006570 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006571
6572 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6573 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006574 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006575 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006576 }
Chris Lattner84dff672008-07-11 05:08:55 +00006577 break;
6578 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006579 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006580 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006581 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006582 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006583
6584 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006585 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006586 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6587 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006588 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006589 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006590
6591 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6592 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006593 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006594 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006595 }
Chris Lattner84dff672008-07-11 05:08:55 +00006596 break;
6597 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006598 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006599 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006600 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006601 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006602 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006603 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006604 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6605 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006606 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006607 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006608 }
Chris Lattner84dff672008-07-11 05:08:55 +00006609 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006610 case ICmpInst::ICMP_SGT:
6611 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006612 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006613 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006614 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006615
6616 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006617 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006618 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6619 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006620 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006621 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006622 }
6623 break;
6624 case ICmpInst::ICMP_SGE:
6625 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6626 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006627 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006628 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006629 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006630 break;
6631 case ICmpInst::ICMP_SLE:
6632 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6633 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006634 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006635 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006636 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006637 break;
6638 case ICmpInst::ICMP_UGE:
6639 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6640 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006641 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006642 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006643 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006644 break;
6645 case ICmpInst::ICMP_ULE:
6646 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6647 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006648 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006649 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006650 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006651 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006652 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006653
6654 // Turn a signed comparison into an unsigned one if both operands
6655 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006656 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006657 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6658 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006659 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006660 }
6661
6662 // Test if the ICmpInst instruction is used exclusively by a select as
6663 // part of a minimum or maximum operation. If so, refrain from doing
6664 // any other folding. This helps out other analyses which understand
6665 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6666 // and CodeGen. And in this case, at least one of the comparison
6667 // operands has at least one user besides the compare (the select),
6668 // which would often largely negate the benefit of folding anyway.
6669 if (I.hasOneUse())
6670 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6671 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6672 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6673 return 0;
6674
6675 // See if we are doing a comparison between a constant and an instruction that
6676 // can be folded into the comparison.
6677 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006678 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006679 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006680 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006681 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006682 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6683 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006684 }
6685
Chris Lattner01deb9d2007-04-03 17:43:25 +00006686 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006687 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6688 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6689 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006690 case Instruction::GetElementPtr:
Reid Spencere4d87aa2006-12-23 06:05:41 +00006691 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnerec12d052010-01-01 23:09:08 +00006692 if (RHSC->isNullValue() &&
6693 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
6694 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6695 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006696 break;
Chris Lattner6970b662005-04-23 15:31:55 +00006697 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006698 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006699 // block. If in the same block, we're encouraging jump threading. If
6700 // not, we are just pessimizing the code by making an i1 phi.
6701 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006702 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006703 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006704 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006705 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006706 // If either operand of the select is a constant, we can fold the
6707 // comparison into the select arms, which will cause one to be
6708 // constant folded and the select turned into a bitwise or.
6709 Value *Op1 = 0, *Op2 = 0;
Eli Friedman97b087c2009-12-18 08:22:35 +00006710 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6711 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6712 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6713 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6714
6715 // We only want to perform this transformation if it will not lead to
6716 // additional code. This is true if either both sides of the select
6717 // fold to a constant (in which case the icmp is replaced with a select
6718 // which will usually simplify) or this is the only user of the
6719 // select (in which case we are trading a select+icmp for a simpler
6720 // select+icmp).
6721 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6722 if (!Op1)
Chris Lattner74381062009-08-30 07:44:24 +00006723 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6724 RHSC, I.getName());
Eli Friedman97b087c2009-12-18 08:22:35 +00006725 if (!Op2)
6726 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6727 RHSC, I.getName());
Gabor Greif051a9502008-04-06 20:25:17 +00006728 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman97b087c2009-12-18 08:22:35 +00006729 }
Chris Lattner6970b662005-04-23 15:31:55 +00006730 break;
6731 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006732 case Instruction::Call:
6733 // If we have (malloc != null), and if the malloc has a single use, we
6734 // can assume it is successful and remove the malloc.
6735 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6736 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006737 // Need to explicitly erase malloc call here, instead of adding it to
6738 // Worklist, because it won't get DCE'd from the Worklist since
6739 // isInstructionTriviallyDead() returns false for function calls.
6740 // It is OK to replace LHSI/MallocCall with Undef because the
6741 // instruction that uses it will be erased via Worklist.
6742 if (extractMallocCall(LHSI)) {
6743 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6744 EraseInstFromFunction(*LHSI);
6745 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006746 ConstantInt::get(Type::getInt1Ty(*Context),
6747 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006748 }
6749 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6750 if (MallocCall->hasOneUse()) {
6751 MallocCall->replaceAllUsesWith(
6752 UndefValue::get(MallocCall->getType()));
6753 EraseInstFromFunction(*MallocCall);
6754 Worklist.Add(LHSI); // The malloc's bitcast use.
6755 return ReplaceInstUsesWith(I,
6756 ConstantInt::get(Type::getInt1Ty(*Context),
6757 !I.isTrueWhenEqual()));
6758 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006759 }
6760 break;
Chris Lattnerec12d052010-01-01 23:09:08 +00006761 case Instruction::IntToPtr:
6762 // icmp pred inttoptr(X), null -> icmp pred X, 0
6763 if (RHSC->isNullValue() && TD &&
6764 TD->getIntPtrType(RHSC->getContext()) ==
6765 LHSI->getOperand(0)->getType())
6766 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6767 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6768 break;
Chris Lattner1f12e442010-01-02 08:12:04 +00006769
6770 case Instruction::Load:
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006771 // Try to optimize things like "A[i] > 4" to index computations.
Chris Lattner1f12e442010-01-02 08:12:04 +00006772 if (GetElementPtrInst *GEP =
Chris Lattner34e0c762010-01-02 08:20:51 +00006773 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006774 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6775 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Chris Lattnera0085af2010-01-03 06:58:48 +00006776 !cast<LoadInst>(LHSI)->isVolatile())
Chris Lattner1f12e442010-01-02 08:12:04 +00006777 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6778 return Res;
Chris Lattner34e0c762010-01-02 08:20:51 +00006779 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006780 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006781 }
Chris Lattner6970b662005-04-23 15:31:55 +00006782 }
6783
Reid Spencere4d87aa2006-12-23 06:05:41 +00006784 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006785 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006786 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006787 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006788 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006789 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6790 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006791 return NI;
6792
Reid Spencere4d87aa2006-12-23 06:05:41 +00006793 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006794 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6795 // now.
6796 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6797 if (isa<PointerType>(Op0->getType()) &&
6798 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006799 // We keep moving the cast from the left operand over to the right
6800 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006801 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006802
Chris Lattner57d86372007-01-06 01:45:59 +00006803 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6804 // so eliminate it as well.
6805 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6806 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006807
Chris Lattnerde90b762003-11-03 04:25:02 +00006808 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006809 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006810 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006811 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006812 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006813 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006814 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006815 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006816 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006817 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006818 }
Chris Lattner57d86372007-01-06 01:45:59 +00006819 }
6820
6821 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006822 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006823 // This comes up when you have code like
6824 // int X = A < B;
6825 // if (X) ...
6826 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006827 // with a constant or another cast from the same type.
Eli Friedman8e4b1972009-12-17 21:27:47 +00006828 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006829 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006830 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006831 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006832
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006833 // See if it's the same type of instruction on the left and right.
6834 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6835 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006836 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006837 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006838 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006839 default: break;
6840 case Instruction::Add:
6841 case Instruction::Sub:
6842 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006843 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006844 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006845 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006846 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6847 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6848 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006849 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006850 ? I.getUnsignedPredicate()
6851 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006852 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006853 Op1I->getOperand(0));
6854 }
6855
6856 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006857 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006858 ? I.getUnsignedPredicate()
6859 : I.getSignedPredicate();
6860 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006861 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006862 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006863 }
6864 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006865 break;
6866 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006867 if (!I.isEquality())
6868 break;
6869
Nick Lewycky5d52c452008-08-21 05:56:10 +00006870 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6871 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6872 // Mask = -1 >> count-trailing-zeros(Cst).
6873 if (!CI->isZero() && !CI->isOne()) {
6874 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006875 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006876 APInt::getLowBitsSet(AP.getBitWidth(),
6877 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006878 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006879 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6880 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006881 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006882 }
6883 }
6884 break;
6885 }
6886 }
6887 }
6888 }
6889
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006890 // ~x < ~y --> y < x
6891 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006892 if (match(Op0, m_Not(m_Value(A))) &&
6893 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006894 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006895 }
6896
Chris Lattner65b72ba2006-09-18 04:22:48 +00006897 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006898 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006899
6900 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006901 if (match(Op0, m_Neg(m_Value(A))) &&
6902 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006903 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006904
Dan Gohman4ae51262009-08-12 16:23:25 +00006905 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006906 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6907 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006908 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006909 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006910 }
6911
Dan Gohman4ae51262009-08-12 16:23:25 +00006912 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006913 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006914 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006915 if (match(B, m_ConstantInt(C1)) &&
6916 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006917 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006918 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006919 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6920 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006921 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006922
6923 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006924 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6925 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6926 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6927 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006928 }
6929 }
6930
Dan Gohman4ae51262009-08-12 16:23:25 +00006931 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006932 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006933 // A == (A^B) -> B == 0
6934 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006935 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006936 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006937 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006938
6939 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006940 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006941 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006942 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006943
6944 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006945 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006946 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006947 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006948
Chris Lattner9c2328e2006-11-14 06:06:06 +00006949 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6950 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006951 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6952 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006953 Value *X = 0, *Y = 0, *Z = 0;
6954
6955 if (A == C) {
6956 X = B; Y = D; Z = A;
6957 } else if (A == D) {
6958 X = B; Y = C; Z = A;
6959 } else if (B == C) {
6960 X = A; Y = D; Z = B;
6961 } else if (B == D) {
6962 X = A; Y = C; Z = B;
6963 }
6964
6965 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006966 Op1 = Builder->CreateXor(X, Y, "tmp");
6967 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006968 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006969 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006970 return &I;
6971 }
6972 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006973 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006974
6975 {
6976 Value *X; ConstantInt *Cst;
Chris Lattner3bf68152009-12-21 04:04:05 +00006977 // icmp X+Cst, X
Chris Lattner2799baf2009-12-21 03:19:28 +00006978 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006979 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6980
Chris Lattner2799baf2009-12-21 03:19:28 +00006981 // icmp X, X+Cst
6982 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006983 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
Chris Lattner2799baf2009-12-21 03:19:28 +00006984 }
Chris Lattner7e708292002-06-25 16:13:24 +00006985 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006986}
6987
Chris Lattner2799baf2009-12-21 03:19:28 +00006988/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6989Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6990 Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +00006991 ICmpInst::Predicate Pred,
6992 Value *TheAdd) {
Chris Lattner2799baf2009-12-21 03:19:28 +00006993 // If we have X+0, exit early (simplifying logic below) and let it get folded
6994 // elsewhere. icmp X+0, X -> icmp X, X
6995 if (CI->isZero()) {
6996 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6997 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6998 }
6999
7000 // (X+4) == X -> false.
7001 if (Pred == ICmpInst::ICMP_EQ)
7002 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
7003
7004 // (X+4) != X -> true.
7005 if (Pred == ICmpInst::ICMP_NE)
7006 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner3bf68152009-12-21 04:04:05 +00007007
7008 // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
7009 bool isNUW = false, isNSW = false;
7010 if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
7011 isNUW = Add->hasNoUnsignedWrap();
7012 isNSW = Add->hasNoSignedWrap();
7013 }
Chris Lattner2799baf2009-12-21 03:19:28 +00007014
7015 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
7016 // so the values can never be equal. Similiarly for all other "or equals"
7017 // operators.
7018
7019 // (X+1) <u X --> X >u (MAXUINT-1) --> X != 255
7020 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
7021 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
7022 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Chris Lattner3bf68152009-12-21 04:04:05 +00007023 // If this is an NUW add, then this is always false.
7024 if (isNUW)
7025 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
7026
Chris Lattner2799baf2009-12-21 03:19:28 +00007027 Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
7028 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
7029 }
7030
7031 // (X+1) >u X --> X <u (0-1) --> X != 255
7032 // (X+2) >u X --> X <u (0-2) --> X <u 254
7033 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Chris Lattner3bf68152009-12-21 04:04:05 +00007034 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
7035 // If this is an NUW add, then this is always true.
7036 if (isNUW)
7037 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner2799baf2009-12-21 03:19:28 +00007038 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00007039 }
Chris Lattner2799baf2009-12-21 03:19:28 +00007040
7041 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
7042 ConstantInt *SMax = ConstantInt::get(X->getContext(),
7043 APInt::getSignedMaxValue(BitWidth));
7044
7045 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
7046 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
7047 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
7048 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
7049 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
7050 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Chris Lattner3bf68152009-12-21 04:04:05 +00007051 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
7052 // If this is an NSW add, then we have two cases: if the constant is
7053 // positive, then this is always false, if negative, this is always true.
7054 if (isNSW) {
7055 bool isTrue = CI->getValue().isNegative();
7056 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
7057 }
7058
Chris Lattner2799baf2009-12-21 03:19:28 +00007059 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00007060 }
Chris Lattner2799baf2009-12-21 03:19:28 +00007061
7062 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
7063 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
7064 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
7065 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
7066 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
7067 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Chris Lattner3bf68152009-12-21 04:04:05 +00007068
7069 // If this is an NSW add, then we have two cases: if the constant is
7070 // positive, then this is always true, if negative, this is always false.
7071 if (isNSW) {
7072 bool isTrue = !CI->getValue().isNegative();
7073 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
7074 }
7075
Chris Lattner2799baf2009-12-21 03:19:28 +00007076 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
7077 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
7078 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
7079}
Chris Lattner562ef782007-06-20 23:46:26 +00007080
7081/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
7082/// and CmpRHS are both known to be integer constants.
7083Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
7084 ConstantInt *DivRHS) {
7085 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
7086 const APInt &CmpRHSV = CmpRHS->getValue();
7087
7088 // FIXME: If the operand types don't match the type of the divide
7089 // then don't attempt this transform. The code below doesn't have the
7090 // logic to deal with a signed divide and an unsigned compare (and
7091 // vice versa). This is because (x /s C1) <s C2 produces different
7092 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
7093 // (x /u C1) <u C2. Simply casting the operands and result won't
7094 // work. :( The if statement below tests that condition and bails
7095 // if it finds it.
7096 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007097 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00007098 return 0;
7099 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00007100 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00007101 if (DivIsSigned && DivRHS->isAllOnesValue())
7102 return 0; // The overflow computation also screws up here
7103 if (DivRHS->isOne())
7104 return 0; // Not worth bothering, and eliminates some funny cases
7105 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00007106
7107 // Compute Prod = CI * DivRHS. We are essentially solving an equation
7108 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
7109 // C2 (CI). By solving for X we can turn this into a range check
7110 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007111 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00007112
7113 // Determine if the product overflows by seeing if the product is
7114 // not equal to the divide. Make sure we do the same kind of divide
7115 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007116 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
7117 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00007118
7119 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00007120 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00007121
Chris Lattner1dbfd482007-06-21 18:11:19 +00007122 // Figure out the interval that is being checked. For example, a comparison
7123 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
7124 // Compute this interval based on the constants involved and the signedness of
7125 // the compare/divide. This computes a half-open interval, keeping track of
7126 // whether either value in the interval overflows. After analysis each
7127 // overflow variable is set to 0 if it's corresponding bound variable is valid
7128 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
7129 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00007130 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00007131
Chris Lattner562ef782007-06-20 23:46:26 +00007132 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00007133 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00007134 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00007135 HiOverflow = LoOverflow = ProdOV;
7136 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007137 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00007138 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00007139 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00007140 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00007141 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00007142 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00007143 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00007144 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
7145 HiOverflow = LoOverflow = ProdOV;
7146 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007147 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00007148 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00007149 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00007150 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00007151 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
7152 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007153 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00007154 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00007155 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00007156 true) ? -1 : 0;
7157 }
Chris Lattner562ef782007-06-20 23:46:26 +00007158 }
Dan Gohman76491272008-02-13 22:09:18 +00007159 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00007160 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00007161 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00007162 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007163 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007164 if (HiBound == DivRHS) { // -INTMIN = INTMIN
7165 HiOverflow = 1; // [INTMIN+1, overflow)
7166 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
7167 }
Dan Gohman76491272008-02-13 22:09:18 +00007168 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00007169 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00007170 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00007171 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00007172 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007173 LoOverflow = AddWithOverflow(LoBound, HiBound,
7174 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00007175 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00007176 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
7177 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00007178 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007179 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00007180 }
7181
Chris Lattner1dbfd482007-06-21 18:11:19 +00007182 // Dividing by a negative swaps the condition. LT <-> GT
7183 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00007184 }
7185
7186 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00007187 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00007188 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00007189 case ICmpInst::ICMP_EQ:
7190 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00007191 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00007192 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007193 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00007194 ICmpInst::ICMP_UGE, X, LoBound);
7195 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007196 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00007197 ICmpInst::ICMP_ULT, X, HiBound);
7198 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00007199 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00007200 case ICmpInst::ICMP_NE:
7201 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00007202 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00007203 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007204 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00007205 ICmpInst::ICMP_ULT, X, LoBound);
7206 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007207 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00007208 ICmpInst::ICMP_UGE, X, HiBound);
7209 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00007210 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00007211 case ICmpInst::ICMP_ULT:
7212 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00007213 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007214 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007215 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007216 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007217 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007218 case ICmpInst::ICMP_UGT:
7219 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00007220 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007221 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007222 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007223 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007224 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007225 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007226 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007227 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007228 }
7229}
7230
7231
Chris Lattner01deb9d2007-04-03 17:43:25 +00007232/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
7233///
7234Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
7235 Instruction *LHSI,
7236 ConstantInt *RHS) {
7237 const APInt &RHSV = RHS->getValue();
7238
7239 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00007240 case Instruction::Trunc:
7241 if (ICI.isEquality() && LHSI->hasOneUse()) {
7242 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
7243 // of the high bits truncated out of x are known.
7244 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
7245 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
7246 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
7247 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
7248 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
7249
7250 // If all the high bits are known, we can do this xform.
7251 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
7252 // Pull in the high bits from known-ones set.
7253 APInt NewRHS(RHS->getValue());
7254 NewRHS.zext(SrcBits);
7255 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007256 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007257 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00007258 }
7259 }
7260 break;
7261
Duncan Sands0091bf22007-04-04 06:42:45 +00007262 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00007263 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
7264 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
7265 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00007266 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
7267 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007268 Value *CompareVal = LHSI->getOperand(0);
7269
7270 // If the sign bit of the XorCST is not set, there is no change to
7271 // the operation, just stop using the Xor.
7272 if (!XorCST->getValue().isNegative()) {
7273 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00007274 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007275 return &ICI;
7276 }
7277
7278 // Was the old condition true if the operand is positive?
7279 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
7280
7281 // If so, the new one isn't.
7282 isTrueIfPositive ^= true;
7283
7284 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007285 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00007286 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007287 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007288 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00007289 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007290 }
Nick Lewycky4333f492009-01-31 21:30:05 +00007291
7292 if (LHSI->hasOneUse()) {
7293 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
7294 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
7295 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00007296 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00007297 ? ICI.getUnsignedPredicate()
7298 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007299 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007300 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00007301 }
7302
7303 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00007304 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00007305 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00007306 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00007307 ? ICI.getUnsignedPredicate()
7308 : ICI.getSignedPredicate();
7309 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007310 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007311 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00007312 }
7313 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007314 }
7315 break;
7316 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
7317 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
7318 LHSI->getOperand(0)->hasOneUse()) {
7319 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
7320
7321 // If the LHS is an AND of a truncating cast, we can widen the
7322 // and/compare to be the input width without changing the value
7323 // produced, eliminating a cast.
7324 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
7325 // We can do this transformation if either the AND constant does not
7326 // have its sign bit set or if it is an equality comparison.
7327 // Extending a relational comparison when we're checking the sign
7328 // bit would not work.
7329 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00007330 (ICI.isEquality() ||
7331 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007332 uint32_t BitWidth =
7333 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
7334 APInt NewCST = AndCST->getValue();
7335 NewCST.zext(BitWidth);
7336 APInt NewCI = RHSV;
7337 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00007338 Value *NewAnd =
7339 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007340 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007341 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00007342 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007343 }
7344 }
7345
7346 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
7347 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
7348 // happens a LOT in code produced by the C front-end, for bitfield
7349 // access.
7350 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
7351 if (Shift && !Shift->isShift())
7352 Shift = 0;
7353
7354 ConstantInt *ShAmt;
7355 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
7356 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
7357 const Type *AndTy = AndCST->getType(); // Type of the and.
7358
7359 // We can fold this as long as we can't shift unknown bits
7360 // into the mask. This can only happen with signed shift
7361 // rights, as they sign-extend.
7362 if (ShAmt) {
7363 bool CanFold = Shift->isLogicalShift();
7364 if (!CanFold) {
7365 // To test for the bad case of the signed shr, see if any
7366 // of the bits shifted in could be tested after the mask.
7367 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
7368 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
7369
7370 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
7371 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
7372 AndCST->getValue()) == 0)
7373 CanFold = true;
7374 }
7375
7376 if (CanFold) {
7377 Constant *NewCst;
7378 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007379 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007380 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007381 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007382
7383 // Check to see if we are shifting out any of the bits being
7384 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007385 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007386 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007387 // If we shifted bits out, the fold is not going to work out.
7388 // As a special case, check to see if this means that the
7389 // result is always true or false now.
7390 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007391 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007392 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007393 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007394 } else {
7395 ICI.setOperand(1, NewCst);
7396 Constant *NewAndCST;
7397 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007398 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007399 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007400 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007401 LHSI->setOperand(1, NewAndCST);
7402 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00007403 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00007404 return &ICI;
7405 }
7406 }
7407 }
7408
7409 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
7410 // preferable because it allows the C<<Y expression to be hoisted out
7411 // of a loop if Y is invariant and X is not.
7412 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00007413 ICI.isEquality() && !Shift->isArithmeticShift() &&
7414 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007415 // Compute C << Y.
7416 Value *NS;
7417 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00007418 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007419 } else {
7420 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00007421 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007422 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007423
7424 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00007425 Value *NewAnd =
7426 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007427
7428 ICI.setOperand(0, NewAnd);
7429 return &ICI;
7430 }
7431 }
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00007432
7433 // Try to optimize things like "A[i]&42 == 0" to index computations.
7434 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
7435 if (GetElementPtrInst *GEP =
7436 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
7437 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
7438 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
7439 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
7440 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
7441 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
7442 return Res;
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00007443 }
7444 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007445 break;
Nick Lewycky546d6312010-01-02 15:25:44 +00007446
7447 case Instruction::Or: {
7448 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
7449 break;
7450 Value *P, *Q;
7451 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
7452 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
7453 // -> and (icmp eq P, null), (icmp eq Q, null).
7454
7455 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
7456 Constant::getNullValue(P->getType()));
7457 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
7458 Constant::getNullValue(Q->getType()));
Nick Lewyckyf994bf02010-01-02 16:14:56 +00007459 Instruction *Op;
7460 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky11ed0312010-01-03 00:55:31 +00007461 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
Nick Lewyckyf994bf02010-01-02 16:14:56 +00007462 else
Nick Lewycky11ed0312010-01-03 00:55:31 +00007463 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
Nick Lewyckyf994bf02010-01-02 16:14:56 +00007464 return Op;
Nick Lewycky546d6312010-01-02 15:25:44 +00007465 }
7466 break;
7467 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007468
Chris Lattnera0141b92007-07-15 20:42:37 +00007469 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
7470 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7471 if (!ShAmt) break;
7472
7473 uint32_t TypeBits = RHSV.getBitWidth();
7474
7475 // Check that the shift amount is in range. If not, don't perform
7476 // undefined shifts. When the shift is visited it will be
7477 // simplified.
7478 if (ShAmt->uge(TypeBits))
7479 break;
7480
7481 if (ICI.isEquality()) {
7482 // If we are comparing against bits always shifted out, the
7483 // comparison cannot succeed.
7484 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00007485 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00007486 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00007487 if (Comp != RHS) {// Comparing against a bit that we know is zero.
7488 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007489 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00007490 return ReplaceInstUsesWith(ICI, Cst);
7491 }
7492
7493 if (LHSI->hasOneUse()) {
7494 // Otherwise strength reduce the shift into an and.
7495 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7496 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00007497 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00007498 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007499
Chris Lattner74381062009-08-30 07:44:24 +00007500 Value *And =
7501 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007502 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00007503 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007504 }
7505 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007506
7507 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7508 bool TrueIfSigned = false;
7509 if (LHSI->hasOneUse() &&
7510 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7511 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00007512 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00007513 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00007514 Value *And =
7515 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007516 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00007517 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00007518 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007519 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007520 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007521
7522 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00007523 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007524 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00007525 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007526 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007527
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007528 // Check that the shift amount is in range. If not, don't perform
7529 // undefined shifts. When the shift is visited it will be
7530 // simplified.
7531 uint32_t TypeBits = RHSV.getBitWidth();
7532 if (ShAmt->uge(TypeBits))
7533 break;
7534
7535 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007536
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007537 // If we are comparing against bits always shifted out, the
7538 // comparison cannot succeed.
7539 APInt Comp = RHSV << ShAmtVal;
7540 if (LHSI->getOpcode() == Instruction::LShr)
7541 Comp = Comp.lshr(ShAmtVal);
7542 else
7543 Comp = Comp.ashr(ShAmtVal);
7544
7545 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7546 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007547 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007548 return ReplaceInstUsesWith(ICI, Cst);
7549 }
7550
7551 // Otherwise, check to see if the bits shifted out are known to be zero.
7552 // If so, we can compare against the unshifted value:
7553 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007554 if (LHSI->hasOneUse() &&
7555 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007556 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007557 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007558 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007559 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007560
Evan Chengf30752c2008-04-23 00:38:06 +00007561 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007562 // Otherwise strength reduce the shift into an and.
7563 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007564 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007565
Chris Lattner74381062009-08-30 07:44:24 +00007566 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7567 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007568 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007569 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007570 }
7571 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007572 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007573
7574 case Instruction::SDiv:
7575 case Instruction::UDiv:
7576 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7577 // Fold this div into the comparison, producing a range check.
7578 // Determine, based on the divide type, what the range is being
7579 // checked. If there is an overflow on the low or high side, remember
7580 // it, otherwise compute the range [low, hi) bounding the new value.
7581 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007582 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7583 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7584 DivRHS))
7585 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007586 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007587
7588 case Instruction::Add:
Chris Lattner2799baf2009-12-21 03:19:28 +00007589 // Fold: icmp pred (add X, C1), C2
Nick Lewycky5be29202008-02-03 16:33:09 +00007590 if (!ICI.isEquality()) {
7591 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7592 if (!LHSC) break;
7593 const APInt &LHSV = LHSC->getValue();
7594
7595 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7596 .subtract(LHSV);
7597
Nick Lewycky4a134af2009-10-25 05:20:17 +00007598 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007599 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007600 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007601 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007602 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007603 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007604 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007605 }
7606 } else {
7607 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007608 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007609 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007610 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007611 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007612 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007613 }
7614 }
7615 }
7616 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007617 }
7618
7619 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7620 if (ICI.isEquality()) {
7621 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7622
7623 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7624 // the second operand is a constant, simplify a bit.
7625 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7626 switch (BO->getOpcode()) {
7627 case Instruction::SRem:
7628 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7629 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7630 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7631 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007632 Value *NewRem =
7633 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7634 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007635 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007636 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007637 }
7638 }
7639 break;
7640 case Instruction::Add:
7641 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7642 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7643 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007644 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007645 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007646 } else if (RHSV == 0) {
7647 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7648 // efficiently invertible, or if the add has just this one use.
7649 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7650
Dan Gohman186a6362009-08-12 16:04:34 +00007651 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007652 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007653 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007654 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007655 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007656 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007657 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007658 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007659 }
7660 }
7661 break;
7662 case Instruction::Xor:
7663 // For the xor case, we can xor two constants together, eliminating
7664 // the explicit xor.
7665 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007666 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007667 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007668
7669 // FALLTHROUGH
7670 case Instruction::Sub:
7671 // Replace (([sub|xor] A, B) != 0) with (A != B)
7672 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007673 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007674 BO->getOperand(1));
7675 break;
7676
7677 case Instruction::Or:
7678 // If bits are being or'd in that are not present in the constant we
7679 // are comparing against, then the comparison could never succeed!
7680 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007681 Constant *NotCI = ConstantExpr::getNot(RHS);
7682 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007683 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007684 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007685 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007686 }
7687 break;
7688
7689 case Instruction::And:
7690 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7691 // If bits are being compared against that are and'd out, then the
7692 // comparison can never succeed!
7693 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007694 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007695 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007696 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007697
7698 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7699 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007700 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007701 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007702 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007703
7704 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007705 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007706 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007707 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007708 ICmpInst::Predicate pred = isICMP_NE ?
7709 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007710 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007711 }
7712
7713 // ((X & ~7) == 0) --> X < 8
7714 if (RHSV == 0 && isHighOnes(BOC)) {
7715 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007716 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007717 ICmpInst::Predicate pred = isICMP_NE ?
7718 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007719 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007720 }
7721 }
7722 default: break;
7723 }
7724 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7725 // Handle icmp {eq|ne} <intrinsic>, intcst.
7726 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007727 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007728 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007729 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007730 return &ICI;
7731 }
7732 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007733 }
7734 return 0;
7735}
7736
7737/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7738/// We only handle extending casts so far.
7739///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007740Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7741 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007742 Value *LHSCIOp = LHSCI->getOperand(0);
7743 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007744 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007745 Value *RHSCIOp;
7746
Chris Lattner8c756c12007-05-05 22:41:33 +00007747 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7748 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007749 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7750 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007751 cast<IntegerType>(DestTy)->getBitWidth()) {
7752 Value *RHSOp = 0;
7753 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007754 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007755 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7756 RHSOp = RHSC->getOperand(0);
7757 // If the pointer types don't match, insert a bitcast.
7758 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007759 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007760 }
7761
7762 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007763 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007764 }
7765
7766 // The code below only handles extension cast instructions, so far.
7767 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007768 if (LHSCI->getOpcode() != Instruction::ZExt &&
7769 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007770 return 0;
7771
Reid Spencere4d87aa2006-12-23 06:05:41 +00007772 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007773 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007774
Reid Spencere4d87aa2006-12-23 06:05:41 +00007775 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007776 // Not an extension from the same type?
7777 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007778 if (RHSCIOp->getType() != LHSCIOp->getType())
7779 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007780
Nick Lewycky4189a532008-01-28 03:48:02 +00007781 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007782 // and the other is a zext), then we can't handle this.
7783 if (CI->getOpcode() != LHSCI->getOpcode())
7784 return 0;
7785
Nick Lewycky4189a532008-01-28 03:48:02 +00007786 // Deal with equality cases early.
7787 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007788 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007789
7790 // A signed comparison of sign extended values simplifies into a
7791 // signed comparison.
7792 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007793 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007794
7795 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007796 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007797 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007798
Reid Spencere4d87aa2006-12-23 06:05:41 +00007799 // If we aren't dealing with a constant on the RHS, exit early
7800 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7801 if (!CI)
7802 return 0;
7803
7804 // Compute the constant that would happen if we truncated to SrcTy then
7805 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007806 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7807 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007808 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007809
7810 // If the re-extended constant didn't change...
7811 if (Res2 == CI) {
Eli Friedmanb17cb062009-12-17 22:42:29 +00007812 // Deal with equality cases early.
7813 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007814 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedmanb17cb062009-12-17 22:42:29 +00007815
7816 // A signed comparison of sign extended values simplifies into a
7817 // signed comparison.
7818 if (isSignedExt && isSignedCmp)
7819 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7820
7821 // The other three cases all fold into an unsigned comparison.
7822 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007823 }
7824
7825 // The re-extended constant changed so the constant cannot be represented
7826 // in the shorter type. Consequently, we cannot emit a simple comparison.
7827
7828 // First, handle some easy cases. We know the result cannot be equal at this
7829 // point so handle the ICI.isEquality() cases
7830 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007831 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007832 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007833 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007834
7835 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7836 // should have been folded away previously and not enter in here.
7837 Value *Result;
7838 if (isSignedCmp) {
7839 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007840 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007841 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007842 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007843 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007844 } else {
7845 // We're performing an unsigned comparison.
7846 if (isSignedExt) {
7847 // We're performing an unsigned comp with a sign extended value.
7848 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007849 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007850 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007851 } else {
7852 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007853 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007854 }
7855 }
7856
7857 // Finally, return the value computed.
7858 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007859 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007860 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007861
7862 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7863 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7864 "ICmp should be folded!");
7865 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007866 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007867 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007868}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007869
Reid Spencer832254e2007-02-02 02:16:23 +00007870Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7871 return commonShiftTransforms(I);
7872}
7873
7874Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7875 return commonShiftTransforms(I);
7876}
7877
7878Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007879 if (Instruction *R = commonShiftTransforms(I))
7880 return R;
7881
7882 Value *Op0 = I.getOperand(0);
7883
7884 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7885 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7886 if (CSI->isAllOnesValue())
7887 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007888
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007889 // See if we can turn a signed shr into an unsigned shr.
7890 if (MaskedValueIsZero(Op0,
7891 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7892 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7893
7894 // Arithmetic shifting an all-sign-bit value is a no-op.
7895 unsigned NumSignBits = ComputeNumSignBits(Op0);
7896 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7897 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007898
Chris Lattner348f6652007-12-06 01:59:46 +00007899 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007900}
7901
7902Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7903 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007904 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007905
7906 // shl X, 0 == X and shr X, 0 == X
7907 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007908 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7909 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007910 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007911
Reid Spencere4d87aa2006-12-23 06:05:41 +00007912 if (isa<UndefValue>(Op0)) {
7913 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007914 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007915 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007916 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007917 }
7918 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007919 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7920 return ReplaceInstUsesWith(I, Op0);
7921 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007922 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007923 }
7924
Dan Gohman9004c8a2009-05-21 02:28:33 +00007925 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007926 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007927 return &I;
7928
Chris Lattner2eefe512004-04-09 19:05:30 +00007929 // Try to fold constant and into select arguments.
7930 if (isa<Constant>(Op0))
7931 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007932 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007933 return R;
7934
Reid Spencerb83eb642006-10-20 07:07:24 +00007935 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007936 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7937 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007938 return 0;
7939}
7940
Reid Spencerb83eb642006-10-20 07:07:24 +00007941Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007942 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007943 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007944
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007945 // See if we can simplify any instructions used by the instruction whose sole
7946 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007947 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007948
Dan Gohmana119de82009-06-14 23:30:43 +00007949 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7950 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007951 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007952 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007953 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007954 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007955 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007956 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007957 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007958 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007959 }
7960
7961 // ((X*C1) << C2) == (X * (C1 << C2))
7962 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7963 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7964 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007965 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007966 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007967
7968 // Try to fold constant and into select arguments.
7969 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7970 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7971 return R;
7972 if (isa<PHINode>(Op0))
7973 if (Instruction *NV = FoldOpIntoPhi(I))
7974 return NV;
7975
Chris Lattner8999dd32007-12-22 09:07:47 +00007976 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7977 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7978 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7979 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7980 // place. Don't try to do this transformation in this case. Also, we
7981 // require that the input operand is a shift-by-constant so that we have
7982 // confidence that the shifts will get folded together. We could do this
7983 // xform in more cases, but it is unlikely to be profitable.
7984 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7985 isa<ConstantInt>(TrOp->getOperand(1))) {
7986 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007987 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007988 // (shift2 (shift1 & 0x00FF), c2)
7989 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007990
7991 // For logical shifts, the truncation has the effect of making the high
7992 // part of the register be zeros. Emulate this by inserting an AND to
7993 // clear the top bits as needed. This 'and' will usually be zapped by
7994 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007995 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7996 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007997 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7998
7999 // The mask we constructed says what the trunc would do if occurring
8000 // between the shifts. We want to know the effect *after* the second
8001 // shift. We know that it is a logical shift by a constant, so adjust the
8002 // mask as appropriate.
8003 if (I.getOpcode() == Instruction::Shl)
8004 MaskV <<= Op1->getZExtValue();
8005 else {
8006 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
8007 MaskV = MaskV.lshr(Op1->getZExtValue());
8008 }
8009
Chris Lattner74381062009-08-30 07:44:24 +00008010 // shift1 & 0x00FF
8011 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
8012 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00008013
8014 // Return the value truncated to the interesting size.
8015 return new TruncInst(And, I.getType());
8016 }
8017 }
8018
Chris Lattner4d5542c2006-01-06 07:12:35 +00008019 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00008020 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
8021 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
8022 Value *V1, *V2;
8023 ConstantInt *CC;
8024 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00008025 default: break;
8026 case Instruction::Add:
8027 case Instruction::And:
8028 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00008029 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00008030 // These operators commute.
8031 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00008032 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008033 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008034 m_Specific(Op1)))) {
8035 Value *YS = // (Y << C)
8036 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
8037 // (X + (Y << C))
8038 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
8039 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00008040 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00008041 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00008042 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00008043 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00008044
Chris Lattner150f12a2005-09-18 06:30:59 +00008045 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00008046 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00008047 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00008048 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00008049 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008050 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00008051 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008052 Value *YS = // (Y << C)
8053 Builder->CreateShl(Op0BO->getOperand(0), Op1,
8054 Op0BO->getName());
8055 // X & (CC << C)
8056 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
8057 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008058 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00008059 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008060 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00008061
Reid Spencera07cb7d2007-02-02 14:41:37 +00008062 // FALL THROUGH.
8063 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00008064 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00008065 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008066 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00008067 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008068 Value *YS = // (Y << C)
8069 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
8070 // (X + (Y << C))
8071 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
8072 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00008073 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00008074 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00008075 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00008076 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00008077
Chris Lattner13d4ab42006-05-31 21:14:00 +00008078 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00008079 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
8080 match(Op0BO->getOperand(0),
8081 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008082 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00008083 cast<BinaryOperator>(Op0BO->getOperand(0))
8084 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008085 Value *YS = // (Y << C)
8086 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
8087 // X & (CC << C)
8088 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
8089 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00008090
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008091 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00008092 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00008093
Chris Lattner11021cb2005-09-18 05:12:10 +00008094 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00008095 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00008096 }
8097
8098
8099 // If the operand is an bitwise operator with a constant RHS, and the
8100 // shift is the only use, we can pull it out of the shift.
8101 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
8102 bool isValid = true; // Valid only for And, Or, Xor
8103 bool highBitSet = false; // Transform if high bit of constant set?
8104
8105 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00008106 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00008107 case Instruction::Add:
8108 isValid = isLeftShift;
8109 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00008110 case Instruction::Or:
8111 case Instruction::Xor:
8112 highBitSet = false;
8113 break;
8114 case Instruction::And:
8115 highBitSet = true;
8116 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00008117 }
8118
8119 // If this is a signed shift right, and the high bit is modified
8120 // by the logical operation, do not perform the transformation.
8121 // The highBitSet boolean indicates the value of the high bit of
8122 // the constant which would cause it to be modified for this
8123 // operation.
8124 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00008125 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00008126 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00008127
8128 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008129 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00008130
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008131 Value *NewShift =
8132 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00008133 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00008134
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008135 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00008136 NewRHS);
8137 }
8138 }
8139 }
8140 }
8141
Chris Lattnerad0124c2006-01-06 07:52:12 +00008142 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00008143 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
8144 if (ShiftOp && !ShiftOp->isShift())
8145 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00008146
Reid Spencerb83eb642006-10-20 07:07:24 +00008147 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00008148 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00008149 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
8150 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00008151 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
8152 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
8153 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00008154
Zhou Sheng4351c642007-04-02 08:20:41 +00008155 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00008156
8157 const IntegerType *Ty = cast<IntegerType>(I.getType());
8158
8159 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00008160 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00008161 // If this is oversized composite shift, then unsigned shifts get 0, ashr
8162 // saturates.
8163 if (AmtSum >= TypeBits) {
8164 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00008165 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00008166 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
8167 }
8168
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008169 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00008170 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008171 }
8172
8173 if (ShiftOp->getOpcode() == Instruction::LShr &&
8174 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00008175 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00008176 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00008177
Chris Lattnerb87056f2007-02-05 00:57:54 +00008178 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00008179 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008180 }
8181
8182 if (ShiftOp->getOpcode() == Instruction::AShr &&
8183 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00008184 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00008185 if (AmtSum >= TypeBits)
8186 AmtSum = TypeBits-1;
8187
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008188 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008189
Zhou Shenge9e03f62007-03-28 15:02:20 +00008190 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008191 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008192 }
8193
Chris Lattnerb87056f2007-02-05 00:57:54 +00008194 // Okay, if we get here, one shift must be left, and the other shift must be
8195 // right. See if the amounts are equal.
8196 if (ShiftAmt1 == ShiftAmt2) {
8197 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
8198 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00008199 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00008200 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008201 }
8202 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
8203 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00008204 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00008205 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008206 }
8207 // We can simplify ((X << C) >>s C) into a trunc + sext.
8208 // NOTE: we could do this for any C, but that would make 'unusual' integer
8209 // types. For now, just stick to ones well-supported by the code
8210 // generators.
8211 const Type *SExtType = 0;
8212 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00008213 case 1 :
8214 case 8 :
8215 case 16 :
8216 case 32 :
8217 case 64 :
8218 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00008219 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00008220 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00008221 default: break;
8222 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008223 if (SExtType)
8224 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00008225 // Otherwise, we can't handle it yet.
8226 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00008227 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00008228
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008229 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008230 if (I.getOpcode() == Instruction::Shl) {
8231 assert(ShiftOp->getOpcode() == Instruction::LShr ||
8232 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008233 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00008234
Reid Spencer55702aa2007-03-25 21:11:44 +00008235 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008236 return BinaryOperator::CreateAnd(Shift,
8237 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008238 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00008239
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008240 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008241 if (I.getOpcode() == Instruction::LShr) {
8242 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008243 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008244
Reid Spencerd5e30f02007-03-26 17:18:58 +00008245 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008246 return BinaryOperator::CreateAnd(Shift,
8247 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00008248 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00008249
8250 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
8251 } else {
8252 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00008253 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00008254
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008255 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008256 if (I.getOpcode() == Instruction::Shl) {
8257 assert(ShiftOp->getOpcode() == Instruction::LShr ||
8258 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008259 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
8260 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008261
Reid Spencer55702aa2007-03-25 21:11:44 +00008262 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008263 return BinaryOperator::CreateAnd(Shift,
8264 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008265 }
8266
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008267 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008268 if (I.getOpcode() == Instruction::LShr) {
8269 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008270 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008271
Reid Spencer68d27cf2007-03-26 23:45:51 +00008272 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008273 return BinaryOperator::CreateAnd(Shift,
8274 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008275 }
8276
8277 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008278 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00008279 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00008280 return 0;
8281}
8282
Chris Lattnera1be5662002-05-02 17:06:02 +00008283
Chris Lattnercfd65102005-10-29 04:36:15 +00008284/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
8285/// expression. If so, decompose it, returning some value X, such that Val is
8286/// X*Scale+Offset.
8287///
8288static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008289 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008290 assert(Val->getType() == Type::getInt32Ty(*Context) &&
8291 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00008292 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008293 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00008294 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00008295 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00008296 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
8297 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8298 if (I->getOpcode() == Instruction::Shl) {
8299 // This is a value scaled by '1 << the shift amt'.
8300 Scale = 1U << RHS->getZExtValue();
8301 Offset = 0;
8302 return I->getOperand(0);
8303 } else if (I->getOpcode() == Instruction::Mul) {
8304 // This value is scaled by 'RHS'.
8305 Scale = RHS->getZExtValue();
8306 Offset = 0;
8307 return I->getOperand(0);
8308 } else if (I->getOpcode() == Instruction::Add) {
8309 // We have X+C. Check to see if we really have (X*C2)+C1,
8310 // where C1 is divisible by C2.
8311 unsigned SubScale;
8312 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00008313 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
8314 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00008315 Offset += RHS->getZExtValue();
8316 Scale = SubScale;
8317 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00008318 }
8319 }
8320 }
8321
8322 // Otherwise, we can't look past this.
8323 Scale = 1;
8324 Offset = 0;
8325 return Val;
8326}
8327
8328
Chris Lattnerb3f83972005-10-24 06:03:58 +00008329/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
8330/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008331Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00008332 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008333 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00008334
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008335 BuilderTy AllocaBuilder(*Builder);
8336 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
8337
Chris Lattnerb53c2382005-10-24 06:22:12 +00008338 // Remove any uses of AI that are dead.
8339 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00008340
Chris Lattnerb53c2382005-10-24 06:22:12 +00008341 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
8342 Instruction *User = cast<Instruction>(*UI++);
8343 if (isInstructionTriviallyDead(User)) {
8344 while (UI != E && *UI == User)
8345 ++UI; // If this instruction uses AI more than once, don't break UI.
8346
Chris Lattnerb53c2382005-10-24 06:22:12 +00008347 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00008348 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008349 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00008350 }
8351 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008352
8353 // This requires TargetData to get the alloca alignment and size information.
8354 if (!TD) return 0;
8355
Chris Lattnerb3f83972005-10-24 06:03:58 +00008356 // Get the type really allocated and the type casted to.
8357 const Type *AllocElTy = AI.getAllocatedType();
8358 const Type *CastElTy = PTy->getElementType();
8359 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00008360
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008361 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
8362 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00008363 if (CastElTyAlign < AllocElTyAlign) return 0;
8364
Chris Lattner39387a52005-10-24 06:35:18 +00008365 // If the allocation has multiple uses, only promote it if we are strictly
8366 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00008367 // same, we open the door to infinite loops of various kinds. (A reference
8368 // from a dbg.declare doesn't count as a use for this purpose.)
8369 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
8370 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00008371
Duncan Sands777d2302009-05-09 07:06:46 +00008372 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
8373 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008374 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00008375
Chris Lattner455fcc82005-10-29 03:19:53 +00008376 // See if we can satisfy the modulus by pulling a scale out of the array
8377 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00008378 unsigned ArraySizeScale;
8379 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00008380 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00008381 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
8382 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00008383
Chris Lattner455fcc82005-10-29 03:19:53 +00008384 // If we can now satisfy the modulus, by using a non-1 scale, we really can
8385 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00008386 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
8387 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00008388
Chris Lattner455fcc82005-10-29 03:19:53 +00008389 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
8390 Value *Amt = 0;
8391 if (Scale == 1) {
8392 Amt = NumElements;
8393 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00008394 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008395 // Insert before the alloca, not before the cast.
8396 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008397 }
8398
Jeff Cohen86796be2007-04-04 16:58:57 +00008399 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008400 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008401 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00008402 }
8403
Victor Hernandez7b929da2009-10-23 21:09:37 +00008404 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008405 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00008406 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00008407
Dale Johannesena0a66372009-03-05 00:39:02 +00008408 // If the allocation has one real use plus a dbg.declare, just remove the
8409 // declare.
8410 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8411 EraseInstFromFunction(*DI);
8412 }
8413 // If the allocation has multiple real uses, insert a cast and change all
8414 // things that used it to use the new cast. This will also hack on CI, but it
8415 // will die soon.
8416 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008417 // New is the allocation instruction, pointer typed. AI is the original
8418 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008419 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00008420 AI.replaceAllUsesWith(NewCast);
8421 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00008422 return ReplaceInstUsesWith(CI, New);
8423}
8424
Chris Lattner70074e02006-05-13 02:06:03 +00008425/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00008426/// and return it as type Ty without inserting any new casts and without
8427/// changing the computed value. This is used by code that tries to decide
8428/// whether promoting or shrinking integer operations to wider or smaller types
8429/// will allow us to eliminate a truncate or extend.
8430///
8431/// This is a truncation operation if Ty is smaller than V->getType(), or an
8432/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00008433///
8434/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
8435/// should return true if trunc(V) can be computed by computing V in the smaller
8436/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
8437/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8438/// efficiently truncated.
8439///
8440/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8441/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8442/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00008443bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008444 unsigned CastOpc,
8445 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00008446 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00008447 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00008448 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00008449
8450 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008451 if (!I) return false;
8452
Dan Gohman6de29f82009-06-15 22:12:54 +00008453 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00008454
Chris Lattner951626b2007-08-02 06:11:14 +00008455 // If this is an extension or truncate, we can often eliminate it.
8456 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8457 // If this is a cast from the destination type, we can trivially eliminate
8458 // it, and this will remove a cast overall.
8459 if (I->getOperand(0)->getType() == Ty) {
8460 // If the first operand is itself a cast, and is eliminable, do not count
8461 // this as an eliminable cast. We would prefer to eliminate those two
8462 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00008463 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00008464 ++NumCastsRemoved;
8465 return true;
8466 }
8467 }
8468
8469 // We can't extend or shrink something that has multiple uses: doing so would
8470 // require duplicating the instruction in general, which isn't profitable.
8471 if (!I->hasOneUse()) return false;
8472
Evan Chengf35fd542009-01-15 17:01:23 +00008473 unsigned Opc = I->getOpcode();
8474 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008475 case Instruction::Add:
8476 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008477 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008478 case Instruction::And:
8479 case Instruction::Or:
8480 case Instruction::Xor:
8481 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00008482 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008483 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00008484 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008485 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008486
Eli Friedman070a9812009-07-13 22:46:01 +00008487 case Instruction::UDiv:
8488 case Instruction::URem: {
8489 // UDiv and URem can be truncated if all the truncated bits are zero.
8490 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8491 uint32_t BitWidth = Ty->getScalarSizeInBits();
8492 if (BitWidth < OrigBitWidth) {
8493 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8494 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8495 MaskedValueIsZero(I->getOperand(1), Mask)) {
8496 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8497 NumCastsRemoved) &&
8498 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8499 NumCastsRemoved);
8500 }
8501 }
8502 break;
8503 }
Chris Lattner46b96052006-11-29 07:18:39 +00008504 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008505 // If we are truncating the result of this SHL, and if it's a shift of a
8506 // constant amount, we can always perform a SHL in a smaller type.
8507 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008508 uint32_t BitWidth = Ty->getScalarSizeInBits();
8509 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008510 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008511 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008512 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008513 }
8514 break;
8515 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008516 // If this is a truncate of a logical shr, we can truncate it to a smaller
8517 // lshr iff we know that the bits we would otherwise be shifting in are
8518 // already zeros.
8519 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008520 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8521 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008522 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008523 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008524 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8525 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008526 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008527 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008528 }
8529 }
Chris Lattner46b96052006-11-29 07:18:39 +00008530 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008531 case Instruction::ZExt:
8532 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008533 case Instruction::Trunc:
8534 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008535 // can safely replace it. Note that replacing it does not reduce the number
8536 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008537 if (Opc == CastOpc)
8538 return true;
8539
8540 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008541 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008542 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008543 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008544 case Instruction::Select: {
8545 SelectInst *SI = cast<SelectInst>(I);
8546 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008547 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008548 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008549 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008550 }
Chris Lattner8114b712008-06-18 04:00:49 +00008551 case Instruction::PHI: {
8552 // We can change a phi if we can change all operands.
8553 PHINode *PN = cast<PHINode>(I);
8554 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8555 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008556 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008557 return false;
8558 return true;
8559 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008560 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008561 // TODO: Can handle more cases here.
8562 break;
8563 }
8564
8565 return false;
8566}
8567
8568/// EvaluateInDifferentType - Given an expression that
8569/// CanEvaluateInDifferentType returns true for, actually insert the code to
8570/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008571Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008572 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008573 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00008574 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008575
8576 // Otherwise, it must be an instruction.
8577 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008578 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008579 unsigned Opc = I->getOpcode();
8580 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008581 case Instruction::Add:
8582 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008583 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008584 case Instruction::And:
8585 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008586 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008587 case Instruction::AShr:
8588 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008589 case Instruction::Shl:
8590 case Instruction::UDiv:
8591 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008592 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008593 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008594 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008595 break;
8596 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008597 case Instruction::Trunc:
8598 case Instruction::ZExt:
8599 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008600 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008601 // just return the source. There's no need to insert it because it is not
8602 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008603 if (I->getOperand(0)->getType() == Ty)
8604 return I->getOperand(0);
8605
Chris Lattner8114b712008-06-18 04:00:49 +00008606 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00008607 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008608 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008609 case Instruction::Select: {
8610 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8611 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8612 Res = SelectInst::Create(I->getOperand(0), True, False);
8613 break;
8614 }
Chris Lattner8114b712008-06-18 04:00:49 +00008615 case Instruction::PHI: {
8616 PHINode *OPN = cast<PHINode>(I);
8617 PHINode *NPN = PHINode::Create(Ty);
8618 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8619 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8620 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8621 }
8622 Res = NPN;
8623 break;
8624 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008625 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008626 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008627 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008628 break;
8629 }
8630
Chris Lattner8114b712008-06-18 04:00:49 +00008631 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008632 return InsertNewInstBefore(Res, *I);
8633}
8634
Reid Spencer3da59db2006-11-27 01:05:10 +00008635/// @brief Implement the transforms common to all CastInst visitors.
8636Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008637 Value *Src = CI.getOperand(0);
8638
Dan Gohman23d9d272007-05-11 21:10:54 +00008639 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008640 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008641 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008642 if (Instruction::CastOps opc =
8643 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8644 // The first cast (CSrc) is eliminable so we need to fix up or replace
8645 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008646 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008647 }
8648 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008649
Reid Spencer3da59db2006-11-27 01:05:10 +00008650 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008651 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8652 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8653 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008654
8655 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00008656 if (isa<PHINode>(Src)) {
8657 // We don't do this if this would create a PHI node with an illegal type if
8658 // it is currently legal.
8659 if (!isa<IntegerType>(Src->getType()) ||
8660 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerc22d4d12009-11-10 07:23:37 +00008661 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner9956c052009-11-08 19:23:30 +00008662 if (Instruction *NV = FoldOpIntoPhi(CI))
8663 return NV;
Chris Lattner9956c052009-11-08 19:23:30 +00008664 }
Chris Lattner9fb92132006-04-12 18:09:35 +00008665
Reid Spencer3da59db2006-11-27 01:05:10 +00008666 return 0;
8667}
8668
Chris Lattner46cd5a12009-01-09 05:44:56 +00008669/// FindElementAtOffset - Given a type and a constant offset, determine whether
8670/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008671/// the specified offset. If so, fill them into NewIndices and return the
8672/// resultant element type, otherwise return null.
8673static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8674 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008675 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008676 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008677 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008678 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008679
8680 // Start with the index over the outer type. Note that the type size
8681 // might be zero (even if the offset isn't zero) if the indexed type
8682 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008683 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008684 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008685 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008686 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008687 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008688
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008689 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008690 if (Offset < 0) {
8691 --FirstIdx;
8692 Offset += TySize;
8693 assert(Offset >= 0);
8694 }
8695 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8696 }
8697
Owen Andersoneed707b2009-07-24 23:12:02 +00008698 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008699
8700 // Index into the types. If we fail, set OrigBase to null.
8701 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008702 // Indexing into tail padding between struct/array elements.
8703 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008704 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008705
Chris Lattner46cd5a12009-01-09 05:44:56 +00008706 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8707 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008708 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8709 "Offset must stay within the indexed type");
8710
Chris Lattner46cd5a12009-01-09 05:44:56 +00008711 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008712 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008713
8714 Offset -= SL->getElementOffset(Elt);
8715 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008716 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008717 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008718 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008719 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008720 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008721 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008722 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008723 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008724 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008725 }
8726 }
8727
Chris Lattner3914f722009-01-24 01:00:13 +00008728 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008729}
8730
Chris Lattnerd3e28342007-04-27 17:44:50 +00008731/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8732Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8733 Value *Src = CI.getOperand(0);
8734
Chris Lattnerd3e28342007-04-27 17:44:50 +00008735 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008736 // If casting the result of a getelementptr instruction with no offset, turn
8737 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008738 if (GEP->hasAllZeroIndices()) {
8739 // Changing the cast operand is usually not a good idea but it is safe
8740 // here because the pointer operand is being replaced with another
8741 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008742 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008743 CI.setOperand(0, GEP->getOperand(0));
8744 return &CI;
8745 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008746
8747 // If the GEP has a single use, and the base pointer is a bitcast, and the
8748 // GEP computes a constant offset, see if we can convert these three
8749 // instructions into fewer. This typically happens with unions and other
8750 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008751 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008752 if (GEP->hasAllConstantIndices()) {
8753 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008754 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008755 int64_t Offset = OffsetV->getSExtValue();
8756
8757 // Get the base pointer input of the bitcast, and the type it points to.
8758 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8759 const Type *GEPIdxTy =
8760 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008761 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008762 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008763 // If we were able to index down into an element, create the GEP
8764 // and bitcast the result. This eliminates one bitcast, potentially
8765 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008766 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8767 Builder->CreateInBoundsGEP(OrigBase,
8768 NewIndices.begin(), NewIndices.end()) :
8769 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008770 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008771
Chris Lattner46cd5a12009-01-09 05:44:56 +00008772 if (isa<BitCastInst>(CI))
8773 return new BitCastInst(NGEP, CI.getType());
8774 assert(isa<PtrToIntInst>(CI));
8775 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008776 }
8777 }
8778 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008779 }
8780
8781 return commonCastTransforms(CI);
8782}
8783
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008784/// commonIntCastTransforms - This function implements the common transforms
8785/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008786Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8787 if (Instruction *Result = commonCastTransforms(CI))
8788 return Result;
8789
8790 Value *Src = CI.getOperand(0);
8791 const Type *SrcTy = Src->getType();
8792 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008793 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8794 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008795
Reid Spencer3da59db2006-11-27 01:05:10 +00008796 // See if we can simplify any instructions used by the LHS whose sole
8797 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008798 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008799 return &CI;
8800
8801 // If the source isn't an instruction or has more than one use then we
8802 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008803 Instruction *SrcI = dyn_cast<Instruction>(Src);
8804 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008805 return 0;
8806
Chris Lattnerc739cd62007-03-03 05:27:34 +00008807 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008808 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008809 // Only do this if the dest type is a simple type, don't convert the
8810 // expression tree to something weird like i93 unless the source is also
8811 // strange.
Chris Lattner6b583912009-11-10 17:00:47 +00008812 if ((isa<VectorType>(DestTy) ||
8813 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8814 CanEvaluateInDifferentType(SrcI, DestTy,
8815 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008816 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008817 // eliminates the cast, so it is always a win. If this is a zero-extension,
8818 // we need to do an AND to maintain the clear top-part of the computation,
8819 // so we require that the input have eliminated at least one cast. If this
8820 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008821 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008822 bool DoXForm = false;
8823 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008824 switch (CI.getOpcode()) {
8825 default:
8826 // All the others use floating point so we shouldn't actually
8827 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008828 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008829 case Instruction::Trunc:
8830 DoXForm = true;
8831 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008832 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008833 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00008834
Chris Lattner39c27ed2009-01-31 19:05:27 +00008835 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008836 // If it's unnecessary to issue an AND to clear the high bits, it's
8837 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008838 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008839 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8840 if (MaskedValueIsZero(TryRes, Mask))
8841 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008842
8843 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008844 if (TryI->use_empty())
8845 EraseInstFromFunction(*TryI);
8846 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008847 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008848 }
Evan Chengf35fd542009-01-15 17:01:23 +00008849 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008850 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008851 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008852 // If we do not have to emit the truncate + sext pair, then it's always
8853 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008854 //
8855 // It's not safe to eliminate the trunc + sext pair if one of the
8856 // eliminated cast is a truncate. e.g.
8857 // t2 = trunc i32 t1 to i16
8858 // t3 = sext i16 t2 to i32
8859 // !=
8860 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008861 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008862 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8863 if (NumSignBits > (DestBitSize - SrcBitSize))
8864 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008865
8866 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008867 if (TryI->use_empty())
8868 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008869 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008870 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008871 }
Evan Chengf35fd542009-01-15 17:01:23 +00008872 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008873
8874 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008875 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8876 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008877 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8878 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008879 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008880 // Just replace this cast with the result.
8881 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008882
Reid Spencer3da59db2006-11-27 01:05:10 +00008883 assert(Res->getType() == DestTy);
8884 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008885 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008886 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008887 // Just replace this cast with the result.
8888 return ReplaceInstUsesWith(CI, Res);
8889 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008890 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008891
8892 // If the high bits are already zero, just replace this cast with the
8893 // result.
8894 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8895 if (MaskedValueIsZero(Res, Mask))
8896 return ReplaceInstUsesWith(CI, Res);
8897
8898 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008899 Constant *C = ConstantInt::get(*Context,
8900 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008901 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008902 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008903 case Instruction::SExt: {
8904 // If the high bits are already filled with sign bit, just replace this
8905 // cast with the result.
8906 unsigned NumSignBits = ComputeNumSignBits(Res);
8907 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008908 return ReplaceInstUsesWith(CI, Res);
8909
Reid Spencer3da59db2006-11-27 01:05:10 +00008910 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008911 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008912 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008913 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008914 }
8915 }
8916
8917 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8918 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8919
8920 switch (SrcI->getOpcode()) {
8921 case Instruction::Add:
8922 case Instruction::Mul:
8923 case Instruction::And:
8924 case Instruction::Or:
8925 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008926 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008927 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8928 // Don't insert two casts unless at least one can be eliminated.
8929 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008930 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008931 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8932 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008933 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008934 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008935 }
8936 }
8937
8938 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8939 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8940 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008941 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008942 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008943 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008944 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008945 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008946 }
8947 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008948
Eli Friedman65445c52009-07-13 21:45:57 +00008949 case Instruction::Shl: {
8950 // Canonicalize trunc inside shl, if we can.
8951 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8952 if (CI && DestBitSize < SrcBitSize &&
8953 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008954 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8955 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008956 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008957 }
8958 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008959 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008960 }
8961 return 0;
8962}
8963
Chris Lattner8a9f5712007-04-11 06:57:46 +00008964Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008965 if (Instruction *Result = commonIntCastTransforms(CI))
8966 return Result;
8967
8968 Value *Src = CI.getOperand(0);
8969 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008970 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8971 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008972
8973 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008974 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008975 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008976 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008977 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008978 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008979 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008980
Chris Lattner4f9797d2009-03-24 18:15:30 +00008981 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8982 ConstantInt *ShAmtV = 0;
8983 Value *ShiftOp = 0;
8984 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008985 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008986 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8987
8988 // Get a mask for the bits shifting in.
8989 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8990 if (MaskedValueIsZero(ShiftOp, Mask)) {
8991 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008992 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008993
8994 // Okay, we can shrink this. Truncate the input, then return a new
8995 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008996 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008997 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008998 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008999 }
9000 }
Chris Lattner9956c052009-11-08 19:23:30 +00009001
Chris Lattner6aa5eb12006-11-29 07:04:07 +00009002 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009003}
9004
Evan Chengb98a10e2008-03-24 00:21:34 +00009005/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
9006/// in order to eliminate the icmp.
9007Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
9008 bool DoXform) {
9009 // If we are just checking for a icmp eq of a single bit and zext'ing it
9010 // to an integer, then shift the bit to the appropriate place and then
9011 // cast to integer to avoid the comparison.
9012 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
9013 const APInt &Op1CV = Op1C->getValue();
9014
9015 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
9016 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
9017 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9018 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
9019 if (!DoXform) return ICI;
9020
9021 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009022 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009023 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009024 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00009025 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009026 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00009027
9028 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009029 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009030 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00009031 }
9032
9033 return ReplaceInstUsesWith(CI, In);
9034 }
9035
9036
9037
9038 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
9039 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
9040 // zext (X == 1) to i32 --> X iff X has only the low bit set.
9041 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
9042 // zext (X != 0) to i32 --> X iff X has only the low bit set.
9043 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
9044 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
9045 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
9046 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
9047 // This only works for EQ and NE
9048 ICI->isEquality()) {
9049 // If Op1C some other power of two, convert:
9050 uint32_t BitWidth = Op1C->getType()->getBitWidth();
9051 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9052 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
9053 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
9054
9055 APInt KnownZeroMask(~KnownZero);
9056 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
9057 if (!DoXform) return ICI;
9058
9059 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
9060 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
9061 // (X&4) == 2 --> false
9062 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00009063 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00009064 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00009065 return ReplaceInstUsesWith(CI, Res);
9066 }
9067
9068 uint32_t ShiftAmt = KnownZeroMask.logBase2();
9069 Value *In = ICI->getOperand(0);
9070 if (ShiftAmt) {
9071 // Perform a logical shr by shiftamt.
9072 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009073 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
9074 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00009075 }
9076
9077 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00009078 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009079 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00009080 }
9081
9082 if (CI.getType() == In->getType())
9083 return ReplaceInstUsesWith(CI, In);
9084 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009085 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00009086 }
9087 }
9088 }
9089
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009090 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
9091 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
9092 // may lead to additional simplifications.
9093 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
9094 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
9095 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009096 Value *LHS = ICI->getOperand(0);
9097 Value *RHS = ICI->getOperand(1);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009098
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009099 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
9100 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
9101 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
9102 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
9103 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009104
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009105 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
9106 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
9107 APInt UnknownBit = ~KnownBits;
9108 if (UnknownBit.countPopulation() == 1) {
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009109 if (!DoXform) return ICI;
9110
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009111 Value *Result = Builder->CreateXor(LHS, RHS);
9112
9113 // Mask off any bits that are set and won't be shifted away.
9114 if (KnownOneLHS.uge(UnknownBit))
9115 Result = Builder->CreateAnd(Result,
9116 ConstantInt::get(ITy, UnknownBit));
9117
9118 // Shift the bit we're testing down to the lsb.
9119 Result = Builder->CreateLShr(
9120 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
9121
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009122 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009123 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
9124 Result->takeName(ICI);
9125 return ReplaceInstUsesWith(CI, Result);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009126 }
9127 }
9128 }
9129 }
9130
Evan Chengb98a10e2008-03-24 00:21:34 +00009131 return 0;
9132}
9133
Chris Lattner8a9f5712007-04-11 06:57:46 +00009134Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Chris Lattnerdffbef02010-01-04 06:23:24 +00009135 // If one of the common conversion will work, do it.
Reid Spencer3da59db2006-11-27 01:05:10 +00009136 if (Instruction *Result = commonIntCastTransforms(CI))
9137 return Result;
9138
9139 Value *Src = CI.getOperand(0);
9140
Chris Lattnera84f47c2009-02-17 20:47:23 +00009141 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
9142 // types and if the sizes are just right we can convert this into a logical
9143 // 'and' which will be much cheaper than the pair of casts.
9144 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
9145 // Get the sizes of the types involved. We know that the intermediate type
9146 // will be smaller than A or C, but don't know the relation between A and C.
9147 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00009148 unsigned SrcSize = A->getType()->getScalarSizeInBits();
9149 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
9150 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00009151 // If we're actually extending zero bits, then if
9152 // SrcSize < DstSize: zext(a & mask)
9153 // SrcSize == DstSize: a & mask
9154 // SrcSize > DstSize: trunc(a) & mask
9155 if (SrcSize < DstSize) {
9156 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00009157 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009158 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00009159 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009160 }
9161
9162 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00009163 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00009164 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009165 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009166 }
9167 if (SrcSize > DstSize) {
9168 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00009169 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00009170 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00009171 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009172 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00009173 }
9174 }
9175
Evan Chengb98a10e2008-03-24 00:21:34 +00009176 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
9177 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00009178
Evan Chengb98a10e2008-03-24 00:21:34 +00009179 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
9180 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
9181 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
9182 // of the (zext icmp) will be transformed.
9183 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
9184 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
9185 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
9186 (transformZExtICmp(LHS, CI, false) ||
9187 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009188 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
9189 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009190 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00009191 }
Evan Chengb98a10e2008-03-24 00:21:34 +00009192 }
9193
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009194 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00009195 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
9196 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9197 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
9198 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009199 if (TI0->getType() == CI.getType())
9200 return
9201 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00009202 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00009203 }
9204
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009205 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
9206 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
9207 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9208 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
9209 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
9210 And->getOperand(1) == C)
9211 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
9212 Value *TI0 = TI->getOperand(0);
9213 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009214 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009215 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009216 return BinaryOperator::CreateXor(NewAnd, ZC);
9217 }
9218 }
9219
Reid Spencer3da59db2006-11-27 01:05:10 +00009220 return 0;
9221}
9222
Chris Lattner8a9f5712007-04-11 06:57:46 +00009223Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00009224 if (Instruction *I = commonIntCastTransforms(CI))
9225 return I;
9226
Chris Lattner8a9f5712007-04-11 06:57:46 +00009227 Value *Src = CI.getOperand(0);
9228
Dan Gohman1975d032008-10-30 20:40:10 +00009229 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00009230 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00009231 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00009232 Constant::getAllOnesValue(CI.getType()),
9233 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00009234
9235 // See if the value being truncated is already sign extended. If so, just
9236 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00009237 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00009238 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00009239 unsigned OpBits = Op->getType()->getScalarSizeInBits();
9240 unsigned MidBits = Src->getType()->getScalarSizeInBits();
9241 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00009242 unsigned NumSignBits = ComputeNumSignBits(Op);
9243
9244 if (OpBits == DestBits) {
9245 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
9246 // bits, it is already ready.
9247 if (NumSignBits > DestBits-MidBits)
9248 return ReplaceInstUsesWith(CI, Op);
9249 } else if (OpBits < DestBits) {
9250 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
9251 // bits, just sext from i32.
9252 if (NumSignBits > OpBits-MidBits)
9253 return new SExtInst(Op, CI.getType(), "tmp");
9254 } else {
9255 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
9256 // bits, just truncate to i32.
9257 if (NumSignBits > OpBits-MidBits)
9258 return new TruncInst(Op, CI.getType(), "tmp");
9259 }
9260 }
Chris Lattner46bbad22008-08-06 07:35:52 +00009261
9262 // If the input is a shl/ashr pair of a same constant, then this is a sign
9263 // extension from a smaller value. If we could trust arbitrary bitwidth
9264 // integers, we could turn this into a truncate to the smaller bit and then
9265 // use a sext for the whole extension. Since we don't, look deeper and check
9266 // for a truncate. If the source and dest are the same type, eliminate the
9267 // trunc and extend and just do shifts. For example, turn:
9268 // %a = trunc i32 %i to i8
9269 // %b = shl i8 %a, 6
9270 // %c = ashr i8 %b, 6
9271 // %d = sext i8 %c to i32
9272 // into:
9273 // %a = shl i32 %i, 30
9274 // %d = ashr i32 %a, 30
9275 Value *A = 0;
9276 ConstantInt *BA = 0, *CA = 0;
9277 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00009278 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00009279 BA == CA && isa<TruncInst>(A)) {
9280 Value *I = cast<TruncInst>(A)->getOperand(0);
9281 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00009282 unsigned MidSize = Src->getType()->getScalarSizeInBits();
9283 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00009284 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00009285 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009286 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00009287 return BinaryOperator::CreateAShr(I, ShAmtV);
9288 }
9289 }
9290
Chris Lattnerba417832007-04-11 06:12:58 +00009291 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009292}
9293
Chris Lattnerb7530652008-01-27 05:29:54 +00009294/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
9295/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00009296static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009297 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00009298 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00009299 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00009300 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
9301 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00009302 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00009303 return 0;
9304}
9305
9306/// LookThroughFPExtensions - If this is an fp extension instruction, look
9307/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00009308static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00009309 if (Instruction *I = dyn_cast<Instruction>(V))
9310 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00009311 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00009312
9313 // If this value is a constant, return the constant in the smallest FP type
9314 // that can accurately represent it. This allows us to turn
9315 // (float)((double)X+2.0) into x+2.0f.
9316 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009317 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009318 return V; // No constant folding of this.
9319 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00009320 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009321 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00009322 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009323 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00009324 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009325 return V;
9326 // Don't try to shrink to various long double types.
9327 }
9328
9329 return V;
9330}
9331
9332Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
9333 if (Instruction *I = commonCastTransforms(CI))
9334 return I;
9335
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009336 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00009337 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009338 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00009339 // many builtins (sqrt, etc).
9340 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
9341 if (OpI && OpI->hasOneUse()) {
9342 switch (OpI->getOpcode()) {
9343 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009344 case Instruction::FAdd:
9345 case Instruction::FSub:
9346 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00009347 case Instruction::FDiv:
9348 case Instruction::FRem:
9349 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00009350 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
9351 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00009352 if (LHSTrunc->getType() != SrcTy &&
9353 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00009354 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00009355 // If the source types were both smaller than the destination type of
9356 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00009357 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
9358 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009359 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
9360 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009361 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00009362 }
9363 }
9364 break;
9365 }
9366 }
9367 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009368}
9369
9370Instruction *InstCombiner::visitFPExt(CastInst &CI) {
9371 return commonCastTransforms(CI);
9372}
9373
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009374Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009375 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9376 if (OpI == 0)
9377 return commonCastTransforms(FI);
9378
9379 // fptoui(uitofp(X)) --> X
9380 // fptoui(sitofp(X)) --> X
9381 // This is safe if the intermediate type has enough bits in its mantissa to
9382 // accurately represent all values of X. For example, do not do this with
9383 // i64->float->i64. This is also safe for sitofp case, because any negative
9384 // 'X' value would cause an undefined result for the fptoui.
9385 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9386 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009387 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00009388 OpI->getType()->getFPMantissaWidth())
9389 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009390
9391 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009392}
9393
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009394Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009395 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9396 if (OpI == 0)
9397 return commonCastTransforms(FI);
9398
9399 // fptosi(sitofp(X)) --> X
9400 // fptosi(uitofp(X)) --> X
9401 // This is safe if the intermediate type has enough bits in its mantissa to
9402 // accurately represent all values of X. For example, do not do this with
9403 // i64->float->i64. This is also safe for sitofp case, because any negative
9404 // 'X' value would cause an undefined result for the fptoui.
9405 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9406 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009407 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00009408 OpI->getType()->getFPMantissaWidth())
9409 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009410
9411 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009412}
9413
9414Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9415 return commonCastTransforms(CI);
9416}
9417
9418Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9419 return commonCastTransforms(CI);
9420}
9421
Chris Lattnera0e69692009-03-24 18:35:40 +00009422Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9423 // If the destination integer type is smaller than the intptr_t type for
9424 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
9425 // trunc to be exposed to other transforms. Don't do this for extending
9426 // ptrtoint's, because we don't know if the target sign or zero extends its
9427 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009428 if (TD &&
9429 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009430 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9431 TD->getIntPtrType(CI.getContext()),
9432 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009433 return new TruncInst(P, CI.getType());
9434 }
9435
Chris Lattnerd3e28342007-04-27 17:44:50 +00009436 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009437}
9438
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009439Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00009440 // If the source integer type is larger than the intptr_t type for
9441 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
9442 // allows the trunc to be exposed to other transforms. Don't do this for
9443 // extending inttoptr's, because we don't know if the target sign or zero
9444 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009445 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00009446 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009447 Value *P = Builder->CreateTrunc(CI.getOperand(0),
9448 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009449 return new IntToPtrInst(P, CI.getType());
9450 }
9451
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009452 if (Instruction *I = commonCastTransforms(CI))
9453 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009454
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009455 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009456}
9457
Chris Lattnerd3e28342007-04-27 17:44:50 +00009458Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009459 // If the operands are integer typed then apply the integer transforms,
9460 // otherwise just apply the common ones.
9461 Value *Src = CI.getOperand(0);
9462 const Type *SrcTy = Src->getType();
9463 const Type *DestTy = CI.getType();
9464
Eli Friedman7e25d452009-07-13 20:53:00 +00009465 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009466 if (Instruction *I = commonPointerCastTransforms(CI))
9467 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00009468 } else {
9469 if (Instruction *Result = commonCastTransforms(CI))
9470 return Result;
9471 }
9472
9473
9474 // Get rid of casts from one type to the same type. These are useless and can
9475 // be replaced by the operand.
9476 if (DestTy == Src->getType())
9477 return ReplaceInstUsesWith(CI, Src);
9478
Reid Spencer3da59db2006-11-27 01:05:10 +00009479 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009480 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9481 const Type *DstElTy = DstPTy->getElementType();
9482 const Type *SrcElTy = SrcPTy->getElementType();
9483
Nate Begeman83ad90a2008-03-31 00:22:16 +00009484 // If the address spaces don't match, don't eliminate the bitcast, which is
9485 // required for changing types.
9486 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9487 return 0;
9488
Victor Hernandez83d63912009-09-18 22:35:49 +00009489 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00009490 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00009491 // There is no need to modify malloc calls because it is their bitcast that
9492 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00009493 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00009494 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9495 return V;
9496
Chris Lattnerd717c182007-05-05 22:32:24 +00009497 // If the source and destination are pointers, and this cast is equivalent
9498 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009499 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00009500 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00009501 unsigned NumZeros = 0;
9502 while (SrcElTy != DstElTy &&
9503 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9504 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9505 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9506 ++NumZeros;
9507 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009508
Chris Lattnerd3e28342007-04-27 17:44:50 +00009509 // If we found a path from the src to dest, create the getelementptr now.
9510 if (SrcElTy == DstElTy) {
9511 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00009512 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9513 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009514 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009515 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009516
Eli Friedman2451a642009-07-18 23:06:53 +00009517 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9518 if (DestVTy->getNumElements() == 1) {
9519 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009520 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009521 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00009522 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009523 }
9524 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9525 }
9526 }
9527
9528 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9529 if (SrcVTy->getNumElements() == 1) {
9530 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009531 Value *Elem =
9532 Builder->CreateExtractElement(Src,
9533 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009534 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9535 }
9536 }
9537 }
9538
Reid Spencer3da59db2006-11-27 01:05:10 +00009539 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9540 if (SVI->hasOneUse()) {
9541 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9542 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009543 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009544 cast<VectorType>(DestTy)->getNumElements() ==
9545 SVI->getType()->getNumElements() &&
9546 SVI->getType()->getNumElements() ==
9547 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009548 CastInst *Tmp;
9549 // If either of the operands is a cast from CI.getType(), then
9550 // evaluating the shuffle in the casted destination's type will allow
9551 // us to eliminate at least one cast.
9552 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9553 Tmp->getOperand(0)->getType() == DestTy) ||
9554 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9555 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009556 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9557 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00009558 // Return a new shuffle vector. Use the same element ID's, as we
9559 // know the vector types match #elts.
9560 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009561 }
9562 }
9563 }
9564 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009565 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009566}
9567
Chris Lattnere576b912004-04-09 23:46:01 +00009568/// GetSelectFoldableOperands - We want to turn code that looks like this:
9569/// %C = or %A, %B
9570/// %D = select %cond, %C, %A
9571/// into:
9572/// %C = select %cond, %B, 0
9573/// %D = or %A, %C
9574///
9575/// Assuming that the specified instruction is an operand to the select, return
9576/// a bitmask indicating which operands of this instruction are foldable if they
9577/// equal the other incoming value of the select.
9578///
9579static unsigned GetSelectFoldableOperands(Instruction *I) {
9580 switch (I->getOpcode()) {
9581 case Instruction::Add:
9582 case Instruction::Mul:
9583 case Instruction::And:
9584 case Instruction::Or:
9585 case Instruction::Xor:
9586 return 3; // Can fold through either operand.
9587 case Instruction::Sub: // Can only fold on the amount subtracted.
9588 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009589 case Instruction::LShr:
9590 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009591 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009592 default:
9593 return 0; // Cannot fold
9594 }
9595}
9596
9597/// GetSelectFoldableConstant - For the same transformation as the previous
9598/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009599static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009600 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009601 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009602 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009603 case Instruction::Add:
9604 case Instruction::Sub:
9605 case Instruction::Or:
9606 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009607 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009608 case Instruction::LShr:
9609 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009610 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009611 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009612 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009613 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009614 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009615 }
9616}
9617
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009618/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9619/// have the same opcode and only one use each. Try to simplify this.
9620Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9621 Instruction *FI) {
9622 if (TI->getNumOperands() == 1) {
9623 // If this is a non-volatile load or a cast from the same type,
9624 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009625 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009626 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9627 return 0;
9628 } else {
9629 return 0; // unknown unary op.
9630 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009631
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009632 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009633 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009634 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009635 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009636 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009637 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009638 }
9639
Reid Spencer832254e2007-02-02 02:16:23 +00009640 // Only handle binary operators here.
9641 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009642 return 0;
9643
9644 // Figure out if the operations have any operands in common.
9645 Value *MatchOp, *OtherOpT, *OtherOpF;
9646 bool MatchIsOpZero;
9647 if (TI->getOperand(0) == FI->getOperand(0)) {
9648 MatchOp = TI->getOperand(0);
9649 OtherOpT = TI->getOperand(1);
9650 OtherOpF = FI->getOperand(1);
9651 MatchIsOpZero = true;
9652 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9653 MatchOp = TI->getOperand(1);
9654 OtherOpT = TI->getOperand(0);
9655 OtherOpF = FI->getOperand(0);
9656 MatchIsOpZero = false;
9657 } else if (!TI->isCommutative()) {
9658 return 0;
9659 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9660 MatchOp = TI->getOperand(0);
9661 OtherOpT = TI->getOperand(1);
9662 OtherOpF = FI->getOperand(0);
9663 MatchIsOpZero = true;
9664 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9665 MatchOp = TI->getOperand(1);
9666 OtherOpT = TI->getOperand(0);
9667 OtherOpF = FI->getOperand(1);
9668 MatchIsOpZero = true;
9669 } else {
9670 return 0;
9671 }
9672
9673 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009674 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9675 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009676 InsertNewInstBefore(NewSI, SI);
9677
9678 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9679 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009680 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009681 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009682 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009683 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009684 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009685 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009686}
9687
Evan Chengde621922009-03-31 20:42:45 +00009688static bool isSelect01(Constant *C1, Constant *C2) {
9689 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9690 if (!C1I)
9691 return false;
9692 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9693 if (!C2I)
9694 return false;
9695 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9696}
9697
9698/// FoldSelectIntoOp - Try fold the select into one of the operands to
9699/// facilitate further optimization.
9700Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9701 Value *FalseVal) {
9702 // See the comment above GetSelectFoldableOperands for a description of the
9703 // transformation we are doing here.
9704 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9705 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9706 !isa<Constant>(FalseVal)) {
9707 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9708 unsigned OpToFold = 0;
9709 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9710 OpToFold = 1;
9711 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9712 OpToFold = 2;
9713 }
9714
9715 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009716 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009717 Value *OOp = TVI->getOperand(2-OpToFold);
9718 // Avoid creating select between 2 constants unless it's selecting
9719 // between 0 and 1.
9720 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9721 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9722 InsertNewInstBefore(NewSel, SI);
9723 NewSel->takeName(TVI);
9724 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9725 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009726 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009727 }
9728 }
9729 }
9730 }
9731 }
9732
9733 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9734 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9735 !isa<Constant>(TrueVal)) {
9736 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9737 unsigned OpToFold = 0;
9738 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9739 OpToFold = 1;
9740 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9741 OpToFold = 2;
9742 }
9743
9744 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009745 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009746 Value *OOp = FVI->getOperand(2-OpToFold);
9747 // Avoid creating select between 2 constants unless it's selecting
9748 // between 0 and 1.
9749 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9750 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9751 InsertNewInstBefore(NewSel, SI);
9752 NewSel->takeName(FVI);
9753 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9754 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009755 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009756 }
9757 }
9758 }
9759 }
9760 }
9761
9762 return 0;
9763}
9764
Dan Gohman81b28ce2008-09-16 18:46:06 +00009765/// visitSelectInstWithICmp - Visit a SelectInst that has an
9766/// ICmpInst as its first operand.
9767///
9768Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9769 ICmpInst *ICI) {
9770 bool Changed = false;
9771 ICmpInst::Predicate Pred = ICI->getPredicate();
9772 Value *CmpLHS = ICI->getOperand(0);
9773 Value *CmpRHS = ICI->getOperand(1);
9774 Value *TrueVal = SI.getTrueValue();
9775 Value *FalseVal = SI.getFalseValue();
9776
9777 // Check cases where the comparison is with a constant that
9778 // can be adjusted to fit the min/max idiom. We may edit ICI in
9779 // place here, so make sure the select is the only user.
9780 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009781 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009782 switch (Pred) {
9783 default: break;
9784 case ICmpInst::ICMP_ULT:
9785 case ICmpInst::ICMP_SLT: {
9786 // X < MIN ? T : F --> F
9787 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9788 return ReplaceInstUsesWith(SI, FalseVal);
9789 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009790 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009791 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9792 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9793 Pred = ICmpInst::getSwappedPredicate(Pred);
9794 CmpRHS = AdjustedRHS;
9795 std::swap(FalseVal, TrueVal);
9796 ICI->setPredicate(Pred);
9797 ICI->setOperand(1, CmpRHS);
9798 SI.setOperand(1, TrueVal);
9799 SI.setOperand(2, FalseVal);
9800 Changed = true;
9801 }
9802 break;
9803 }
9804 case ICmpInst::ICMP_UGT:
9805 case ICmpInst::ICMP_SGT: {
9806 // X > MAX ? T : F --> F
9807 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9808 return ReplaceInstUsesWith(SI, FalseVal);
9809 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009810 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009811 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9812 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9813 Pred = ICmpInst::getSwappedPredicate(Pred);
9814 CmpRHS = AdjustedRHS;
9815 std::swap(FalseVal, TrueVal);
9816 ICI->setPredicate(Pred);
9817 ICI->setOperand(1, CmpRHS);
9818 SI.setOperand(1, TrueVal);
9819 SI.setOperand(2, FalseVal);
9820 Changed = true;
9821 }
9822 break;
9823 }
9824 }
9825
Dan Gohman1975d032008-10-30 20:40:10 +00009826 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9827 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009828 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009829 if (match(TrueVal, m_ConstantInt<-1>()) &&
9830 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009831 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009832 else if (match(TrueVal, m_ConstantInt<0>()) &&
9833 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009834 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9835
Dan Gohman1975d032008-10-30 20:40:10 +00009836 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9837 // If we are just checking for a icmp eq of a single bit and zext'ing it
9838 // to an integer, then shift the bit to the appropriate place and then
9839 // cast to integer to avoid the comparison.
9840 const APInt &Op1CV = CI->getValue();
9841
9842 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9843 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9844 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009845 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009846 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009847 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009848 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009849 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009850 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009851 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009852 if (In->getType() != SI.getType())
9853 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009854 true/*SExt*/, "tmp", ICI);
9855
9856 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009857 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009858 In->getName()+".not"), *ICI);
9859
9860 return ReplaceInstUsesWith(SI, In);
9861 }
9862 }
9863 }
9864
Dan Gohman81b28ce2008-09-16 18:46:06 +00009865 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9866 // Transform (X == Y) ? X : Y -> Y
9867 if (Pred == ICmpInst::ICMP_EQ)
9868 return ReplaceInstUsesWith(SI, FalseVal);
9869 // Transform (X != Y) ? X : Y -> X
9870 if (Pred == ICmpInst::ICMP_NE)
9871 return ReplaceInstUsesWith(SI, TrueVal);
9872 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9873
9874 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9875 // Transform (X == Y) ? Y : X -> X
9876 if (Pred == ICmpInst::ICMP_EQ)
9877 return ReplaceInstUsesWith(SI, FalseVal);
9878 // Transform (X != Y) ? Y : X -> Y
9879 if (Pred == ICmpInst::ICMP_NE)
9880 return ReplaceInstUsesWith(SI, TrueVal);
9881 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9882 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009883 return Changed ? &SI : 0;
9884}
9885
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009886
Chris Lattner7f239582009-10-22 00:17:26 +00009887/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9888/// PHI node (but the two may be in different blocks). See if the true/false
9889/// values (V) are live in all of the predecessor blocks of the PHI. For
9890/// example, cases like this cannot be mapped:
9891///
9892/// X = phi [ C1, BB1], [C2, BB2]
9893/// Y = add
9894/// Z = select X, Y, 0
9895///
9896/// because Y is not live in BB1/BB2.
9897///
9898static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9899 const SelectInst &SI) {
9900 // If the value is a non-instruction value like a constant or argument, it
9901 // can always be mapped.
9902 const Instruction *I = dyn_cast<Instruction>(V);
9903 if (I == 0) return true;
9904
9905 // If V is a PHI node defined in the same block as the condition PHI, we can
9906 // map the arguments.
9907 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9908
9909 if (const PHINode *VP = dyn_cast<PHINode>(I))
9910 if (VP->getParent() == CondPHI->getParent())
9911 return true;
9912
9913 // Otherwise, if the PHI and select are defined in the same block and if V is
9914 // defined in a different block, then we can transform it.
9915 if (SI.getParent() == CondPHI->getParent() &&
9916 I->getParent() != CondPHI->getParent())
9917 return true;
9918
9919 // Otherwise we have a 'hard' case and we can't tell without doing more
9920 // detailed dominator based analysis, punt.
9921 return false;
9922}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009923
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009924/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
9925/// SPF2(SPF1(A, B), C)
9926Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
9927 SelectPatternFlavor SPF1,
9928 Value *A, Value *B,
9929 Instruction &Outer,
9930 SelectPatternFlavor SPF2, Value *C) {
9931 if (C == A || C == B) {
9932 // MAX(MAX(A, B), B) -> MAX(A, B)
9933 // MIN(MIN(a, b), a) -> MIN(a, b)
9934 if (SPF1 == SPF2)
9935 return ReplaceInstUsesWith(Outer, Inner);
9936
9937 // MAX(MIN(a, b), a) -> a
9938 // MIN(MAX(a, b), a) -> a
Daniel Dunbareddfaaf2009-12-21 23:27:57 +00009939 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
9940 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
9941 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
9942 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009943 return ReplaceInstUsesWith(Outer, C);
9944 }
9945
9946 // TODO: MIN(MIN(A, 23), 97)
9947 return 0;
9948}
9949
9950
9951
9952
Chris Lattner3d69f462004-03-12 05:52:32 +00009953Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009954 Value *CondVal = SI.getCondition();
9955 Value *TrueVal = SI.getTrueValue();
9956 Value *FalseVal = SI.getFalseValue();
9957
9958 // select true, X, Y -> X
9959 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009960 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009961 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009962
9963 // select C, X, X -> X
9964 if (TrueVal == FalseVal)
9965 return ReplaceInstUsesWith(SI, TrueVal);
9966
Chris Lattnere87597f2004-10-16 18:11:37 +00009967 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9968 return ReplaceInstUsesWith(SI, FalseVal);
9969 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9970 return ReplaceInstUsesWith(SI, TrueVal);
9971 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9972 if (isa<Constant>(TrueVal))
9973 return ReplaceInstUsesWith(SI, TrueVal);
9974 else
9975 return ReplaceInstUsesWith(SI, FalseVal);
9976 }
9977
Owen Anderson1d0be152009-08-13 21:58:54 +00009978 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009979 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009980 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009981 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009982 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009983 } else {
9984 // Change: A = select B, false, C --> A = and !B, C
9985 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009986 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009987 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009988 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009989 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009990 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009991 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009992 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009993 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009994 } else {
9995 // Change: A = select B, C, true --> A = or !B, C
9996 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009997 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009998 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009999 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +000010000 }
10001 }
Chris Lattnercfa59752007-11-25 21:27:53 +000010002
10003 // select a, b, a -> a&b
10004 // select a, a, b -> a|b
10005 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010006 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +000010007 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010008 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010009 }
Chris Lattner0c199a72004-04-08 04:43:23 +000010010
Chris Lattner2eefe512004-04-09 19:05:30 +000010011 // Selecting between two integer constants?
10012 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
10013 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +000010014 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +000010015 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010016 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +000010017 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +000010018 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +000010019 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +000010020 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +000010021 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010022 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +000010023 }
Chris Lattner457dd822004-06-09 07:59:58 +000010024
Reid Spencere4d87aa2006-12-23 06:05:41 +000010025 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +000010026 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +000010027 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +000010028 // non-constant value, eliminate this whole mess. This corresponds to
10029 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +000010030 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +000010031 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +000010032 cast<Constant>(IC->getOperand(1))->isNullValue())
10033 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
10034 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010035 isa<ConstantInt>(ICA->getOperand(1)) &&
10036 (ICA->getOperand(1) == TrueValC ||
10037 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +000010038 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
10039 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +000010040 // know whether we have a icmp_ne or icmp_eq and whether the
10041 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +000010042 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +000010043 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +000010044 Value *V = ICA;
10045 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010046 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +000010047 Instruction::Xor, V, ICA->getOperand(1)), SI);
10048 return ReplaceInstUsesWith(SI, V);
10049 }
Chris Lattnerb8456462006-09-20 04:44:59 +000010050 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +000010051 }
Chris Lattnerd76956d2004-04-10 22:21:27 +000010052
10053 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +000010054 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
10055 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +000010056 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +000010057 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
10058 // This is not safe in general for floating point:
10059 // consider X== -0, Y== +0.
10060 // It becomes safe if either operand is a nonzero constant.
10061 ConstantFP *CFPt, *CFPf;
10062 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
10063 !CFPt->getValueAPF().isZero()) ||
10064 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
10065 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +000010066 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +000010067 }
Chris Lattnerd76956d2004-04-10 22:21:27 +000010068 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +000010069 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +000010070 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +000010071 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +000010072
Reid Spencere4d87aa2006-12-23 06:05:41 +000010073 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +000010074 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +000010075 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
10076 // This is not safe in general for floating point:
10077 // consider X== -0, Y== +0.
10078 // It becomes safe if either operand is a nonzero constant.
10079 ConstantFP *CFPt, *CFPf;
10080 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
10081 !CFPt->getValueAPF().isZero()) ||
10082 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
10083 !CFPf->getValueAPF().isZero()))
10084 return ReplaceInstUsesWith(SI, FalseVal);
10085 }
Chris Lattnerd76956d2004-04-10 22:21:27 +000010086 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +000010087 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
10088 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +000010089 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +000010090 }
Dan Gohman81b28ce2008-09-16 18:46:06 +000010091 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +000010092 }
10093
10094 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +000010095 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
10096 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
10097 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +000010098
Chris Lattner87875da2005-01-13 22:52:24 +000010099 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
10100 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
10101 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +000010102 Instruction *AddOp = 0, *SubOp = 0;
10103
Chris Lattner6fb5a4a2005-01-19 21:50:18 +000010104 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
10105 if (TI->getOpcode() == FI->getOpcode())
10106 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
10107 return IV;
10108
10109 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
10110 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +000010111 if ((TI->getOpcode() == Instruction::Sub &&
10112 FI->getOpcode() == Instruction::Add) ||
10113 (TI->getOpcode() == Instruction::FSub &&
10114 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +000010115 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +000010116 } else if ((FI->getOpcode() == Instruction::Sub &&
10117 TI->getOpcode() == Instruction::Add) ||
10118 (FI->getOpcode() == Instruction::FSub &&
10119 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +000010120 AddOp = TI; SubOp = FI;
10121 }
10122
10123 if (AddOp) {
10124 Value *OtherAddOp = 0;
10125 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
10126 OtherAddOp = AddOp->getOperand(1);
10127 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
10128 OtherAddOp = AddOp->getOperand(0);
10129 }
10130
10131 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +000010132 // So at this point we know we have (Y -> OtherAddOp):
10133 // select C, (add X, Y), (sub X, Z)
10134 Value *NegVal; // Compute -Z
10135 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +000010136 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +000010137 } else {
10138 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +000010139 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +000010140 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +000010141 }
Chris Lattner97f37a42006-02-24 18:05:58 +000010142
10143 Value *NewTrueOp = OtherAddOp;
10144 Value *NewFalseOp = NegVal;
10145 if (AddOp != TI)
10146 std::swap(NewTrueOp, NewFalseOp);
10147 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010148 SelectInst::Create(CondVal, NewTrueOp,
10149 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +000010150
10151 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010152 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +000010153 }
10154 }
10155 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010156
Chris Lattnere576b912004-04-09 23:46:01 +000010157 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +000010158 if (SI.getType()->isInteger()) {
Chris Lattnerb109b5c2009-12-21 06:03:05 +000010159 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Chengde621922009-03-31 20:42:45 +000010160 return FoldI;
Chris Lattnerb109b5c2009-12-21 06:03:05 +000010161
10162 // MAX(MAX(a, b), a) -> MAX(a, b)
10163 // MIN(MIN(a, b), a) -> MIN(a, b)
10164 // MAX(MIN(a, b), a) -> a
10165 // MIN(MAX(a, b), a) -> a
10166 Value *LHS, *RHS, *LHS2, *RHS2;
10167 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
10168 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
10169 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
10170 SI, SPF, RHS))
10171 return R;
10172 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
10173 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
10174 SI, SPF, LHS))
10175 return R;
10176 }
10177
10178 // TODO.
10179 // ABS(-X) -> ABS(X)
10180 // ABS(ABS(X)) -> ABS(X)
Chris Lattnere576b912004-04-09 23:46:01 +000010181 }
Chris Lattnera1df33c2005-04-24 07:30:14 +000010182
Chris Lattner7f239582009-10-22 00:17:26 +000010183 // See if we can fold the select into a phi node if the condition is a select.
10184 if (isa<PHINode>(SI.getCondition()))
10185 // The true/false values have to be live in the PHI predecessor's blocks.
10186 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
10187 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
10188 if (Instruction *NV = FoldOpIntoPhi(SI))
10189 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +000010190
Chris Lattnera1df33c2005-04-24 07:30:14 +000010191 if (BinaryOperator::isNot(CondVal)) {
10192 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
10193 SI.setOperand(1, FalseVal);
10194 SI.setOperand(2, TrueVal);
10195 return &SI;
10196 }
10197
Chris Lattner3d69f462004-03-12 05:52:32 +000010198 return 0;
10199}
10200
Dan Gohmaneee962e2008-04-10 18:43:06 +000010201/// EnforceKnownAlignment - If the specified pointer points to an object that
10202/// we control, modify the object's alignment to PrefAlign. This isn't
10203/// often possible though. If alignment is important, a more reliable approach
10204/// is to simply align all global variables and allocation instructions to
10205/// their preferred alignment from the beginning.
10206///
10207static unsigned EnforceKnownAlignment(Value *V,
10208 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +000010209
Dan Gohmaneee962e2008-04-10 18:43:06 +000010210 User *U = dyn_cast<User>(V);
10211 if (!U) return Align;
10212
Dan Gohmanca178902009-07-17 20:47:02 +000010213 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +000010214 default: break;
10215 case Instruction::BitCast:
10216 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
10217 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +000010218 // If all indexes are zero, it is just the alignment of the base pointer.
10219 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +000010220 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +000010221 if (!isa<Constant>(*i) ||
10222 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +000010223 AllZeroOperands = false;
10224 break;
10225 }
Chris Lattnerf2369f22007-08-09 19:05:49 +000010226
10227 if (AllZeroOperands) {
10228 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010229 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +000010230 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010231 break;
Chris Lattner95a959d2006-03-06 20:18:44 +000010232 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010233 }
10234
10235 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
10236 // If there is a large requested alignment and we can, bump up the alignment
10237 // of the global.
10238 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +000010239 if (GV->getAlignment() >= PrefAlign)
10240 Align = GV->getAlignment();
10241 else {
10242 GV->setAlignment(PrefAlign);
10243 Align = PrefAlign;
10244 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010245 }
Chris Lattner42ebefa2009-09-27 21:42:46 +000010246 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
10247 // If there is a requested alignment and if this is an alloca, round up.
10248 if (AI->getAlignment() >= PrefAlign)
10249 Align = AI->getAlignment();
10250 else {
10251 AI->setAlignment(PrefAlign);
10252 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +000010253 }
10254 }
10255
10256 return Align;
10257}
10258
10259/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
10260/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
10261/// and it is more than the alignment of the ultimate object, see if we can
10262/// increase the alignment of the ultimate object, making this check succeed.
10263unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
10264 unsigned PrefAlign) {
10265 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
10266 sizeof(PrefAlign) * CHAR_BIT;
10267 APInt Mask = APInt::getAllOnesValue(BitWidth);
10268 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
10269 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
10270 unsigned TrailZ = KnownZero.countTrailingOnes();
10271 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
10272
10273 if (PrefAlign > Align)
10274 Align = EnforceKnownAlignment(V, Align, PrefAlign);
10275
10276 // We don't need to make any adjustment.
10277 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +000010278}
10279
Chris Lattnerf497b022008-01-13 23:50:23 +000010280Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +000010281 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +000010282 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +000010283 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010284 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +000010285
10286 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010287 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +000010288 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +000010289 return MI;
10290 }
10291
10292 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
10293 // load/store.
10294 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
10295 if (MemOpLength == 0) return 0;
10296
Chris Lattner37ac6082008-01-14 00:28:35 +000010297 // Source and destination pointer types are always "i8*" for intrinsic. See
10298 // if the size is something we can handle with a single primitive load/store.
10299 // A single load+store correctly handles overlapping memory in the memmove
10300 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +000010301 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +000010302 if (Size == 0) return MI; // Delete this mem transfer.
10303
10304 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +000010305 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +000010306
Chris Lattner37ac6082008-01-14 00:28:35 +000010307 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +000010308 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +000010309 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +000010310
10311 // Memcpy forces the use of i8* for the source and destination. That means
10312 // that if you're using memcpy to move one double around, you'll get a cast
10313 // from double* to i8*. We'd much rather use a double load+store rather than
10314 // an i64 load+store, here because this improves the odds that the source or
10315 // dest address will be promotable. See if we can find a better type than the
10316 // integer datatype.
10317 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
10318 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010319 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +000010320 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
10321 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +000010322 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +000010323 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
10324 if (STy->getNumElements() == 1)
10325 SrcETy = STy->getElementType(0);
10326 else
10327 break;
10328 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
10329 if (ATy->getNumElements() == 1)
10330 SrcETy = ATy->getElementType();
10331 else
10332 break;
10333 } else
10334 break;
10335 }
10336
Dan Gohman8f8e2692008-05-23 01:52:21 +000010337 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +000010338 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +000010339 }
10340 }
10341
10342
Chris Lattnerf497b022008-01-13 23:50:23 +000010343 // If the memcpy/memmove provides better alignment info than we can
10344 // infer, use it.
10345 SrcAlign = std::max(SrcAlign, CopyAlign);
10346 DstAlign = std::max(DstAlign, CopyAlign);
10347
Chris Lattner08142f22009-08-30 19:47:22 +000010348 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
10349 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +000010350 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
10351 InsertNewInstBefore(L, *MI);
10352 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
10353
10354 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010355 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +000010356 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +000010357}
Chris Lattner3d69f462004-03-12 05:52:32 +000010358
Chris Lattner69ea9d22008-04-30 06:39:11 +000010359Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
10360 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010361 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010362 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +000010363 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010364 return MI;
10365 }
10366
10367 // Extract the length and alignment and fill if they are constant.
10368 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
10369 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +000010370 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +000010371 return 0;
10372 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010373 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +000010374
10375 // If the length is zero, this is a no-op
10376 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
10377
10378 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
10379 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010380 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +000010381
10382 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +000010383 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010384
10385 // Alignment 0 is identity for alignment 1 for memset, but not store.
10386 if (Alignment == 0) Alignment = 1;
10387
10388 // Extract the fill value and store.
10389 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +000010390 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +000010391 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +000010392
10393 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010394 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010395 return MI;
10396 }
10397
10398 return 0;
10399}
10400
10401
Chris Lattner8b0ea312006-01-13 20:11:04 +000010402/// visitCallInst - CallInst simplification. This mostly only handles folding
10403/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
10404/// the heavy lifting.
10405///
Chris Lattner9fe38862003-06-19 17:00:31 +000010406Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +000010407 if (isFreeCall(&CI))
10408 return visitFree(CI);
10409
Chris Lattneraab6ec42009-05-13 17:39:14 +000010410 // If the caller function is nounwind, mark the call as nounwind, even if the
10411 // callee isn't.
10412 if (CI.getParent()->getParent()->doesNotThrow() &&
10413 !CI.doesNotThrow()) {
10414 CI.setDoesNotThrow();
10415 return &CI;
10416 }
10417
Chris Lattner8b0ea312006-01-13 20:11:04 +000010418 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
10419 if (!II) return visitCallSite(&CI);
10420
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010421 // Intrinsics cannot occur in an invoke, so handle them here instead of in
10422 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +000010423 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010424 bool Changed = false;
10425
10426 // memmove/cpy/set of zero bytes is a noop.
10427 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
10428 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
10429
Chris Lattner35b9e482004-10-12 04:52:52 +000010430 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +000010431 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010432 // Replace the instruction with just byte operations. We would
10433 // transform other cases to loads/stores, but we don't know if
10434 // alignment is sufficient.
10435 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010436 }
10437
Chris Lattner35b9e482004-10-12 04:52:52 +000010438 // If we have a memmove and the source operation is a constant global,
10439 // then the source and dest pointers can't alias, so we can change this
10440 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +000010441 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010442 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
10443 if (GVSrc->isConstant()) {
10444 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +000010445 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10446 const Type *Tys[1];
10447 Tys[0] = CI.getOperand(3)->getType();
10448 CI.setOperand(0,
10449 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +000010450 Changed = true;
10451 }
Eli Friedman0c826d92009-12-17 21:07:31 +000010452 }
Chris Lattnera935db82008-05-28 05:30:41 +000010453
Eli Friedman0c826d92009-12-17 21:07:31 +000010454 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +000010455 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +000010456 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +000010457 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +000010458 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010459
Chris Lattner95a959d2006-03-06 20:18:44 +000010460 // If we can determine a pointer alignment that is bigger than currently
10461 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +000010462 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +000010463 if (Instruction *I = SimplifyMemTransfer(MI))
10464 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +000010465 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10466 if (Instruction *I = SimplifyMemSet(MSI))
10467 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +000010468 }
10469
Chris Lattner8b0ea312006-01-13 20:11:04 +000010470 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010471 }
10472
10473 switch (II->getIntrinsicID()) {
10474 default: break;
10475 case Intrinsic::bswap:
10476 // bswap(bswap(x)) -> x
10477 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10478 if (Operand->getIntrinsicID() == Intrinsic::bswap)
10479 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +000010480
10481 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
10482 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
10483 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
10484 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
10485 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
10486 TI->getType()->getPrimitiveSizeInBits();
10487 Value *CV = ConstantInt::get(Operand->getType(), C);
10488 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
10489 return new TruncInst(V, TI->getType());
10490 }
10491 }
10492
Chris Lattner0521e3c2008-06-18 04:33:20 +000010493 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +000010494 case Intrinsic::powi:
10495 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
10496 // powi(x, 0) -> 1.0
10497 if (Power->isZero())
10498 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
10499 // powi(x, 1) -> x
10500 if (Power->isOne())
10501 return ReplaceInstUsesWith(CI, II->getOperand(1));
10502 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +000010503 if (Power->isAllOnesValue())
10504 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
10505 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +000010506 }
10507 break;
10508
Chris Lattner2bbac752009-11-26 21:42:47 +000010509 case Intrinsic::uadd_with_overflow: {
10510 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10511 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10512 uint32_t BitWidth = IT->getBitWidth();
10513 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +000010514 APInt LHSKnownZero(BitWidth, 0);
10515 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010516 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10517 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10518 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10519
10520 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +000010521 APInt RHSKnownZero(BitWidth, 0);
10522 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010523 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10524 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10525 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10526 if (LHSKnownNegative && RHSKnownNegative) {
10527 // The sign bit is set in both cases: this MUST overflow.
10528 // Create a simple add instruction, and insert it into the struct.
10529 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10530 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010531 Constant *V[] = {
10532 UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10533 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010534 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10535 return InsertValueInst::Create(Struct, Add, 0);
10536 }
10537
10538 if (LHSKnownPositive && RHSKnownPositive) {
10539 // The sign bit is clear in both cases: this CANNOT overflow.
10540 // Create a simple add instruction, and insert it into the struct.
10541 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10542 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010543 Constant *V[] = {
10544 UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10545 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010546 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10547 return InsertValueInst::Create(Struct, Add, 0);
10548 }
10549 }
10550 }
10551 // FALL THROUGH uadd into sadd
10552 case Intrinsic::sadd_with_overflow:
10553 // Canonicalize constants into the RHS.
10554 if (isa<Constant>(II->getOperand(1)) &&
10555 !isa<Constant>(II->getOperand(2))) {
10556 Value *LHS = II->getOperand(1);
10557 II->setOperand(1, II->getOperand(2));
10558 II->setOperand(2, LHS);
10559 return II;
10560 }
10561
10562 // X + undef -> undef
10563 if (isa<UndefValue>(II->getOperand(2)))
10564 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10565
10566 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10567 // X + 0 -> {X, false}
10568 if (RHS->isZero()) {
10569 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010570 UndefValue::get(II->getOperand(0)->getType()),
10571 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010572 };
10573 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10574 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10575 }
10576 }
10577 break;
10578 case Intrinsic::usub_with_overflow:
10579 case Intrinsic::ssub_with_overflow:
10580 // undef - X -> undef
10581 // X - undef -> undef
10582 if (isa<UndefValue>(II->getOperand(1)) ||
10583 isa<UndefValue>(II->getOperand(2)))
10584 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10585
10586 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10587 // X - 0 -> {X, false}
10588 if (RHS->isZero()) {
10589 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010590 UndefValue::get(II->getOperand(1)->getType()),
10591 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010592 };
10593 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10594 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10595 }
10596 }
10597 break;
10598 case Intrinsic::umul_with_overflow:
10599 case Intrinsic::smul_with_overflow:
10600 // Canonicalize constants into the RHS.
10601 if (isa<Constant>(II->getOperand(1)) &&
10602 !isa<Constant>(II->getOperand(2))) {
10603 Value *LHS = II->getOperand(1);
10604 II->setOperand(1, II->getOperand(2));
10605 II->setOperand(2, LHS);
10606 return II;
10607 }
10608
10609 // X * undef -> undef
10610 if (isa<UndefValue>(II->getOperand(2)))
10611 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10612
10613 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10614 // X*0 -> {0, false}
10615 if (RHSI->isZero())
10616 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10617
10618 // X * 1 -> {X, false}
10619 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +000010620 Constant *V[] = {
10621 UndefValue::get(II->getOperand(1)->getType()),
10622 ConstantInt::getFalse(*Context)
10623 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010624 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +000010625 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010626 }
10627 }
10628 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010629 case Intrinsic::ppc_altivec_lvx:
10630 case Intrinsic::ppc_altivec_lvxl:
10631 case Intrinsic::x86_sse_loadu_ps:
10632 case Intrinsic::x86_sse2_loadu_pd:
10633 case Intrinsic::x86_sse2_loadu_dq:
10634 // Turn PPC lvx -> load if the pointer is known aligned.
10635 // Turn X86 loadups -> load if the pointer is known aligned.
10636 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +000010637 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10638 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +000010639 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +000010640 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010641 break;
10642 case Intrinsic::ppc_altivec_stvx:
10643 case Intrinsic::ppc_altivec_stvxl:
10644 // Turn stvx -> store if the pointer is known aligned.
10645 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10646 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010647 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010648 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010649 return new StoreInst(II->getOperand(1), Ptr);
10650 }
10651 break;
10652 case Intrinsic::x86_sse_storeu_ps:
10653 case Intrinsic::x86_sse2_storeu_pd:
10654 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +000010655 // Turn X86 storeu -> store if the pointer is known aligned.
10656 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10657 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010658 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010659 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010660 return new StoreInst(II->getOperand(2), Ptr);
10661 }
10662 break;
10663
10664 case Intrinsic::x86_sse_cvttss2si: {
10665 // These intrinsics only demands the 0th element of its input vector. If
10666 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +000010667 unsigned VWidth =
10668 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10669 APInt DemandedElts(VWidth, 1);
10670 APInt UndefElts(VWidth, 0);
10671 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +000010672 UndefElts)) {
10673 II->setOperand(1, V);
10674 return II;
10675 }
10676 break;
10677 }
10678
10679 case Intrinsic::ppc_altivec_vperm:
10680 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10681 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10682 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +000010683
Chris Lattner0521e3c2008-06-18 04:33:20 +000010684 // Check that all of the elements are integer constants or undefs.
10685 bool AllEltsOk = true;
10686 for (unsigned i = 0; i != 16; ++i) {
10687 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10688 !isa<UndefValue>(Mask->getOperand(i))) {
10689 AllEltsOk = false;
10690 break;
10691 }
10692 }
10693
10694 if (AllEltsOk) {
10695 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +000010696 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10697 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010698 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010699
Chris Lattner0521e3c2008-06-18 04:33:20 +000010700 // Only extract each element once.
10701 Value *ExtractedElts[32];
10702 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10703
Chris Lattnere2ed0572006-04-06 19:19:17 +000010704 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010705 if (isa<UndefValue>(Mask->getOperand(i)))
10706 continue;
10707 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10708 Idx &= 31; // Match the hardware behavior.
10709
10710 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010711 ExtractedElts[Idx] =
10712 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10713 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10714 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010715 }
Chris Lattnere2ed0572006-04-06 19:19:17 +000010716
Chris Lattner0521e3c2008-06-18 04:33:20 +000010717 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010718 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10719 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10720 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010721 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010722 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010723 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010724 }
10725 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010726
Chris Lattner0521e3c2008-06-18 04:33:20 +000010727 case Intrinsic::stackrestore: {
10728 // If the save is right next to the restore, remove the restore. This can
10729 // happen when variable allocas are DCE'd.
10730 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10731 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10732 BasicBlock::iterator BI = SS;
10733 if (&*++BI == II)
10734 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010735 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010736 }
10737
10738 // Scan down this block to see if there is another stack restore in the
10739 // same block without an intervening call/alloca.
10740 BasicBlock::iterator BI = II;
10741 TerminatorInst *TI = II->getParent()->getTerminator();
10742 bool CannotRemove = false;
10743 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +000010744 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010745 CannotRemove = true;
10746 break;
10747 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010748 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10749 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10750 // If there is a stackrestore below this one, remove this one.
10751 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10752 return EraseInstFromFunction(CI);
10753 // Otherwise, ignore the intrinsic.
10754 } else {
10755 // If we found a non-intrinsic call, we can't remove the stack
10756 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010757 CannotRemove = true;
10758 break;
10759 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010760 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010761 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010762
10763 // If the stack restore is in a return/unwind block and if there are no
10764 // allocas or calls between the restore and the return, nuke the restore.
10765 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10766 return EraseInstFromFunction(CI);
10767 break;
10768 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010769 }
10770
Chris Lattner8b0ea312006-01-13 20:11:04 +000010771 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010772}
10773
10774// InvokeInst simplification
10775//
10776Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010777 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010778}
10779
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010780/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10781/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010782static bool isSafeToEliminateVarargsCast(const CallSite CS,
10783 const CastInst * const CI,
10784 const TargetData * const TD,
10785 const int ix) {
10786 if (!CI->isLosslessCast())
10787 return false;
10788
10789 // The size of ByVal arguments is derived from the type, so we
10790 // can't change to a type with a different size. If the size were
10791 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010792 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010793 return true;
10794
10795 const Type* SrcTy =
10796 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10797 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10798 if (!SrcTy->isSized() || !DstTy->isSized())
10799 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010800 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010801 return false;
10802 return true;
10803}
10804
Chris Lattnera44d8a22003-10-07 22:32:43 +000010805// visitCallSite - Improvements for call and invoke instructions.
10806//
10807Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010808 bool Changed = false;
10809
10810 // If the callee is a constexpr cast of a function, attempt to move the cast
10811 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010812 if (transformConstExprCastCall(CS)) return 0;
10813
Chris Lattner6c266db2003-10-07 22:54:13 +000010814 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010815
Chris Lattner08b22ec2005-05-13 07:09:09 +000010816 if (Function *CalleeF = dyn_cast<Function>(Callee))
10817 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10818 Instruction *OldCall = CS.getInstruction();
10819 // If the call and callee calling conventions don't match, this call must
10820 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010821 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010822 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010823 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010824 // If OldCall dues not return void then replaceAllUsesWith undef.
10825 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010826 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010827 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010828 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10829 return EraseInstFromFunction(*OldCall);
10830 return 0;
10831 }
10832
Chris Lattner17be6352004-10-18 02:59:09 +000010833 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10834 // This instruction is not reachable, just remove it. We insert a store to
10835 // undef so that we know that this code is not reachable, despite the fact
10836 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010837 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010838 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010839 CS.getInstruction());
10840
Devang Patel228ebd02009-10-13 22:56:32 +000010841 // If CS dues not return void then replaceAllUsesWith undef.
10842 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010843 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010844 CS.getInstruction()->
10845 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010846
10847 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10848 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010849 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010850 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010851 }
Chris Lattner17be6352004-10-18 02:59:09 +000010852 return EraseInstFromFunction(*CS.getInstruction());
10853 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010854
Duncan Sandscdb6d922007-09-17 10:26:40 +000010855 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10856 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10857 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10858 return transformCallThroughTrampoline(CS);
10859
Chris Lattner6c266db2003-10-07 22:54:13 +000010860 const PointerType *PTy = cast<PointerType>(Callee->getType());
10861 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10862 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010863 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010864 // See if we can optimize any arguments passed through the varargs area of
10865 // the call.
10866 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010867 E = CS.arg_end(); I != E; ++I, ++ix) {
10868 CastInst *CI = dyn_cast<CastInst>(*I);
10869 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10870 *I = CI->getOperand(0);
10871 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010872 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010873 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010874 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010875
Duncan Sandsf0c33542007-12-19 21:13:37 +000010876 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010877 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010878 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010879 Changed = true;
10880 }
10881
Chris Lattner6c266db2003-10-07 22:54:13 +000010882 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010883}
10884
Chris Lattner9fe38862003-06-19 17:00:31 +000010885// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10886// attempt to move the cast to the arguments of the call/invoke.
10887//
10888bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10889 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10890 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010891 if (CE->getOpcode() != Instruction::BitCast ||
10892 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010893 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010894 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010895 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010896 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010897
10898 // Okay, this is a cast from a function to a different type. Unless doing so
10899 // would cause a type conversion of one of our arguments, change this call to
10900 // be a direct call with arguments casted to the appropriate types.
10901 //
10902 const FunctionType *FT = Callee->getFunctionType();
10903 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010904 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010905
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010906 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010907 return false; // TODO: Handle multiple return values.
10908
Chris Lattnerf78616b2004-01-14 06:06:08 +000010909 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010910 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010911 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010912 // Conversion is ok if changing from one pointer type to another or from
10913 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010914 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010915 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010916 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010917 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010918 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010919
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010920 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010921 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010922 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010923 return false; // Cannot transform this return value.
10924
Chris Lattner58d74912008-03-12 17:45:29 +000010925 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010926 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010927 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010928 return false; // Attribute not compatible with transformed value.
10929 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010930
Chris Lattnerf78616b2004-01-14 06:06:08 +000010931 // If the callsite is an invoke instruction, and the return value is used by
10932 // a PHI node in a successor, we cannot change the return type of the call
10933 // because there is no place to put the cast instruction (without breaking
10934 // the critical edge). Bail out in this case.
10935 if (!Caller->use_empty())
10936 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10937 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10938 UI != E; ++UI)
10939 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10940 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010941 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010942 return false;
10943 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010944
10945 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10946 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010947
Chris Lattner9fe38862003-06-19 17:00:31 +000010948 CallSite::arg_iterator AI = CS.arg_begin();
10949 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10950 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010951 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010952
10953 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010954 return false; // Cannot transform this parameter value.
10955
Devang Patel19c87462008-09-26 22:53:05 +000010956 if (CallerPAL.getParamAttributes(i + 1)
10957 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010958 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010959
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010960 // Converting from one pointer type to another or between a pointer and an
10961 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010962 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010963 (TD && ((isa<PointerType>(ParamTy) ||
10964 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10965 (isa<PointerType>(ActTy) ||
10966 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010967 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010968 }
10969
10970 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010971 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010972 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010973
Chris Lattner58d74912008-03-12 17:45:29 +000010974 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10975 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010976 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010977 // won't be dropping them. Check that these extra arguments have attributes
10978 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010979 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10980 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010981 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010982 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010983 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010984 return false;
10985 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010986
Chris Lattner9fe38862003-06-19 17:00:31 +000010987 // Okay, we decided that this is a safe thing to do: go ahead and start
10988 // inserting cast instructions as necessary...
10989 std::vector<Value*> Args;
10990 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010991 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010992 attrVec.reserve(NumCommonArgs);
10993
10994 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010995 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010996
10997 // If the return value is not being used, the type may not be compatible
10998 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010999 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000011000
11001 // Add the new return attributes.
11002 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000011003 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000011004
11005 AI = CS.arg_begin();
11006 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
11007 const Type *ParamTy = FT->getParamType(i);
11008 if ((*AI)->getType() == ParamTy) {
11009 Args.push_back(*AI);
11010 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000011011 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000011012 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011013 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000011014 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000011015
11016 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000011017 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000011018 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000011019 }
11020
11021 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011022 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000011023 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000011024 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000011025
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011026 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011027 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000011028 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000011029 errs() << "WARNING: While resolving call to function '"
11030 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000011031 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011032 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000011033 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
11034 const Type *PTy = getPromotedType((*AI)->getType());
11035 if (PTy != (*AI)->getType()) {
11036 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011037 Instruction::CastOps opcode =
11038 CastInst::getCastOpcode(*AI, false, PTy, false);
11039 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000011040 } else {
11041 Args.push_back(*AI);
11042 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000011043
Duncan Sandse1e520f2008-01-13 08:02:44 +000011044 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000011045 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000011046 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000011047 }
Chris Lattner9fe38862003-06-19 17:00:31 +000011048 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011049 }
Chris Lattner9fe38862003-06-19 17:00:31 +000011050
Devang Patel19c87462008-09-26 22:53:05 +000011051 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
11052 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
11053
Devang Patel9674d152009-10-14 17:29:00 +000011054 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000011055 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000011056
Eric Christophera66297a2009-07-25 02:45:27 +000011057 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
11058 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000011059
Chris Lattner9fe38862003-06-19 17:00:31 +000011060 Instruction *NC;
11061 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011062 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011063 Args.begin(), Args.end(),
11064 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000011065 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000011066 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000011067 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000011068 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
11069 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000011070 CallInst *CI = cast<CallInst>(Caller);
11071 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000011072 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000011073 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000011074 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000011075 }
11076
Chris Lattner6934a042007-02-11 01:23:03 +000011077 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000011078 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000011079 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000011080 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011081 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000011082 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011083 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000011084
11085 // If this is an invoke instruction, we should insert it after the first
11086 // non-phi, instruction in the normal successor block.
11087 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000011088 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000011089 InsertNewInstBefore(NC, *I);
11090 } else {
11091 // Otherwise, it's a call, just insert cast right after the call instr
11092 InsertNewInstBefore(NC, *Caller);
11093 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000011094 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000011095 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011096 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000011097 }
11098 }
11099
Devang Patel1bf5ebc2009-10-13 21:41:20 +000011100
Chris Lattner931f8f32009-08-31 05:17:58 +000011101 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000011102 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000011103
11104 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000011105 return true;
11106}
11107
Duncan Sandscdb6d922007-09-17 10:26:40 +000011108// transformCallThroughTrampoline - Turn a call to a function created by the
11109// init_trampoline intrinsic into a direct call to the underlying function.
11110//
11111Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
11112 Value *Callee = CS.getCalledValue();
11113 const PointerType *PTy = cast<PointerType>(Callee->getType());
11114 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000011115 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011116
11117 // If the call already has the 'nest' attribute somewhere then give up -
11118 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000011119 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011120 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000011121
11122 IntrinsicInst *Tramp =
11123 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
11124
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000011125 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000011126 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
11127 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
11128
Devang Patel05988662008-09-25 21:00:45 +000011129 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000011130 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000011131 unsigned NestIdx = 1;
11132 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000011133 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000011134
11135 // Look for a parameter marked with the 'nest' attribute.
11136 for (FunctionType::param_iterator I = NestFTy->param_begin(),
11137 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000011138 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000011139 // Record the parameter type and any other attributes.
11140 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000011141 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011142 break;
11143 }
11144
11145 if (NestTy) {
11146 Instruction *Caller = CS.getInstruction();
11147 std::vector<Value*> NewArgs;
11148 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
11149
Devang Patel05988662008-09-25 21:00:45 +000011150 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000011151 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011152
Duncan Sandscdb6d922007-09-17 10:26:40 +000011153 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011154 // mean appending it. Likewise for attributes.
11155
Devang Patel19c87462008-09-26 22:53:05 +000011156 // Add any result attributes.
11157 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000011158 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011159
Duncan Sandscdb6d922007-09-17 10:26:40 +000011160 {
11161 unsigned Idx = 1;
11162 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
11163 do {
11164 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011165 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011166 Value *NestVal = Tramp->getOperand(3);
11167 if (NestVal->getType() != NestTy)
11168 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
11169 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000011170 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000011171 }
11172
11173 if (I == E)
11174 break;
11175
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011176 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011177 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000011178 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011179 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000011180 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000011181
11182 ++Idx, ++I;
11183 } while (1);
11184 }
11185
Devang Patel19c87462008-09-26 22:53:05 +000011186 // Add any function attributes.
11187 if (Attributes Attr = Attrs.getFnAttributes())
11188 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
11189
Duncan Sandscdb6d922007-09-17 10:26:40 +000011190 // The trampoline may have been bitcast to a bogus type (FTy).
11191 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011192 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011193
Duncan Sandscdb6d922007-09-17 10:26:40 +000011194 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000011195 NewTypes.reserve(FTy->getNumParams()+1);
11196
Duncan Sandscdb6d922007-09-17 10:26:40 +000011197 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011198 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011199 {
11200 unsigned Idx = 1;
11201 FunctionType::param_iterator I = FTy->param_begin(),
11202 E = FTy->param_end();
11203
11204 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011205 if (Idx == NestIdx)
11206 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011207 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011208
11209 if (I == E)
11210 break;
11211
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011212 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011213 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011214
11215 ++Idx, ++I;
11216 } while (1);
11217 }
11218
11219 // Replace the trampoline call with a direct call. Let the generic
11220 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000011221 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000011222 FTy->isVarArg());
11223 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000011224 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000011225 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000011226 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000011227 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
11228 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000011229
11230 Instruction *NewCaller;
11231 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011232 NewCaller = InvokeInst::Create(NewCallee,
11233 II->getNormalDest(), II->getUnwindDest(),
11234 NewArgs.begin(), NewArgs.end(),
11235 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011236 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000011237 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011238 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000011239 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
11240 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011241 if (cast<CallInst>(Caller)->isTailCall())
11242 cast<CallInst>(NewCaller)->setTailCall();
11243 cast<CallInst>(NewCaller)->
11244 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000011245 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011246 }
Devang Patel9674d152009-10-14 17:29:00 +000011247 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000011248 Caller->replaceAllUsesWith(NewCaller);
11249 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000011250 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011251 return 0;
11252 }
11253 }
11254
11255 // Replace the trampoline call with a direct call. Since there is no 'nest'
11256 // parameter, there is no need to adjust the argument list. Let the generic
11257 // code sort out any function type mismatches.
11258 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000011259 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000011260 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011261 CS.setCalledFunction(NewCallee);
11262 return CS.getInstruction();
11263}
11264
Dan Gohman9ad29202009-09-16 16:50:24 +000011265/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
11266/// and if a/b/c and the add's all have a single use, turn this into a phi
Chris Lattner7da52b22006-11-01 04:51:18 +000011267/// and a single binop.
11268Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
11269 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011270 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000011271 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011272 Value *LHSVal = FirstInst->getOperand(0);
11273 Value *RHSVal = FirstInst->getOperand(1);
11274
11275 const Type *LHSType = LHSVal->getType();
11276 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000011277
Dan Gohman9ad29202009-09-16 16:50:24 +000011278 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000011279 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000011280 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000011281 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000011282 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000011283 // types or GEP's with different index types.
11284 I->getOperand(0)->getType() != LHSType ||
11285 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000011286 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011287
11288 // If they are CmpInst instructions, check their predicates
11289 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
11290 if (cast<CmpInst>(I)->getPredicate() !=
11291 cast<CmpInst>(FirstInst)->getPredicate())
11292 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011293
11294 // Keep track of which operand needs a phi node.
11295 if (I->getOperand(0) != LHSVal) LHSVal = 0;
11296 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000011297 }
Dan Gohman9ad29202009-09-16 16:50:24 +000011298
11299 // If both LHS and RHS would need a PHI, don't do this transformation,
11300 // because it would increase the number of PHIs entering the block,
11301 // which leads to higher register pressure. This is especially
11302 // bad when the PHIs are in the header of a loop.
11303 if (!LHSVal && !RHSVal)
11304 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000011305
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011306 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000011307
Chris Lattner7da52b22006-11-01 04:51:18 +000011308 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000011309 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000011310 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011311 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011312 NewLHS = PHINode::Create(LHSType,
11313 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011314 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
11315 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000011316 InsertNewInstBefore(NewLHS, PN);
11317 LHSVal = NewLHS;
11318 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011319
11320 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011321 NewRHS = PHINode::Create(RHSType,
11322 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011323 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
11324 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000011325 InsertNewInstBefore(NewRHS, PN);
11326 RHSVal = NewRHS;
11327 }
11328
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011329 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000011330 if (NewLHS || NewRHS) {
11331 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11332 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
11333 if (NewLHS) {
11334 Value *NewInLHS = InInst->getOperand(0);
11335 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
11336 }
11337 if (NewRHS) {
11338 Value *NewInRHS = InInst->getOperand(1);
11339 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
11340 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011341 }
11342 }
11343
Chris Lattner7da52b22006-11-01 04:51:18 +000011344 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011345 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011346 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000011347 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000011348 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000011349}
11350
Chris Lattner05f18922008-12-01 02:34:36 +000011351Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
11352 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
11353
11354 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
11355 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000011356 // This is true if all GEP bases are allocas and if all indices into them are
11357 // constants.
11358 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011359
11360 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000011361 // more than one phi, which leads to higher register pressure. This is
11362 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011363 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000011364
Dan Gohman9ad29202009-09-16 16:50:24 +000011365 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000011366 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11367 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
11368 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
11369 GEP->getNumOperands() != FirstInst->getNumOperands())
11370 return 0;
11371
Chris Lattner36d3e322009-02-21 00:46:50 +000011372 // Keep track of whether or not all GEPs are of alloca pointers.
11373 if (AllBasePointersAreAllocas &&
11374 (!isa<AllocaInst>(GEP->getOperand(0)) ||
11375 !GEP->hasAllConstantIndices()))
11376 AllBasePointersAreAllocas = false;
11377
Chris Lattner05f18922008-12-01 02:34:36 +000011378 // Compare the operand lists.
11379 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
11380 if (FirstInst->getOperand(op) == GEP->getOperand(op))
11381 continue;
11382
11383 // Don't merge two GEPs when two operands differ (introducing phi nodes)
11384 // if one of the PHIs has a constant for the index. The index may be
11385 // substantially cheaper to compute for the constants, so making it a
11386 // variable index could pessimize the path. This also handles the case
11387 // for struct indices, which must always be constant.
11388 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
11389 isa<ConstantInt>(GEP->getOperand(op)))
11390 return 0;
11391
11392 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
11393 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011394
11395 // If we already needed a PHI for an earlier operand, and another operand
11396 // also requires a PHI, we'd be introducing more PHIs than we're
11397 // eliminating, which increases register pressure on entry to the PHI's
11398 // block.
11399 if (NeededPhi)
11400 return 0;
11401
Chris Lattner05f18922008-12-01 02:34:36 +000011402 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011403 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000011404 }
11405 }
11406
Chris Lattner36d3e322009-02-21 00:46:50 +000011407 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000011408 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000011409 // offset calculation, but all the predecessors will have to materialize the
11410 // stack address into a register anyway. We'd actually rather *clone* the
11411 // load up into the predecessors so that we have a load of a gep of an alloca,
11412 // which can usually all be folded into the load.
11413 if (AllBasePointersAreAllocas)
11414 return 0;
11415
Chris Lattner05f18922008-12-01 02:34:36 +000011416 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
11417 // that is variable.
11418 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
11419
11420 bool HasAnyPHIs = false;
11421 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
11422 if (FixedOperands[i]) continue; // operand doesn't need a phi.
11423 Value *FirstOp = FirstInst->getOperand(i);
11424 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
11425 FirstOp->getName()+".pn");
11426 InsertNewInstBefore(NewPN, PN);
11427
11428 NewPN->reserveOperandSpace(e);
11429 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
11430 OperandPhis[i] = NewPN;
11431 FixedOperands[i] = NewPN;
11432 HasAnyPHIs = true;
11433 }
11434
11435
11436 // Add all operands to the new PHIs.
11437 if (HasAnyPHIs) {
11438 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11439 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
11440 BasicBlock *InBB = PN.getIncomingBlock(i);
11441
11442 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
11443 if (PHINode *OpPhi = OperandPhis[op])
11444 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
11445 }
11446 }
11447
11448 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011449 return cast<GEPOperator>(FirstInst)->isInBounds() ?
11450 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
11451 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011452 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
11453 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000011454}
11455
11456
Chris Lattner21550882009-02-23 05:56:17 +000011457/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
11458/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000011459/// obvious the value of the load is not changed from the point of the load to
11460/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011461///
11462/// Finally, it is safe, but not profitable, to sink a load targetting a
11463/// non-address-taken alloca. Doing so will cause us to not promote the alloca
11464/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000011465static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000011466 BasicBlock::iterator BBI = L, E = L->getParent()->end();
11467
11468 for (++BBI; BBI != E; ++BBI)
11469 if (BBI->mayWriteToMemory())
11470 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011471
11472 // Check for non-address taken alloca. If not address-taken already, it isn't
11473 // profitable to do this xform.
11474 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11475 bool isAddressTaken = false;
11476 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11477 UI != E; ++UI) {
11478 if (isa<LoadInst>(UI)) continue;
11479 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11480 // If storing TO the alloca, then the address isn't taken.
11481 if (SI->getOperand(1) == AI) continue;
11482 }
11483 isAddressTaken = true;
11484 break;
11485 }
11486
Chris Lattner36d3e322009-02-21 00:46:50 +000011487 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011488 return false;
11489 }
11490
Chris Lattner36d3e322009-02-21 00:46:50 +000011491 // If this load is a load from a GEP with a constant offset from an alloca,
11492 // then we don't want to sink it. In its present form, it will be
11493 // load [constant stack offset]. Sinking it will cause us to have to
11494 // materialize the stack addresses in each predecessor in a register only to
11495 // do a shared load from register in the successor.
11496 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11497 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11498 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11499 return false;
11500
Chris Lattner76c73142006-11-01 07:13:54 +000011501 return true;
11502}
11503
Chris Lattner751a3622009-11-01 20:04:24 +000011504Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11505 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11506
11507 // When processing loads, we need to propagate two bits of information to the
11508 // sunk load: whether it is volatile, and what its alignment is. We currently
11509 // don't sink loads when some have their alignment specified and some don't.
11510 // visitLoadInst will propagate an alignment onto the load when TD is around,
11511 // and if TD isn't around, we can't handle the mixed case.
11512 bool isVolatile = FirstLI->isVolatile();
11513 unsigned LoadAlignment = FirstLI->getAlignment();
11514
11515 // We can't sink the load if the loaded value could be modified between the
11516 // load and the PHI.
11517 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11518 !isSafeAndProfitableToSinkLoad(FirstLI))
11519 return 0;
11520
11521 // If the PHI is of volatile loads and the load block has multiple
11522 // successors, sinking it would remove a load of the volatile value from
11523 // the path through the other successor.
11524 if (isVolatile &&
11525 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11526 return 0;
11527
11528 // Check to see if all arguments are the same operation.
11529 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11530 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11531 if (!LI || !LI->hasOneUse())
11532 return 0;
11533
11534 // We can't sink the load if the loaded value could be modified between
11535 // the load and the PHI.
11536 if (LI->isVolatile() != isVolatile ||
11537 LI->getParent() != PN.getIncomingBlock(i) ||
11538 !isSafeAndProfitableToSinkLoad(LI))
11539 return 0;
11540
11541 // If some of the loads have an alignment specified but not all of them,
11542 // we can't do the transformation.
11543 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11544 return 0;
11545
Chris Lattnera664bb72009-11-01 20:07:07 +000011546 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000011547
11548 // If the PHI is of volatile loads and the load block has multiple
11549 // successors, sinking it would remove a load of the volatile value from
11550 // the path through the other successor.
11551 if (isVolatile &&
11552 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11553 return 0;
11554 }
11555
11556 // Okay, they are all the same operation. Create a new PHI node of the
11557 // correct type, and PHI together all of the LHS's of the instructions.
11558 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11559 PN.getName()+".in");
11560 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11561
11562 Value *InVal = FirstLI->getOperand(0);
11563 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11564
11565 // Add all operands to the new PHI.
11566 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11567 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11568 if (NewInVal != InVal)
11569 InVal = 0;
11570 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11571 }
11572
11573 Value *PhiVal;
11574 if (InVal) {
11575 // The new PHI unions all of the same values together. This is really
11576 // common, so we handle it intelligently here for compile-time speed.
11577 PhiVal = InVal;
11578 delete NewPN;
11579 } else {
11580 InsertNewInstBefore(NewPN, PN);
11581 PhiVal = NewPN;
11582 }
11583
11584 // If this was a volatile load that we are merging, make sure to loop through
11585 // and mark all the input loads as non-volatile. If we don't do this, we will
11586 // insert a new volatile load and the old ones will not be deletable.
11587 if (isVolatile)
11588 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11589 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11590
11591 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11592}
11593
Chris Lattner9fe38862003-06-19 17:00:31 +000011594
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011595
11596/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11597/// operator and they all are only used by the PHI, PHI together their
11598/// inputs, and do the operation once, to the result of the PHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011599Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11600 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11601
Chris Lattner751a3622009-11-01 20:04:24 +000011602 if (isa<GetElementPtrInst>(FirstInst))
11603 return FoldPHIArgGEPIntoPHI(PN);
11604 if (isa<LoadInst>(FirstInst))
11605 return FoldPHIArgLoadIntoPHI(PN);
11606
Chris Lattnerbac32862004-11-14 19:13:23 +000011607 // Scan the instruction, looking for input operations that can be folded away.
11608 // If all input operands to the phi are the same instruction (e.g. a cast from
11609 // the same type or "+42") we can pull the operation through the PHI, reducing
11610 // code size and simplifying code.
11611 Constant *ConstantOp = 0;
11612 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000011613
Chris Lattnerbac32862004-11-14 19:13:23 +000011614 if (isa<CastInst>(FirstInst)) {
11615 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000011616
11617 // Be careful about transforming integer PHIs. We don't want to pessimize
11618 // the code by turning an i32 into an i1293.
11619 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011620 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattnerbf382b52009-11-08 21:20:06 +000011621 return 0;
11622 }
Reid Spencer832254e2007-02-02 02:16:23 +000011623 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000011624 // Can fold binop, compare or shift here if the RHS is a constant,
11625 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011626 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000011627 if (ConstantOp == 0)
11628 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000011629 } else {
11630 return 0; // Cannot fold this operation.
11631 }
11632
11633 // Check to see if all arguments are the same operation.
11634 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000011635 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11636 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000011637 return 0;
11638 if (CastSrcTy) {
11639 if (I->getOperand(0)->getType() != CastSrcTy)
11640 return 0; // Cast operation must match.
11641 } else if (I->getOperand(1) != ConstantOp) {
11642 return 0;
11643 }
11644 }
11645
11646 // Okay, they are all the same operation. Create a new PHI node of the
11647 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000011648 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11649 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000011650 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000011651
11652 Value *InVal = FirstInst->getOperand(0);
11653 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000011654
11655 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000011656 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11657 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11658 if (NewInVal != InVal)
11659 InVal = 0;
11660 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11661 }
11662
11663 Value *PhiVal;
11664 if (InVal) {
11665 // The new PHI unions all of the same values together. This is really
11666 // common, so we handle it intelligently here for compile-time speed.
11667 PhiVal = InVal;
11668 delete NewPN;
11669 } else {
11670 InsertNewInstBefore(NewPN, PN);
11671 PhiVal = NewPN;
11672 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011673
Chris Lattnerbac32862004-11-14 19:13:23 +000011674 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000011675 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011676 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000011677
Chris Lattner54545ac2008-04-29 17:13:43 +000011678 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011679 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000011680
Chris Lattner751a3622009-11-01 20:04:24 +000011681 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11682 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11683 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000011684}
Chris Lattnera1be5662002-05-02 17:06:02 +000011685
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011686/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11687/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011688static bool DeadPHICycle(PHINode *PN,
11689 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011690 if (PN->use_empty()) return true;
11691 if (!PN->hasOneUse()) return false;
11692
11693 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011694 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011695 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000011696
11697 // Don't scan crazily complex things.
11698 if (PotentiallyDeadPHIs.size() == 16)
11699 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011700
11701 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11702 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000011703
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011704 return false;
11705}
11706
Chris Lattnercf5008a2007-11-06 21:52:06 +000011707/// PHIsEqualValue - Return true if this phi node is always equal to
11708/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11709/// z = some value; x = phi (y, z); y = phi (x, z)
11710static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11711 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11712 // See if we already saw this PHI node.
11713 if (!ValueEqualPHIs.insert(PN))
11714 return true;
11715
11716 // Don't scan crazily complex things.
11717 if (ValueEqualPHIs.size() == 16)
11718 return false;
11719
11720 // Scan the operands to see if they are either phi nodes or are equal to
11721 // the value.
11722 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11723 Value *Op = PN->getIncomingValue(i);
11724 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11725 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11726 return false;
11727 } else if (Op != NonPhiInVal)
11728 return false;
11729 }
11730
11731 return true;
11732}
11733
11734
Chris Lattner9956c052009-11-08 19:23:30 +000011735namespace {
11736struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011737 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000011738 unsigned Shift; // The amount shifted.
11739 Instruction *Inst; // The trunc instruction.
11740
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011741 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11742 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000011743
11744 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011745 if (PHIId < RHS.PHIId) return true;
11746 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000011747 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011748 if (Shift > RHS.Shift) return false;
11749 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000011750 RHS.Inst->getType()->getPrimitiveSizeInBits();
11751 }
11752};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011753
11754struct LoweredPHIRecord {
11755 PHINode *PN; // The PHI that was lowered.
11756 unsigned Shift; // The amount shifted.
11757 unsigned Width; // The width extracted.
11758
11759 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11760 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11761
11762 // Ctor form used by DenseMap.
11763 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11764 : PN(pn), Shift(Sh), Width(0) {}
11765};
11766}
11767
11768namespace llvm {
11769 template<>
11770 struct DenseMapInfo<LoweredPHIRecord> {
11771 static inline LoweredPHIRecord getEmptyKey() {
11772 return LoweredPHIRecord(0, 0);
11773 }
11774 static inline LoweredPHIRecord getTombstoneKey() {
11775 return LoweredPHIRecord(0, 1);
11776 }
11777 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11778 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11779 (Val.Width>>3);
11780 }
11781 static bool isEqual(const LoweredPHIRecord &LHS,
11782 const LoweredPHIRecord &RHS) {
11783 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11784 LHS.Width == RHS.Width;
11785 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011786 };
Chris Lattner4bbf4ee2009-12-15 07:26:43 +000011787 template <>
11788 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner9956c052009-11-08 19:23:30 +000011789}
11790
11791
11792/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11793/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11794/// so, we split the PHI into the various pieces being extracted. This sort of
11795/// thing is introduced when SROA promotes an aggregate to large integer values.
11796///
11797/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11798/// inttoptr. We should produce new PHIs in the right type.
11799///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011800Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11801 // PHIUsers - Keep track of all of the truncated values extracted from a set
11802 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000011803 SmallVector<PHIUsageRecord, 16> PHIUsers;
11804
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011805 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11806 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11807 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11808 // check the uses of (to ensure they are all extracts).
11809 SmallVector<PHINode*, 8> PHIsToSlice;
11810 SmallPtrSet<PHINode*, 8> PHIsInspected;
11811
11812 PHIsToSlice.push_back(&FirstPhi);
11813 PHIsInspected.insert(&FirstPhi);
11814
11815 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11816 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011817
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011818 // Scan the input list of the PHI. If any input is an invoke, and if the
11819 // input is defined in the predecessor, then we won't be split the critical
11820 // edge which is required to insert a truncate. Because of this, we have to
11821 // bail out.
11822 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11823 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11824 if (II == 0) continue;
11825 if (II->getParent() != PN->getIncomingBlock(i))
11826 continue;
11827
11828 // If we have a phi, and if it's directly in the predecessor, then we have
11829 // a critical edge where we need to put the truncate. Since we can't
11830 // split the edge in instcombine, we have to bail out.
11831 return 0;
11832 }
11833
11834
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011835 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11836 UI != E; ++UI) {
11837 Instruction *User = cast<Instruction>(*UI);
11838
11839 // If the user is a PHI, inspect its uses recursively.
11840 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11841 if (PHIsInspected.insert(UserPN))
11842 PHIsToSlice.push_back(UserPN);
11843 continue;
11844 }
11845
11846 // Truncates are always ok.
11847 if (isa<TruncInst>(User)) {
11848 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11849 continue;
11850 }
11851
11852 // Otherwise it must be a lshr which can only be used by one trunc.
11853 if (User->getOpcode() != Instruction::LShr ||
11854 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11855 !isa<ConstantInt>(User->getOperand(1)))
11856 return 0;
11857
11858 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11859 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000011860 }
Chris Lattner9956c052009-11-08 19:23:30 +000011861 }
11862
11863 // If we have no users, they must be all self uses, just nuke the PHI.
11864 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011865 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000011866
11867 // If this phi node is transformable, create new PHIs for all the pieces
11868 // extracted out of it. First, sort the users by their offset and size.
11869 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11870
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011871 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11872 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11873 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11874 );
Chris Lattner9956c052009-11-08 19:23:30 +000011875
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011876 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11877 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000011878 DenseMap<BasicBlock*, Value*> PredValues;
11879
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011880 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11881 // introduce redundant PHIs.
11882 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11883
11884 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11885 unsigned PHIId = PHIUsers[UserI].PHIId;
11886 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011887 unsigned Offset = PHIUsers[UserI].Shift;
11888 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000011889
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011890 PHINode *EltPHI;
11891
11892 // If we've already lowered a user like this, reuse the previously lowered
11893 // value.
11894 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000011895
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011896 // Otherwise, Create the new PHI node for this user.
11897 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11898 assert(EltPHI->getType() != PN->getType() &&
11899 "Truncate didn't shrink phi?");
11900
11901 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11902 BasicBlock *Pred = PN->getIncomingBlock(i);
11903 Value *&PredVal = PredValues[Pred];
11904
11905 // If we already have a value for this predecessor, reuse it.
11906 if (PredVal) {
11907 EltPHI->addIncoming(PredVal, Pred);
11908 continue;
11909 }
Chris Lattner9956c052009-11-08 19:23:30 +000011910
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011911 // Handle the PHI self-reuse case.
11912 Value *InVal = PN->getIncomingValue(i);
11913 if (InVal == PN) {
11914 PredVal = EltPHI;
11915 EltPHI->addIncoming(PredVal, Pred);
11916 continue;
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011917 }
11918
11919 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011920 // If the incoming value was a PHI, and if it was one of the PHIs we
11921 // already rewrote it, just use the lowered value.
11922 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11923 PredVal = Res;
11924 EltPHI->addIncoming(PredVal, Pred);
11925 continue;
11926 }
11927 }
11928
11929 // Otherwise, do an extract in the predecessor.
11930 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11931 Value *Res = InVal;
11932 if (Offset)
11933 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11934 Offset), "extract");
11935 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11936 PredVal = Res;
11937 EltPHI->addIncoming(Res, Pred);
11938
11939 // If the incoming value was a PHI, and if it was one of the PHIs we are
11940 // rewriting, we will ultimately delete the code we inserted. This
11941 // means we need to revisit that PHI to make sure we extract out the
11942 // needed piece.
11943 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11944 if (PHIsInspected.count(OldInVal)) {
11945 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11946 OldInVal)-PHIsToSlice.begin();
11947 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11948 cast<Instruction>(Res)));
11949 ++UserE;
11950 }
Chris Lattner9956c052009-11-08 19:23:30 +000011951 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011952 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000011953
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011954 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11955 << *EltPHI << '\n');
11956 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000011957 }
Chris Lattner9956c052009-11-08 19:23:30 +000011958
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011959 // Replace the use of this piece with the PHI node.
11960 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000011961 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011962
11963 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11964 // with undefs.
11965 Value *Undef = UndefValue::get(FirstPhi.getType());
11966 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11967 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11968 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000011969}
11970
Chris Lattner473945d2002-05-06 18:06:38 +000011971// PHINode simplification
11972//
Chris Lattner7e708292002-06-25 16:13:24 +000011973Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011974 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011975 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011976
Owen Anderson7e057142006-07-10 22:03:18 +000011977 if (Value *V = PN.hasConstantValue())
11978 return ReplaceInstUsesWith(PN, V);
11979
Owen Anderson7e057142006-07-10 22:03:18 +000011980 // If all PHI operands are the same operation, pull them through the PHI,
11981 // reducing code size.
11982 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011983 isa<Instruction>(PN.getIncomingValue(1)) &&
11984 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11985 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11986 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11987 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011988 PN.getIncomingValue(0)->hasOneUse())
11989 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11990 return Result;
11991
11992 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11993 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11994 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011995 if (PN.hasOneUse()) {
11996 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11997 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011998 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011999 PotentiallyDeadPHIs.insert(&PN);
12000 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012001 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000012002 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000012003
12004 // If this phi has a single use, and if that use just computes a value for
12005 // the next iteration of a loop, delete the phi. This occurs with unused
12006 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
12007 // common case here is good because the only other things that catch this
12008 // are induction variable analysis (sometimes) and ADCE, which is only run
12009 // late.
12010 if (PHIUser->hasOneUse() &&
12011 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
12012 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012013 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000012014 }
12015 }
Owen Anderson7e057142006-07-10 22:03:18 +000012016
Chris Lattnercf5008a2007-11-06 21:52:06 +000012017 // We sometimes end up with phi cycles that non-obviously end up being the
12018 // same value, for example:
12019 // z = some value; x = phi (y, z); y = phi (x, z)
12020 // where the phi nodes don't necessarily need to be in the same block. Do a
12021 // quick check to see if the PHI node only contains a single non-phi value, if
12022 // so, scan to see if the phi cycle is actually equal to that value.
12023 {
12024 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
12025 // Scan for the first non-phi operand.
12026 while (InValNo != NumOperandVals &&
12027 isa<PHINode>(PN.getIncomingValue(InValNo)))
12028 ++InValNo;
12029
12030 if (InValNo != NumOperandVals) {
12031 Value *NonPhiInVal = PN.getOperand(InValNo);
12032
12033 // Scan the rest of the operands to see if there are any conflicts, if so
12034 // there is no need to recursively scan other phis.
12035 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
12036 Value *OpVal = PN.getIncomingValue(InValNo);
12037 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
12038 break;
12039 }
12040
12041 // If we scanned over all operands, then we have one unique value plus
12042 // phi values. Scan PHI nodes to see if they all merge in each other or
12043 // the value.
12044 if (InValNo == NumOperandVals) {
12045 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
12046 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
12047 return ReplaceInstUsesWith(PN, NonPhiInVal);
12048 }
12049 }
12050 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000012051
Dan Gohman5b097012009-10-31 14:22:52 +000012052 // If there are multiple PHIs, sort their operands so that they all list
12053 // the blocks in the same order. This will help identical PHIs be eliminated
12054 // by other passes. Other passes shouldn't depend on this for correctness
12055 // however.
12056 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
12057 if (&PN != FirstPN)
12058 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000012059 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000012060 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
12061 if (BBA != BBB) {
12062 Value *VA = PN.getIncomingValue(i);
12063 unsigned j = PN.getBasicBlockIndex(BBB);
12064 Value *VB = PN.getIncomingValue(j);
12065 PN.setIncomingBlock(i, BBB);
12066 PN.setIncomingValue(i, VB);
12067 PN.setIncomingBlock(j, BBA);
12068 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000012069 // NOTE: Instcombine normally would want us to "return &PN" if we
12070 // modified any of the operands of an instruction. However, since we
12071 // aren't adding or removing uses (just rearranging them) we don't do
12072 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000012073 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000012074 }
12075
Chris Lattner9956c052009-11-08 19:23:30 +000012076 // If this is an integer PHI and we know that it has an illegal type, see if
12077 // it is only used by trunc or trunc(lshr) operations. If so, we split the
12078 // PHI into the various pieces being extracted. This sort of thing is
12079 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000012080 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000012081 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
12082 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
12083 return Res;
12084
Chris Lattner60921c92003-12-19 05:58:40 +000012085 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000012086}
12087
Chris Lattner7e708292002-06-25 16:13:24 +000012088Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +000012089 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
12090
12091 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
12092 return ReplaceInstUsesWith(GEP, V);
12093
Chris Lattner620ce142004-05-07 22:09:22 +000012094 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000012095
Chris Lattnere87597f2004-10-16 18:11:37 +000012096 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012097 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000012098
Chris Lattner28977af2004-04-05 01:30:19 +000012099 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000012100 if (TD) {
12101 bool MadeChange = false;
12102 unsigned PtrSize = TD->getPointerSizeInBits();
12103
12104 gep_type_iterator GTI = gep_type_begin(GEP);
12105 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
12106 I != E; ++I, ++GTI) {
12107 if (!isa<SequentialType>(*GTI)) continue;
12108
Chris Lattnercb69a4e2004-04-07 18:38:20 +000012109 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000012110 // to what we need. If narrower, sign-extend it to what we need. This
12111 // explicit cast can make subsequent optimizations more obvious.
12112 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000012113 if (OpBits == PtrSize)
12114 continue;
12115
Chris Lattner2345d1d2009-08-30 20:01:10 +000012116 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000012117 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000012118 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000012119 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000012120 }
Chris Lattner28977af2004-04-05 01:30:19 +000012121
Chris Lattner90ac28c2002-08-02 19:29:35 +000012122 // Combine Indices - If the source pointer to this getelementptr instruction
12123 // is a getelementptr instruction, combine the indices of the two
12124 // getelementptr instructions into a single instruction.
12125 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012126 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000012127 // Note that if our source is a gep chain itself that we wait for that
12128 // chain to be resolved before we perform this transformation. This
12129 // avoids us creating a TON of code in some cases.
12130 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012131 if (GetElementPtrInst *SrcGEP =
12132 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
12133 if (SrcGEP->getNumOperands() == 2)
12134 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000012135
Chris Lattner72588fc2007-02-15 22:48:32 +000012136 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000012137
12138 // Find out whether the last index in the source GEP is a sequential idx.
12139 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000012140 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
12141 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000012142 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012143
Chris Lattner90ac28c2002-08-02 19:29:35 +000012144 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000012145 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000012146 // Replace: gep (gep %P, long B), long A, ...
12147 // With: T = long A+B; gep %P, T, ...
12148 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012149 Value *Sum;
12150 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
12151 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000012152 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000012153 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000012154 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000012155 Sum = SO1;
12156 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000012157 // If they aren't the same type, then the input hasn't been processed
12158 // by the loop above yet (which canonicalizes sequential index types to
12159 // intptr_t). Just avoid transforming this until the input has been
12160 // normalized.
12161 if (SO1->getType() != GO1->getType())
12162 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012163 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000012164 }
Chris Lattner620ce142004-05-07 22:09:22 +000012165
Chris Lattnerab984842009-08-30 05:30:55 +000012166 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012167 if (Src->getNumOperands() == 2) {
12168 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000012169 GEP.setOperand(1, Sum);
12170 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000012171 }
Chris Lattnerab984842009-08-30 05:30:55 +000012172 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000012173 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000012174 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000012175 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000012176 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012177 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000012178 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000012179 Indices.append(Src->op_begin()+1, Src->op_end());
12180 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000012181 }
12182
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012183 if (!Indices.empty())
12184 return (cast<GEPOperator>(&GEP)->isInBounds() &&
12185 Src->isInBounds()) ?
12186 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
12187 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012188 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000012189 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000012190 }
12191
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012192 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
12193 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000012194 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000012195
Chris Lattner2de23192009-08-30 20:38:21 +000012196 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
12197 // want to change the gep until the bitcasts are eliminated.
12198 if (getBitCastOperand(X)) {
12199 Worklist.AddValue(PtrOp);
12200 return 0;
12201 }
12202
Chris Lattnerc514c1f2009-11-27 00:29:05 +000012203 bool HasZeroPointerIndex = false;
12204 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
12205 HasZeroPointerIndex = C->isZero();
12206
Chris Lattner963f4ba2009-08-30 20:36:46 +000012207 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
12208 // into : GEP [10 x i8]* X, i32 0, ...
12209 //
12210 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
12211 // into : GEP i8* X, ...
12212 //
12213 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000012214 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000012215 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
12216 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012217 if (const ArrayType *CATy =
12218 dyn_cast<ArrayType>(CPTy->getElementType())) {
12219 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
12220 if (CATy->getElementType() == XTy->getElementType()) {
12221 // -> GEP i8* X, ...
12222 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012223 return cast<GEPOperator>(&GEP)->isInBounds() ?
12224 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
12225 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012226 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
12227 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000012228 }
12229
12230 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012231 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000012232 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012233 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000012234 // At this point, we know that the cast source type is a pointer
12235 // to an array of the same type as the destination pointer
12236 // array. Because the array type is never stepped over (there
12237 // is a leading zero) we can fold the cast into this GEP.
12238 GEP.setOperand(0, X);
12239 return &GEP;
12240 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012241 }
12242 }
Chris Lattnereed48272005-09-13 00:40:14 +000012243 } else if (GEP.getNumOperands() == 2) {
12244 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012245 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
12246 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000012247 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
12248 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012249 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000012250 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
12251 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000012252 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000012253 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000012254 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012255 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12256 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012257 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000012258 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012259 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000012260 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000012261
12262 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012263 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000012264 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012265 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000012266
Owen Anderson1d0be152009-08-13 21:58:54 +000012267 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000012268 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000012269 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000012270
12271 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
12272 // allow either a mul, shift, or constant here.
12273 Value *NewIdx = 0;
12274 ConstantInt *Scale = 0;
12275 if (ArrayEltSize == 1) {
12276 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000012277 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012278 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012279 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012280 Scale = CI;
12281 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
12282 if (Inst->getOpcode() == Instruction::Shl &&
12283 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000012284 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
12285 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000012286 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000012287 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012288 NewIdx = Inst->getOperand(0);
12289 } else if (Inst->getOpcode() == Instruction::Mul &&
12290 isa<ConstantInt>(Inst->getOperand(1))) {
12291 Scale = cast<ConstantInt>(Inst->getOperand(1));
12292 NewIdx = Inst->getOperand(0);
12293 }
12294 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012295
Chris Lattner7835cdd2005-09-13 18:36:04 +000012296 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012297 // out, perform the transformation. Note, we don't know whether Scale is
12298 // signed or not. We'll use unsigned version of division/modulo
12299 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000012300 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012301 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012302 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012303 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000012304 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000012305 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
12306 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012307 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000012308 }
12309
12310 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000012311 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000012312 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000012313 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012314 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12315 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
12316 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000012317 // The NewGEP must be pointer typed, so must the old one -> BitCast
12318 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000012319 }
12320 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000012321 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012322 }
Chris Lattner58407792009-01-09 04:53:57 +000012323
Chris Lattner46cd5a12009-01-09 05:44:56 +000012324 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000012325 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000012326 /// Y = gep X, <...constant indices...>
12327 /// into a gep of the original struct. This is important for SROA and alias
12328 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000012329 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012330 if (TD &&
12331 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000012332 // Determine how much the GEP moves the pointer. We are guaranteed to get
12333 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000012334 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000012335 int64_t Offset = OffsetV->getSExtValue();
12336
12337 // If this GEP instruction doesn't move the pointer, just replace the GEP
12338 // with a bitcast of the real input to the dest type.
12339 if (Offset == 0) {
12340 // If the bitcast is of an allocation, and the allocation will be
12341 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000012342 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000012343 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000012344 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
12345 if (Instruction *I = visitBitCast(*BCI)) {
12346 if (I != BCI) {
12347 I->takeName(BCI);
12348 BCI->getParent()->getInstList().insert(BCI, I);
12349 ReplaceInstUsesWith(*BCI, I);
12350 }
12351 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000012352 }
Chris Lattner58407792009-01-09 04:53:57 +000012353 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000012354 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000012355 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000012356
12357 // Otherwise, if the offset is non-zero, we need to find out if there is a
12358 // field at Offset in 'A's type. If so, we can pull the cast through the
12359 // GEP.
12360 SmallVector<Value*, 8> NewIndices;
12361 const Type *InTy =
12362 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000012363 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012364 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12365 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
12366 NewIndices.end()) :
12367 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
12368 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012369
12370 if (NGEP->getType() == GEP.getType())
12371 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000012372 NGEP->takeName(&GEP);
12373 return new BitCastInst(NGEP, GEP.getType());
12374 }
Chris Lattner58407792009-01-09 04:53:57 +000012375 }
12376 }
12377
Chris Lattner8a2a3112001-12-14 16:52:21 +000012378 return 0;
12379}
12380
Victor Hernandez7b929da2009-10-23 21:09:37 +000012381Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000012382 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012383 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000012384 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
12385 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000012386 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000012387 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000012388 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012389 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000012390
Chris Lattner0864acf2002-11-04 16:18:53 +000012391 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000012392 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000012393 //
12394 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000012395 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000012396
12397 // Now that I is pointing to the first non-allocation-inst in the block,
12398 // insert our getelementptr instruction...
12399 //
Owen Anderson1d0be152009-08-13 21:58:54 +000012400 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000012401 Value *Idx[2];
12402 Idx[0] = NullIdx;
12403 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012404 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
12405 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000012406
12407 // Now make everything use the getelementptr instead of the original
12408 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000012409 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000012410 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000012411 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000012412 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012413 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012414
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012415 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000012416 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000012417 // Note that we only do this for alloca's, because malloc should allocate
12418 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000012419 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000012420 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000012421
12422 // If the alignment is 0 (unspecified), assign it the preferred alignment.
12423 if (AI.getAlignment() == 0)
12424 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
12425 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012426
Chris Lattner0864acf2002-11-04 16:18:53 +000012427 return 0;
12428}
12429
Victor Hernandez66284e02009-10-24 04:23:03 +000012430Instruction *InstCombiner::visitFree(Instruction &FI) {
12431 Value *Op = FI.getOperand(1);
12432
12433 // free undef -> unreachable.
12434 if (isa<UndefValue>(Op)) {
12435 // Insert a new store to null because we cannot modify the CFG here.
12436 new StoreInst(ConstantInt::getTrue(*Context),
12437 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
12438 return EraseInstFromFunction(FI);
12439 }
12440
12441 // If we have 'free null' delete the instruction. This can happen in stl code
12442 // when lots of inlining happens.
12443 if (isa<ConstantPointerNull>(Op))
12444 return EraseInstFromFunction(FI);
12445
Victor Hernandez046e78c2009-10-26 23:43:48 +000012446 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000012447 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000012448 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
12449 if (Op->hasOneUse() && CI->hasOneUse()) {
12450 EraseInstFromFunction(FI);
12451 EraseInstFromFunction(*CI);
12452 return EraseInstFromFunction(*cast<Instruction>(Op));
12453 }
12454 } else {
12455 // Op is a call to malloc
12456 if (Op->hasOneUse()) {
12457 EraseInstFromFunction(FI);
12458 return EraseInstFromFunction(*cast<Instruction>(Op));
12459 }
12460 }
Dan Gohman7f712a12009-10-27 00:11:02 +000012461 }
Victor Hernandez66284e02009-10-24 04:23:03 +000012462
12463 return 0;
12464}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000012465
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012466/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000012467static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000012468 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000012469 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000012470 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000012471 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000012472
Mon P Wang6753f952009-02-07 22:19:29 +000012473 const PointerType *DestTy = cast<PointerType>(CI->getType());
12474 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012475 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000012476
12477 // If the address spaces don't match, don't eliminate the cast.
12478 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12479 return 0;
12480
Chris Lattnerb89e0712004-07-13 01:49:43 +000012481 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012482
Reid Spencer42230162007-01-22 05:51:25 +000012483 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012484 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000012485 // If the source is an array, the code below will not succeed. Check to
12486 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12487 // constants.
12488 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12489 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12490 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000012491 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000012492 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12493 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000012494 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000012495 SrcTy = cast<PointerType>(CastOp->getType());
12496 SrcPTy = SrcTy->getElementType();
12497 }
12498
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012499 if (IC.getTargetData() &&
12500 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012501 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000012502 // Do not allow turning this into a load of an integer, which is then
12503 // casted to a pointer, this pessimizes pointer analysis a lot.
12504 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012505 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12506 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000012507
Chris Lattnerf9527852005-01-31 04:50:46 +000012508 // Okay, we are casting from one integer or pointer type to another of
12509 // the same size. Instead of casting the pointer before the load, cast
12510 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012511 Value *NewLoad =
12512 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000012513 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000012514 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000012515 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000012516 }
12517 }
12518 return 0;
12519}
12520
Chris Lattner833b8a42003-06-26 05:06:25 +000012521Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12522 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000012523
Dan Gohman9941f742007-07-20 16:34:21 +000012524 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012525 if (TD) {
12526 unsigned KnownAlign =
12527 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12528 if (KnownAlign >
12529 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12530 LI.getAlignment()))
12531 LI.setAlignment(KnownAlign);
12532 }
Dan Gohman9941f742007-07-20 16:34:21 +000012533
Chris Lattner963f4ba2009-08-30 20:36:46 +000012534 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012535 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000012536 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000012537 return Res;
12538
12539 // None of the following transforms are legal for volatile loads.
12540 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000012541
Dan Gohman2276a7b2008-10-15 23:19:35 +000012542 // Do really simple store-to-load forwarding and load CSE, to catch cases
12543 // where there are several consequtive memory accesses to the same location,
12544 // separated by a few arithmetic operations.
12545 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000012546 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12547 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000012548
Chris Lattner878e4942009-10-22 06:25:11 +000012549 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000012550 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12551 const Value *GEPI0 = GEPI->getOperand(0);
12552 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000012553 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000012554 // Insert a new store to null instruction before the load to indicate
12555 // that this code is not reachable. We do this instead of inserting
12556 // an unreachable instruction directly because we cannot modify the
12557 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012558 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000012559 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012560 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000012561 }
Christopher Lambb15147e2007-12-29 07:56:53 +000012562 }
Chris Lattner37366c12005-05-01 04:24:53 +000012563
Chris Lattner878e4942009-10-22 06:25:11 +000012564 // load null/undef -> unreachable
12565 // TODO: Consider a target hook for valid address spaces for this xform.
12566 if (isa<UndefValue>(Op) ||
12567 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12568 // Insert a new store to null instruction before the load to indicate that
12569 // this code is not reachable. We do this instead of inserting an
12570 // unreachable instruction directly because we cannot modify the CFG.
12571 new StoreInst(UndefValue::get(LI.getType()),
12572 Constant::getNullValue(Op->getType()), &LI);
12573 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000012574 }
Chris Lattner878e4942009-10-22 06:25:11 +000012575
12576 // Instcombine load (constantexpr_cast global) -> cast (load global)
12577 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12578 if (CE->isCast())
12579 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12580 return Res;
12581
Chris Lattner37366c12005-05-01 04:24:53 +000012582 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000012583 // Change select and PHI nodes to select values instead of addresses: this
12584 // helps alias analysis out a lot, allows many others simplifications, and
12585 // exposes redundancy in the code.
12586 //
12587 // Note that we cannot do the transformation unless we know that the
12588 // introduced loads cannot trap! Something like this is valid as long as
12589 // the condition is always false: load (select bool %C, int* null, int* %G),
12590 // but it would not be valid if we transformed it to load from null
12591 // unconditionally.
12592 //
12593 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12594 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000012595 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12596 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012597 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12598 SI->getOperand(1)->getName()+".val");
12599 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12600 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000012601 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000012602 }
12603
Chris Lattner684fe212004-09-23 15:46:00 +000012604 // load (select (cond, null, P)) -> load P
12605 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12606 if (C->isNullValue()) {
12607 LI.setOperand(0, SI->getOperand(2));
12608 return &LI;
12609 }
12610
12611 // load (select (cond, P, null)) -> load P
12612 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12613 if (C->isNullValue()) {
12614 LI.setOperand(0, SI->getOperand(1));
12615 return &LI;
12616 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000012617 }
12618 }
Chris Lattner833b8a42003-06-26 05:06:25 +000012619 return 0;
12620}
12621
Reid Spencer55af2b52007-01-19 21:20:31 +000012622/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000012623/// when possible. This makes it generally easy to do alias analysis and/or
12624/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012625static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12626 User *CI = cast<User>(SI.getOperand(1));
12627 Value *CastOp = CI->getOperand(0);
12628
12629 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012630 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12631 if (SrcTy == 0) return 0;
12632
12633 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012634
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012635 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12636 return 0;
12637
Chris Lattner3914f722009-01-24 01:00:13 +000012638 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12639 /// to its first element. This allows us to handle things like:
12640 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12641 /// on 32-bit hosts.
12642 SmallVector<Value*, 4> NewGEPIndices;
12643
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012644 // If the source is an array, the code below will not succeed. Check to
12645 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12646 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000012647 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12648 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000012649 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000012650 NewGEPIndices.push_back(Zero);
12651
12652 while (1) {
12653 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000012654 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000012655 break;
Chris Lattner3914f722009-01-24 01:00:13 +000012656 NewGEPIndices.push_back(Zero);
12657 SrcPTy = STy->getElementType(0);
12658 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12659 NewGEPIndices.push_back(Zero);
12660 SrcPTy = ATy->getElementType();
12661 } else {
12662 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012663 }
Chris Lattner3914f722009-01-24 01:00:13 +000012664 }
12665
Owen Andersondebcb012009-07-29 22:17:13 +000012666 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000012667 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012668
12669 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12670 return 0;
12671
Chris Lattner71759c42009-01-16 20:12:52 +000012672 // If the pointers point into different address spaces or if they point to
12673 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012674 if (!IC.getTargetData() ||
12675 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000012676 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012677 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12678 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012679 return 0;
12680
12681 // Okay, we are casting from one integer or pointer type to another of
12682 // the same size. Instead of casting the pointer before
12683 // the store, cast the value to be stored.
12684 Value *NewCast;
12685 Value *SIOp0 = SI.getOperand(0);
12686 Instruction::CastOps opcode = Instruction::BitCast;
12687 const Type* CastSrcTy = SIOp0->getType();
12688 const Type* CastDstTy = SrcPTy;
12689 if (isa<PointerType>(CastDstTy)) {
12690 if (CastSrcTy->isInteger())
12691 opcode = Instruction::IntToPtr;
12692 } else if (isa<IntegerType>(CastDstTy)) {
12693 if (isa<PointerType>(SIOp0->getType()))
12694 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012695 }
Chris Lattner3914f722009-01-24 01:00:13 +000012696
12697 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12698 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012699 if (!NewGEPIndices.empty())
12700 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12701 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000012702
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012703 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12704 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012705 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012706}
12707
Chris Lattner4aebaee2008-11-27 08:56:30 +000012708/// equivalentAddressValues - Test if A and B will obviously have the same
12709/// value. This includes recognizing that %t0 and %t1 will have the same
12710/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012711/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012712/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012713/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012714/// %t2 = load i32* %t1
12715///
12716static bool equivalentAddressValues(Value *A, Value *B) {
12717 // Test if the values are trivially equivalent.
12718 if (A == B) return true;
12719
12720 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012721 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12722 // its only used to compare two uses within the same basic block, which
12723 // means that they'll always either have the same value or one of them
12724 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000012725 if (isa<BinaryOperator>(A) ||
12726 isa<CastInst>(A) ||
12727 isa<PHINode>(A) ||
12728 isa<GetElementPtrInst>(A))
12729 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012730 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000012731 return true;
12732
12733 // Otherwise they may not be equivalent.
12734 return false;
12735}
12736
Dale Johannesen4945c652009-03-03 21:26:39 +000012737// If this instruction has two uses, one of which is a llvm.dbg.declare,
12738// return the llvm.dbg.declare.
12739DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12740 if (!V->hasNUses(2))
12741 return 0;
12742 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12743 UI != E; ++UI) {
12744 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12745 return DI;
12746 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12747 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12748 return DI;
12749 }
12750 }
12751 return 0;
12752}
12753
Chris Lattner2f503e62005-01-31 05:36:43 +000012754Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12755 Value *Val = SI.getOperand(0);
12756 Value *Ptr = SI.getOperand(1);
12757
Chris Lattner836692d2007-01-15 06:51:56 +000012758 // If the RHS is an alloca with a single use, zapify the store, making the
12759 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000012760 // If the RHS is an alloca with a two uses, the other one being a
12761 // llvm.dbg.declare, zapify the store and the declare, making the
12762 // alloca dead. We must do this to prevent declare's from affecting
12763 // codegen.
12764 if (!SI.isVolatile()) {
12765 if (Ptr->hasOneUse()) {
12766 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000012767 EraseInstFromFunction(SI);
12768 ++NumCombined;
12769 return 0;
12770 }
Dale Johannesen4945c652009-03-03 21:26:39 +000012771 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12772 if (isa<AllocaInst>(GEP->getOperand(0))) {
12773 if (GEP->getOperand(0)->hasOneUse()) {
12774 EraseInstFromFunction(SI);
12775 ++NumCombined;
12776 return 0;
12777 }
12778 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12779 EraseInstFromFunction(*DI);
12780 EraseInstFromFunction(SI);
12781 ++NumCombined;
12782 return 0;
12783 }
12784 }
12785 }
12786 }
12787 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12788 EraseInstFromFunction(*DI);
12789 EraseInstFromFunction(SI);
12790 ++NumCombined;
12791 return 0;
12792 }
Chris Lattner836692d2007-01-15 06:51:56 +000012793 }
Chris Lattner2f503e62005-01-31 05:36:43 +000012794
Dan Gohman9941f742007-07-20 16:34:21 +000012795 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012796 if (TD) {
12797 unsigned KnownAlign =
12798 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12799 if (KnownAlign >
12800 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12801 SI.getAlignment()))
12802 SI.setAlignment(KnownAlign);
12803 }
Dan Gohman9941f742007-07-20 16:34:21 +000012804
Dale Johannesenacb51a32009-03-03 01:43:03 +000012805 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000012806 // stores to the same location, separated by a few arithmetic operations. This
12807 // situation often occurs with bitfield accesses.
12808 BasicBlock::iterator BBI = &SI;
12809 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12810 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000012811 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012812 // Don't count debug info directives, lest they affect codegen,
12813 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12814 // It is necessary for correctness to skip those that feed into a
12815 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000012816 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012817 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000012818 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000012819 continue;
12820 }
Chris Lattner9ca96412006-02-08 03:25:32 +000012821
12822 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12823 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000012824 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12825 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012826 ++NumDeadStore;
12827 ++BBI;
12828 EraseInstFromFunction(*PrevSI);
12829 continue;
12830 }
12831 break;
12832 }
12833
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012834 // If this is a load, we have to stop. However, if the loaded value is from
12835 // the pointer we're loading and is producing the pointer we're storing,
12836 // then *this* store is dead (X = load P; store X -> P).
12837 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000012838 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12839 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012840 EraseInstFromFunction(SI);
12841 ++NumCombined;
12842 return 0;
12843 }
12844 // Otherwise, this is a load from some other location. Stores before it
12845 // may not be dead.
12846 break;
12847 }
12848
Chris Lattner9ca96412006-02-08 03:25:32 +000012849 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000012850 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000012851 break;
12852 }
12853
12854
12855 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000012856
12857 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000012858 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000012859 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012860 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000012861 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000012862 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000012863 ++NumCombined;
12864 }
12865 return 0; // Do not modify these!
12866 }
12867
12868 // store undef, Ptr -> noop
12869 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012870 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012871 ++NumCombined;
12872 return 0;
12873 }
12874
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012875 // If the pointer destination is a cast, see if we can fold the cast into the
12876 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012877 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012878 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12879 return Res;
12880 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000012881 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012882 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12883 return Res;
12884
Chris Lattner408902b2005-09-12 23:23:25 +000012885
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012886 // If this store is the last instruction in the basic block (possibly
12887 // excepting debug info instructions and the pointer bitcasts that feed
12888 // into them), and if the block ends with an unconditional branch, try
12889 // to move it to the successor block.
12890 BBI = &SI;
12891 do {
12892 ++BBI;
12893 } while (isa<DbgInfoIntrinsic>(BBI) ||
12894 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000012895 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012896 if (BI->isUnconditional())
12897 if (SimplifyStoreAtEndOfBlock(SI))
12898 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000012899
Chris Lattner2f503e62005-01-31 05:36:43 +000012900 return 0;
12901}
12902
Chris Lattner3284d1f2007-04-15 00:07:55 +000012903/// SimplifyStoreAtEndOfBlock - Turn things like:
12904/// if () { *P = v1; } else { *P = v2 }
12905/// into a phi node with a store in the successor.
12906///
Chris Lattner31755a02007-04-15 01:02:18 +000012907/// Simplify things like:
12908/// *P = v1; if () { *P = v2; }
12909/// into a phi node with a store in the successor.
12910///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012911bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12912 BasicBlock *StoreBB = SI.getParent();
12913
12914 // Check to see if the successor block has exactly two incoming edges. If
12915 // so, see if the other predecessor contains a store to the same location.
12916 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012917 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012918
12919 // Determine whether Dest has exactly two predecessors and, if so, compute
12920 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012921 pred_iterator PI = pred_begin(DestBB);
12922 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012923 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012924 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012925 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012926 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012927 return false;
12928
12929 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012930 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012931 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012932 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012933 }
Chris Lattner31755a02007-04-15 01:02:18 +000012934 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012935 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012936
12937 // Bail out if all the relevant blocks aren't distinct (this can happen,
12938 // for example, if SI is in an infinite loop)
12939 if (StoreBB == DestBB || OtherBB == DestBB)
12940 return false;
12941
Chris Lattner31755a02007-04-15 01:02:18 +000012942 // Verify that the other block ends in a branch and is not otherwise empty.
12943 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012944 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012945 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012946 return false;
12947
Chris Lattner31755a02007-04-15 01:02:18 +000012948 // If the other block ends in an unconditional branch, check for the 'if then
12949 // else' case. there is an instruction before the branch.
12950 StoreInst *OtherStore = 0;
12951 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012952 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012953 // Skip over debugging info.
12954 while (isa<DbgInfoIntrinsic>(BBI) ||
12955 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12956 if (BBI==OtherBB->begin())
12957 return false;
12958 --BBI;
12959 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012960 // If this isn't a store, isn't a store to the same location, or if the
12961 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012962 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012963 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12964 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012965 return false;
12966 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012967 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012968 // destinations is StoreBB, then we have the if/then case.
12969 if (OtherBr->getSuccessor(0) != StoreBB &&
12970 OtherBr->getSuccessor(1) != StoreBB)
12971 return false;
12972
12973 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012974 // if/then triangle. See if there is a store to the same ptr as SI that
12975 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012976 for (;; --BBI) {
12977 // Check to see if we find the matching store.
12978 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012979 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12980 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012981 return false;
12982 break;
12983 }
Eli Friedman6903a242008-06-13 22:02:12 +000012984 // If we find something that may be using or overwriting the stored
12985 // value, or if we run out of instructions, we can't do the xform.
12986 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012987 BBI == OtherBB->begin())
12988 return false;
12989 }
12990
12991 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012992 // make sure nothing reads or overwrites the stored value in
12993 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012994 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12995 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012996 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012997 return false;
12998 }
12999 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000013000
Chris Lattner31755a02007-04-15 01:02:18 +000013001 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000013002 Value *MergedVal = OtherStore->getOperand(0);
13003 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000013004 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000013005 PN->reserveOperandSpace(2);
13006 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000013007 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
13008 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000013009 }
13010
13011 // Advance to a place where it is safe to insert the new store and
13012 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000013013 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000013014 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000013015 OtherStore->isVolatile(),
13016 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000013017
13018 // Nuke the old stores.
13019 EraseInstFromFunction(SI);
13020 EraseInstFromFunction(*OtherStore);
13021 ++NumCombined;
13022 return true;
13023}
13024
Chris Lattner2f503e62005-01-31 05:36:43 +000013025
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000013026Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
13027 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000013028 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000013029 BasicBlock *TrueDest;
13030 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000013031 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000013032 !isa<Constant>(X)) {
13033 // Swap Destinations and condition...
13034 BI.setCondition(X);
13035 BI.setSuccessor(0, FalseDest);
13036 BI.setSuccessor(1, TrueDest);
13037 return &BI;
13038 }
13039
Reid Spencere4d87aa2006-12-23 06:05:41 +000013040 // Cannonicalize fcmp_one -> fcmp_oeq
13041 FCmpInst::Predicate FPred; Value *Y;
13042 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000013043 TrueDest, FalseDest)) &&
13044 BI.getCondition()->hasOneUse())
13045 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
13046 FPred == FCmpInst::FCMP_OGE) {
13047 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
13048 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
13049
13050 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000013051 BI.setSuccessor(0, FalseDest);
13052 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000013053 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000013054 return &BI;
13055 }
13056
13057 // Cannonicalize icmp_ne -> icmp_eq
13058 ICmpInst::Predicate IPred;
13059 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000013060 TrueDest, FalseDest)) &&
13061 BI.getCondition()->hasOneUse())
13062 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
13063 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
13064 IPred == ICmpInst::ICMP_SGE) {
13065 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
13066 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
13067 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000013068 BI.setSuccessor(0, FalseDest);
13069 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000013070 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000013071 return &BI;
13072 }
Misha Brukmanfd939082005-04-21 23:48:37 +000013073
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000013074 return 0;
13075}
Chris Lattner0864acf2002-11-04 16:18:53 +000013076
Chris Lattner46238a62004-07-03 00:26:11 +000013077Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
13078 Value *Cond = SI.getCondition();
13079 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
13080 if (I->getOpcode() == Instruction::Add)
13081 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
13082 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
13083 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000013084 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000013085 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000013086 AddRHS));
13087 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000013088 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000013089 return &SI;
13090 }
13091 }
13092 return 0;
13093}
13094
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000013095Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013096 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000013097
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013098 if (!EV.hasIndices())
13099 return ReplaceInstUsesWith(EV, Agg);
13100
13101 if (Constant *C = dyn_cast<Constant>(Agg)) {
13102 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013103 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013104
13105 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000013106 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013107
13108 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
13109 // Extract the element indexed by the first index out of the constant
13110 Value *V = C->getOperand(*EV.idx_begin());
13111 if (EV.getNumIndices() > 1)
13112 // Extract the remaining indices out of the constant indexed by the
13113 // first index
13114 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
13115 else
13116 return ReplaceInstUsesWith(EV, V);
13117 }
13118 return 0; // Can't handle other constants
13119 }
13120 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
13121 // We're extracting from an insertvalue instruction, compare the indices
13122 const unsigned *exti, *exte, *insi, *inse;
13123 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
13124 exte = EV.idx_end(), inse = IV->idx_end();
13125 exti != exte && insi != inse;
13126 ++exti, ++insi) {
13127 if (*insi != *exti)
13128 // The insert and extract both reference distinctly different elements.
13129 // This means the extract is not influenced by the insert, and we can
13130 // replace the aggregate operand of the extract with the aggregate
13131 // operand of the insert. i.e., replace
13132 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
13133 // %E = extractvalue { i32, { i32 } } %I, 0
13134 // with
13135 // %E = extractvalue { i32, { i32 } } %A, 0
13136 return ExtractValueInst::Create(IV->getAggregateOperand(),
13137 EV.idx_begin(), EV.idx_end());
13138 }
13139 if (exti == exte && insi == inse)
13140 // Both iterators are at the end: Index lists are identical. Replace
13141 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
13142 // %C = extractvalue { i32, { i32 } } %B, 1, 0
13143 // with "i32 42"
13144 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
13145 if (exti == exte) {
13146 // The extract list is a prefix of the insert list. i.e. replace
13147 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
13148 // %E = extractvalue { i32, { i32 } } %I, 1
13149 // with
13150 // %X = extractvalue { i32, { i32 } } %A, 1
13151 // %E = insertvalue { i32 } %X, i32 42, 0
13152 // by switching the order of the insert and extract (though the
13153 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000013154 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
13155 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013156 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
13157 insi, inse);
13158 }
13159 if (insi == inse)
13160 // The insert list is a prefix of the extract list
13161 // We can simply remove the common indices from the extract and make it
13162 // operate on the inserted value instead of the insertvalue result.
13163 // i.e., replace
13164 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
13165 // %E = extractvalue { i32, { i32 } } %I, 1, 0
13166 // with
13167 // %E extractvalue { i32 } { i32 42 }, 0
13168 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
13169 exti, exte);
13170 }
Chris Lattner7e606e22009-11-09 07:07:56 +000013171 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
13172 // We're extracting from an intrinsic, see if we're the only user, which
13173 // allows us to simplify multiple result intrinsics to simpler things that
13174 // just get one value..
13175 if (II->hasOneUse()) {
13176 // Check if we're grabbing the overflow bit or the result of a 'with
13177 // overflow' intrinsic. If it's the latter we can remove the intrinsic
13178 // and replace it with a traditional binary instruction.
13179 switch (II->getIntrinsicID()) {
13180 case Intrinsic::uadd_with_overflow:
13181 case Intrinsic::sadd_with_overflow:
13182 if (*EV.idx_begin() == 0) { // Normal result.
13183 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13184 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13185 EraseInstFromFunction(*II);
13186 return BinaryOperator::CreateAdd(LHS, RHS);
13187 }
13188 break;
13189 case Intrinsic::usub_with_overflow:
13190 case Intrinsic::ssub_with_overflow:
13191 if (*EV.idx_begin() == 0) { // Normal result.
13192 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13193 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13194 EraseInstFromFunction(*II);
13195 return BinaryOperator::CreateSub(LHS, RHS);
13196 }
13197 break;
13198 case Intrinsic::umul_with_overflow:
13199 case Intrinsic::smul_with_overflow:
13200 if (*EV.idx_begin() == 0) { // Normal result.
13201 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13202 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13203 EraseInstFromFunction(*II);
13204 return BinaryOperator::CreateMul(LHS, RHS);
13205 }
13206 break;
13207 default:
13208 break;
13209 }
13210 }
13211 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013212 // Can't simplify extracts from other values. Note that nested extracts are
13213 // already simplified implicitely by the above (extract ( extract (insert) )
13214 // will be translated into extract ( insert ( extract ) ) first and then just
13215 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000013216 return 0;
13217}
13218
Chris Lattner220b0cf2006-03-05 00:22:33 +000013219/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
13220/// is to leave as a vector operation.
13221static bool CheapToScalarize(Value *V, bool isConstant) {
13222 if (isa<ConstantAggregateZero>(V))
13223 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000013224 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000013225 if (isConstant) return true;
13226 // If all elts are the same, we can extract.
13227 Constant *Op0 = C->getOperand(0);
13228 for (unsigned i = 1; i < C->getNumOperands(); ++i)
13229 if (C->getOperand(i) != Op0)
13230 return false;
13231 return true;
13232 }
13233 Instruction *I = dyn_cast<Instruction>(V);
13234 if (!I) return false;
13235
13236 // Insert element gets simplified to the inserted element or is deleted if
13237 // this is constant idx extract element and its a constant idx insertelt.
13238 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
13239 isa<ConstantInt>(I->getOperand(2)))
13240 return true;
13241 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
13242 return true;
13243 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
13244 if (BO->hasOneUse() &&
13245 (CheapToScalarize(BO->getOperand(0), isConstant) ||
13246 CheapToScalarize(BO->getOperand(1), isConstant)))
13247 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000013248 if (CmpInst *CI = dyn_cast<CmpInst>(I))
13249 if (CI->hasOneUse() &&
13250 (CheapToScalarize(CI->getOperand(0), isConstant) ||
13251 CheapToScalarize(CI->getOperand(1), isConstant)))
13252 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000013253
13254 return false;
13255}
13256
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000013257/// Read and decode a shufflevector mask.
13258///
13259/// It turns undef elements into values that are larger than the number of
13260/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000013261static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
13262 unsigned NElts = SVI->getType()->getNumElements();
13263 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
13264 return std::vector<unsigned>(NElts, 0);
13265 if (isa<UndefValue>(SVI->getOperand(2)))
13266 return std::vector<unsigned>(NElts, 2*NElts);
13267
13268 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000013269 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000013270 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
13271 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000013272 Result.push_back(NElts*2); // undef -> 8
13273 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000013274 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000013275 return Result;
13276}
13277
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013278/// FindScalarElement - Given a vector and an element number, see if the scalar
13279/// value is already around as a register, for example if it were inserted then
13280/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000013281static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013282 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000013283 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
13284 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000013285 unsigned Width = PTy->getNumElements();
13286 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013287 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013288
13289 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013290 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013291 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000013292 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000013293 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013294 return CP->getOperand(EltNo);
13295 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
13296 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000013297 if (!isa<ConstantInt>(III->getOperand(2)))
13298 return 0;
13299 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013300
13301 // If this is an insert to the element we are looking for, return the
13302 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000013303 if (EltNo == IIElt)
13304 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013305
13306 // Otherwise, the insertelement doesn't modify the value, recurse on its
13307 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000013308 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000013309 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000013310 unsigned LHSWidth =
13311 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000013312 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000013313 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000013314 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000013315 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000013316 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000013317 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013318 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013319 }
13320
13321 // Otherwise, we don't know.
13322 return 0;
13323}
13324
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013325Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000013326 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000013327 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013328 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000013329
Dan Gohman07a96762007-07-16 14:29:03 +000013330 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000013331 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000013332 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000013333
Reid Spencer9d6565a2007-02-15 02:26:10 +000013334 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000013335 // If vector val is constant with all elements the same, replace EI with
13336 // that element. When the elements are not identical, we cannot replace yet
13337 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000013338 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000013339 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000013340 if (C->getOperand(i) != op0) {
13341 op0 = 0;
13342 break;
13343 }
13344 if (op0)
13345 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013346 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000013347
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013348 // If extracting a specified index from the vector, see if we can recursively
13349 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000013350 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000013351 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000013352 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000013353
13354 // If this is extracting an invalid index, turn this into undef, to avoid
13355 // crashing the code below.
13356 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013357 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000013358
Chris Lattner867b99f2006-10-05 06:55:50 +000013359 // This instruction only demands the single element from the input vector.
13360 // If the input vector has a single use, simplify it based on this use
13361 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000013362 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000013363 APInt UndefElts(VectorWidth, 0);
13364 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000013365 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000013366 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000013367 EI.setOperand(0, V);
13368 return &EI;
13369 }
13370 }
13371
Owen Andersond672ecb2009-07-03 00:17:18 +000013372 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013373 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013374
13375 // If the this extractelement is directly using a bitcast from a vector of
13376 // the same number of elements, see if we can find the source element from
13377 // it. In this case, we will end up needing to bitcast the scalars.
13378 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
13379 if (const VectorType *VT =
13380 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
13381 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000013382 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
13383 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013384 return new BitCastInst(Elt, EI.getType());
13385 }
Chris Lattner389a6f52006-04-10 23:06:36 +000013386 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013387
Chris Lattner73fa49d2006-05-25 22:53:38 +000013388 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000013389 // Push extractelement into predecessor operation if legal and
13390 // profitable to do so
13391 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
13392 if (I->hasOneUse() &&
13393 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
13394 Value *newEI0 =
13395 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
13396 EI.getName()+".lhs");
13397 Value *newEI1 =
13398 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
13399 EI.getName()+".rhs");
13400 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000013401 }
Chris Lattner275a6d62009-09-08 18:48:01 +000013402 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000013403 // Extracting the inserted element?
13404 if (IE->getOperand(2) == EI.getOperand(1))
13405 return ReplaceInstUsesWith(EI, IE->getOperand(1));
13406 // If the inserted and extracted elements are constants, they must not
13407 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000013408 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000013409 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000013410 EI.setOperand(0, IE->getOperand(0));
13411 return &EI;
13412 }
13413 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
13414 // If this is extracting an element from a shufflevector, figure out where
13415 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000013416 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13417 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000013418 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013419 unsigned LHSWidth =
13420 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13421
13422 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000013423 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000013424 else if (SrcIdx < LHSWidth*2) {
13425 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000013426 Src = SVI->getOperand(1);
13427 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013428 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000013429 }
Eric Christophera3500da2009-07-25 02:28:41 +000013430 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000013431 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
13432 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013433 }
13434 }
Eli Friedman2451a642009-07-18 23:06:53 +000013435 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000013436 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013437 return 0;
13438}
13439
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013440/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
13441/// elements from either LHS or RHS, return the shuffle mask and true.
13442/// Otherwise, return false.
13443static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000013444 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013445 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013446 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
13447 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013448 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013449
13450 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013451 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013452 return true;
13453 } else if (V == LHS) {
13454 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013455 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013456 return true;
13457 } else if (V == RHS) {
13458 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013459 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013460 return true;
13461 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13462 // If this is an insert of an extract from some other vector, include it.
13463 Value *VecOp = IEI->getOperand(0);
13464 Value *ScalarOp = IEI->getOperand(1);
13465 Value *IdxOp = IEI->getOperand(2);
13466
Chris Lattnerd929f062006-04-27 21:14:21 +000013467 if (!isa<ConstantInt>(IdxOp))
13468 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000013469 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000013470
13471 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
13472 // Okay, we can handle this if the vector we are insertinting into is
13473 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000013474 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000013475 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013476 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000013477 return true;
13478 }
13479 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13480 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013481 EI->getOperand(0)->getType() == V->getType()) {
13482 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013483 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013484
13485 // This must be extracting from either LHS or RHS.
13486 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13487 // Okay, we can handle this if the vector we are insertinting into is
13488 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000013489 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013490 // If so, update the mask to reflect the inserted value.
13491 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013492 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013493 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013494 } else {
13495 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013496 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013497 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013498
13499 }
13500 return true;
13501 }
13502 }
13503 }
13504 }
13505 }
13506 // TODO: Handle shufflevector here!
13507
13508 return false;
13509}
13510
13511/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13512/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
13513/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000013514static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013515 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000013516 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013517 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000013518 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013519 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000013520
13521 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013522 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000013523 return V;
13524 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013525 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000013526 return V;
13527 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13528 // If this is an insert of an extract from some other vector, include it.
13529 Value *VecOp = IEI->getOperand(0);
13530 Value *ScalarOp = IEI->getOperand(1);
13531 Value *IdxOp = IEI->getOperand(2);
13532
13533 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13534 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13535 EI->getOperand(0)->getType() == V->getType()) {
13536 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013537 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13538 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013539
13540 // Either the extracted from or inserted into vector must be RHSVec,
13541 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013542 if (EI->getOperand(0) == RHS || RHS == 0) {
13543 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000013544 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013545 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013546 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000013547 return V;
13548 }
13549
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013550 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000013551 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13552 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000013553 // Everything but the extracted element is replaced with the RHS.
13554 for (unsigned i = 0; i != NumElts; ++i) {
13555 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000013556 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000013557 }
13558 return V;
13559 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013560
13561 // If this insertelement is a chain that comes from exactly these two
13562 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000013563 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13564 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013565 return EI->getOperand(0);
13566
Chris Lattnerefb47352006-04-15 01:39:45 +000013567 }
13568 }
13569 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013570 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000013571
13572 // Otherwise, can't do anything fancy. Return an identity vector.
13573 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013574 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000013575 return V;
13576}
13577
13578Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13579 Value *VecOp = IE.getOperand(0);
13580 Value *ScalarOp = IE.getOperand(1);
13581 Value *IdxOp = IE.getOperand(2);
13582
Chris Lattner599ded12007-04-09 01:11:16 +000013583 // Inserting an undef or into an undefined place, remove this.
13584 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13585 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000013586
Chris Lattnerefb47352006-04-15 01:39:45 +000013587 // If the inserted element was extracted from some other vector, and if the
13588 // indexes are constant, try to turn this into a shufflevector operation.
13589 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13590 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13591 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000013592 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000013593 unsigned ExtractedIdx =
13594 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000013595 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013596
13597 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13598 return ReplaceInstUsesWith(IE, VecOp);
13599
13600 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013601 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000013602
13603 // If we are extracting a value from a vector, then inserting it right
13604 // back into the same place, just use the input vector.
13605 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13606 return ReplaceInstUsesWith(IE, VecOp);
13607
Chris Lattnerefb47352006-04-15 01:39:45 +000013608 // If this insertelement isn't used by some other insertelement, turn it
13609 // (and any insertelements it points to), into one big shuffle.
13610 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13611 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013612 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000013613 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013614 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013615 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000013616 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000013617 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000013618 }
13619 }
13620 }
13621
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000013622 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13623 APInt UndefElts(VWidth, 0);
13624 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13625 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13626 return &IE;
13627
Chris Lattnerefb47352006-04-15 01:39:45 +000013628 return 0;
13629}
13630
13631
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013632Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13633 Value *LHS = SVI.getOperand(0);
13634 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000013635 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013636
13637 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013638
Chris Lattner867b99f2006-10-05 06:55:50 +000013639 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000013640 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013641 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000013642
Dan Gohman488fbfc2008-09-09 18:11:14 +000013643 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000013644
13645 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13646 return 0;
13647
Evan Cheng388df622009-02-03 10:05:09 +000013648 APInt UndefElts(VWidth, 0);
13649 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13650 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000013651 LHS = SVI.getOperand(0);
13652 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000013653 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000013654 }
Chris Lattnerefb47352006-04-15 01:39:45 +000013655
Chris Lattner863bcff2006-05-25 23:48:38 +000013656 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13657 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13658 if (LHS == RHS || isa<UndefValue>(LHS)) {
13659 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013660 // shuffle(undef,undef,mask) -> undef.
13661 return ReplaceInstUsesWith(SVI, LHS);
13662 }
13663
Chris Lattner863bcff2006-05-25 23:48:38 +000013664 // Remap any references to RHS to use LHS.
13665 std::vector<Constant*> Elts;
13666 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013667 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000013668 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013669 else {
13670 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000013671 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013672 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013673 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000013674 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013675 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000013676 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000013677 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013678 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013679 }
Chris Lattner863bcff2006-05-25 23:48:38 +000013680 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013681 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000013682 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013683 LHS = SVI.getOperand(0);
13684 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013685 MadeChange = true;
13686 }
13687
Chris Lattner7b2e27922006-05-26 00:29:06 +000013688 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000013689 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000013690
Chris Lattner863bcff2006-05-25 23:48:38 +000013691 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13692 if (Mask[i] >= e*2) continue; // Ignore undef values.
13693 // Is this an identity shuffle of the LHS value?
13694 isLHSID &= (Mask[i] == i);
13695
13696 // Is this an identity shuffle of the RHS value?
13697 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000013698 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013699
Chris Lattner863bcff2006-05-25 23:48:38 +000013700 // Eliminate identity shuffles.
13701 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13702 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013703
Chris Lattner7b2e27922006-05-26 00:29:06 +000013704 // If the LHS is a shufflevector itself, see if we can combine it with this
13705 // one without producing an unusual shuffle. Here we are really conservative:
13706 // we are absolutely afraid of producing a shuffle mask not in the input
13707 // program, because the code gen may not be smart enough to turn a merged
13708 // shuffle into two specific shuffles: it may produce worse code. As such,
13709 // we only merge two shuffles if the result is one of the two input shuffle
13710 // masks. In this case, merging the shuffles just removes one instruction,
13711 // which we know is safe. This is good for things like turning:
13712 // (splat(splat)) -> splat.
13713 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13714 if (isa<UndefValue>(RHS)) {
13715 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13716
David Greenef941d292009-11-16 21:52:23 +000013717 if (LHSMask.size() == Mask.size()) {
13718 std::vector<unsigned> NewMask;
13719 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sands76700ba2009-11-20 13:19:51 +000013720 if (Mask[i] >= e)
David Greenef941d292009-11-16 21:52:23 +000013721 NewMask.push_back(2*e);
13722 else
13723 NewMask.push_back(LHSMask[Mask[i]]);
Chris Lattner7b2e27922006-05-26 00:29:06 +000013724
David Greenef941d292009-11-16 21:52:23 +000013725 // If the result mask is equal to the src shuffle or this
13726 // shuffle mask, do the replacement.
13727 if (NewMask == LHSMask || NewMask == Mask) {
13728 unsigned LHSInNElts =
13729 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13730 getNumElements();
13731 std::vector<Constant*> Elts;
13732 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13733 if (NewMask[i] >= LHSInNElts*2) {
13734 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13735 } else {
13736 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13737 NewMask[i]));
13738 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013739 }
David Greenef941d292009-11-16 21:52:23 +000013740 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13741 LHSSVI->getOperand(1),
13742 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013743 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013744 }
13745 }
13746 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000013747
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013748 return MadeChange ? &SVI : 0;
13749}
13750
13751
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013752
Chris Lattnerea1c4542004-12-08 23:43:58 +000013753
13754/// TryToSinkInstruction - Try to move the specified instruction from its
13755/// current block into the beginning of DestBlock, which can only happen if it's
13756/// safe to move the instruction past all of the instructions between it and the
13757/// end of its block.
13758static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13759 assert(I->hasOneUse() && "Invariants didn't hold!");
13760
Chris Lattner108e9022005-10-27 17:13:11 +000013761 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000013762 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000013763 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000013764
Chris Lattnerea1c4542004-12-08 23:43:58 +000013765 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000013766 if (isa<AllocaInst>(I) && I->getParent() ==
13767 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013768 return false;
13769
Chris Lattner96a52a62004-12-09 07:14:34 +000013770 // We can only sink load instructions if there is nothing between the load and
13771 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000013772 if (I->mayReadFromMemory()) {
13773 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000013774 Scan != E; ++Scan)
13775 if (Scan->mayWriteToMemory())
13776 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000013777 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000013778
Dan Gohman02dea8b2008-05-23 21:05:58 +000013779 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000013780
Dale Johannesenbd8e6502009-03-03 01:09:07 +000013781 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000013782 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013783 ++NumSunkInst;
13784 return true;
13785}
13786
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013787
13788/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13789/// all reachable code to the worklist.
13790///
13791/// This has a couple of tricks to make the code faster and more powerful. In
13792/// particular, we constant fold and DCE instructions as we go, to avoid adding
13793/// them to the worklist (this significantly speeds up instcombine on code where
13794/// many instructions are dead or constant). Additionally, if we find a branch
13795/// whose condition is a known constant, we only visit the reachable successors.
13796///
Chris Lattner2ee743b2009-10-15 04:59:28 +000013797static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000013798 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000013799 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013800 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000013801 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000013802 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000013803 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000013804
13805 std::vector<Instruction*> InstrsForInstCombineWorklist;
13806 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013807
Chris Lattner2ee743b2009-10-15 04:59:28 +000013808 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13809
Chris Lattner2c7718a2007-03-23 19:17:18 +000013810 while (!Worklist.empty()) {
13811 BB = Worklist.back();
13812 Worklist.pop_back();
13813
13814 // We have now visited this block! If we've already been here, ignore it.
13815 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000013816
Chris Lattner2c7718a2007-03-23 19:17:18 +000013817 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13818 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013819
Chris Lattner2c7718a2007-03-23 19:17:18 +000013820 // DCE instruction if trivially dead.
13821 if (isInstructionTriviallyDead(Inst)) {
13822 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000013823 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000013824 Inst->eraseFromParent();
13825 continue;
13826 }
13827
13828 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013829 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013830 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013831 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13832 << *Inst << '\n');
13833 Inst->replaceAllUsesWith(C);
13834 ++NumConstProp;
13835 Inst->eraseFromParent();
13836 continue;
13837 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000013838
13839
13840
13841 if (TD) {
13842 // See if we can constant fold its operands.
13843 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13844 i != e; ++i) {
13845 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13846 if (CE == 0) continue;
13847
13848 // If we already folded this constant, don't try again.
13849 if (!FoldedConstants.insert(CE))
13850 continue;
13851
Chris Lattner7b550cc2009-11-06 04:27:31 +000013852 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000013853 if (NewC && NewC != CE) {
13854 *i = NewC;
13855 MadeIRChange = true;
13856 }
13857 }
13858 }
13859
Devang Patel7fe1dec2008-11-19 18:56:50 +000013860
Chris Lattner67f7d542009-10-12 03:58:40 +000013861 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013862 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000013863
13864 // Recursively visit successors. If this is a branch or switch on a
13865 // constant, only visit the reachable successor.
13866 TerminatorInst *TI = BB->getTerminator();
13867 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13868 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13869 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000013870 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013871 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013872 continue;
13873 }
13874 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13875 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13876 // See if this is an explicit destination.
13877 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13878 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000013879 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013880 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013881 continue;
13882 }
13883
13884 // Otherwise it is the default destination.
13885 Worklist.push_back(SI->getSuccessor(0));
13886 continue;
13887 }
13888 }
13889
13890 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13891 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013892 }
Chris Lattner67f7d542009-10-12 03:58:40 +000013893
13894 // Once we've found all of the instructions to add to instcombine's worklist,
13895 // add them in reverse order. This way instcombine will visit from the top
13896 // of the function down. This jives well with the way that it adds all uses
13897 // of instructions to the worklist after doing a transformation, thus avoiding
13898 // some N^2 behavior in pathological cases.
13899 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13900 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000013901
13902 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013903}
13904
Chris Lattnerec9c3582007-03-03 02:04:50 +000013905bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013906 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013907
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000013908 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13909 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000013910
Chris Lattnerb3d59702005-07-07 20:40:38 +000013911 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013912 // Do a depth-first traversal of the function, populate the worklist with
13913 // the reachable instructions. Ignore blocks that are not reachable. Keep
13914 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000013915 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000013916 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000013917
Chris Lattnerb3d59702005-07-07 20:40:38 +000013918 // Do a quick scan over the function. If we find any blocks that are
13919 // unreachable, remove any instructions inside of them. This prevents
13920 // the instcombine code from having to deal with some bad special cases.
13921 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13922 if (!Visited.count(BB)) {
13923 Instruction *Term = BB->getTerminator();
13924 while (Term != BB->begin()) { // Remove instrs bottom-up
13925 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000013926
Chris Lattnerbdff5482009-08-23 04:37:46 +000013927 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000013928 // A debug intrinsic shouldn't force another iteration if we weren't
13929 // going to do one without it.
13930 if (!isa<DbgInfoIntrinsic>(I)) {
13931 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013932 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000013933 }
Devang Patel228ebd02009-10-13 22:56:32 +000013934
Devang Patel228ebd02009-10-13 22:56:32 +000013935 // If I is not void type then replaceAllUsesWith undef.
13936 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000013937 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000013938 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013939 I->eraseFromParent();
13940 }
13941 }
13942 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013943
Chris Lattner873ff012009-08-30 05:55:36 +000013944 while (!Worklist.isEmpty()) {
13945 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013946 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013947
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013948 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013949 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013950 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000013951 EraseInstFromFunction(*I);
13952 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013953 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013954 continue;
13955 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013956
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013957 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013958 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013959 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013960 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000013961
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013962 // Add operands to the worklist.
13963 ReplaceInstUsesWith(*I, C);
13964 ++NumConstProp;
13965 EraseInstFromFunction(*I);
13966 MadeIRChange = true;
13967 continue;
13968 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013969
Chris Lattnerea1c4542004-12-08 23:43:58 +000013970 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013971 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013972 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000013973 Instruction *UserInst = cast<Instruction>(I->use_back());
13974 BasicBlock *UserParent;
13975
13976 // Get the block the use occurs in.
13977 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13978 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13979 else
13980 UserParent = UserInst->getParent();
13981
Chris Lattnerea1c4542004-12-08 23:43:58 +000013982 if (UserParent != BB) {
13983 bool UserIsSuccessor = false;
13984 // See if the user is one of our successors.
13985 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13986 if (*SI == UserParent) {
13987 UserIsSuccessor = true;
13988 break;
13989 }
13990
13991 // If the user is one of our immediate successors, and if that successor
13992 // only has us as a predecessors (we'd have to split the critical edge
13993 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000013994 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013995 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013996 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013997 }
13998 }
13999
Chris Lattner74381062009-08-30 07:44:24 +000014000 // Now that we have an instruction, try combining it to simplify it.
14001 Builder->SetInsertPoint(I->getParent(), I);
14002
Reid Spencera9b81012007-03-26 17:44:01 +000014003#ifndef NDEBUG
14004 std::string OrigI;
14005#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000014006 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000014007 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
14008
Chris Lattner90ac28c2002-08-02 19:29:35 +000014009 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000014010 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000014011 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000014012 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000014013 DEBUG(errs() << "IC: Old = " << *I << '\n'
14014 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000014015
Chris Lattnerf523d062004-06-09 05:08:07 +000014016 // Everything uses the new instruction now.
14017 I->replaceAllUsesWith(Result);
14018
14019 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000014020 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000014021 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000014022
Chris Lattner6934a042007-02-11 01:23:03 +000014023 // Move the name to the new instruction first.
14024 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000014025
14026 // Insert the new instruction into the basic block...
14027 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000014028 BasicBlock::iterator InsertPos = I;
14029
14030 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
14031 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
14032 ++InsertPos;
14033
14034 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000014035
Chris Lattner7a1e9242009-08-30 06:13:40 +000014036 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000014037 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000014038#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000014039 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
14040 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000014041#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000014042
Chris Lattner90ac28c2002-08-02 19:29:35 +000014043 // If the instruction was modified, it's possible that it is now dead.
14044 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000014045 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000014046 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000014047 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000014048 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000014049 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000014050 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000014051 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000014052 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000014053 }
14054 }
14055
Chris Lattner873ff012009-08-30 05:55:36 +000014056 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000014057 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000014058}
14059
Chris Lattnerec9c3582007-03-03 02:04:50 +000014060
14061bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000014062 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000014063 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000014064 TD = getAnalysisIfAvailable<TargetData>();
14065
Chris Lattner74381062009-08-30 07:44:24 +000014066
14067 /// Builder - This is an IRBuilder that automatically inserts new
14068 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000014069 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000014070 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000014071 InstCombineIRInserter(Worklist));
14072 Builder = &TheBuilder;
14073
Chris Lattnerec9c3582007-03-03 02:04:50 +000014074 bool EverMadeChange = false;
14075
14076 // Iterate while there is work to do.
14077 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000014078 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000014079 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000014080
14081 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000014082 return EverMadeChange;
14083}
14084
Brian Gaeke96d4bf72004-07-27 17:43:21 +000014085FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000014086 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000014087}