blob: ee0b9374cb14e70d76667793d845f61cb47906cb [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);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000261 Instruction *visitFCmpInst(FCmpInst &I);
262 Instruction *visitICmpInst(ICmpInst &I);
263 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000264 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
265 Instruction *LHS,
266 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000267 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
268 ConstantInt *DivRHS);
Chris Lattner2799baf2009-12-21 03:19:28 +0000269 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +0000270 ICmpInst::Predicate Pred, Value *TheAdd);
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000271 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000272 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000273 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000274 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000275 Instruction *commonCastTransforms(CastInst &CI);
276 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000277 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000278 Instruction *visitTrunc(TruncInst &CI);
279 Instruction *visitZExt(ZExtInst &CI);
280 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000281 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000282 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000283 Instruction *visitFPToUI(FPToUIInst &FI);
284 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000285 Instruction *visitUIToFP(CastInst &CI);
286 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000287 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000288 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000289 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000290 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
291 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000292 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000293 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
294 Value *A, Value *B, Instruction &Outer,
295 SelectPatternFlavor SPF2, Value *C);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000296 Instruction *visitSelectInst(SelectInst &SI);
297 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000298 Instruction *visitCallInst(CallInst &CI);
299 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner9956c052009-11-08 19:23:30 +0000300
301 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Chris Lattner7e708292002-06-25 16:13:24 +0000302 Instruction *visitPHINode(PHINode &PN);
303 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000304 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000305 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000306 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000307 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000308 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000309 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000310 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000311 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000312 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000313 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000314
315 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000316 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000317
Chris Lattner9fe38862003-06-19 17:00:31 +0000318 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000319 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000320 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000321 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000322 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
323 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000324 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000325 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
326
Chris Lattner9fe38862003-06-19 17:00:31 +0000327
Chris Lattner28977af2004-04-05 01:30:19 +0000328 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000329 // InsertNewInstBefore - insert an instruction New before instruction Old
330 // in the program. Add the new instruction to the worklist.
331 //
Chris Lattner955f3312004-09-28 21:48:02 +0000332 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000333 assert(New && New->getParent() == 0 &&
334 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000335 BasicBlock *BB = Old.getParent();
336 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000337 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000338 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000339 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000340
Chris Lattner8b170942002-08-09 23:47:40 +0000341 // ReplaceInstUsesWith - This method is to be used when an instruction is
342 // found to be dead, replacable with another preexisting expression. Here
343 // we add all uses of I to the worklist, replace all uses of I with the new
344 // value, then return I, so that the inst combiner will know that I was
345 // modified.
346 //
347 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000348 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000349
350 // If we are replacing the instruction with itself, this must be in a
351 // segment of unreachable code, so just clobber the instruction.
352 if (&I == V)
353 V = UndefValue::get(I.getType());
354
355 I.replaceAllUsesWith(V);
356 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000357 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000358
359 // EraseInstFromFunction - When dealing with an instruction that has side
360 // effects or produces a void value, we can't rely on DCE to delete the
361 // instruction. Instead, visit methods should return the value returned by
362 // this function.
363 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000364 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000365
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000366 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000367 // Make sure that we reprocess all operands now that we reduced their
368 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000369 if (I.getNumOperands() < 8) {
370 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
371 if (Instruction *Op = dyn_cast<Instruction>(*i))
372 Worklist.Add(Op);
373 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000374 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000375 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000376 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000377 return 0; // Don't do anything with FI
378 }
Chris Lattner173234a2008-06-02 01:18:21 +0000379
380 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
381 APInt &KnownOne, unsigned Depth = 0) const {
382 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
383 }
384
385 bool MaskedValueIsZero(Value *V, const APInt &Mask,
386 unsigned Depth = 0) const {
387 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
388 }
389 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
390 return llvm::ComputeNumSignBits(Op, TD, Depth);
391 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000392
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000393 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000394
Reid Spencere4d87aa2006-12-23 06:05:41 +0000395 /// SimplifyCommutative - This performs a few simplifications for
396 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000397 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000398
Chris Lattner886ab6c2009-01-31 08:15:18 +0000399 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
400 /// based on the demanded bits.
401 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
402 APInt& KnownZero, APInt& KnownOne,
403 unsigned Depth);
404 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000405 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000406 unsigned Depth=0);
407
408 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
409 /// SimplifyDemandedBits knows about. See if the instruction has any
410 /// properties that allow us to simplify its operands.
411 bool SimplifyDemandedInstructionBits(Instruction &Inst);
412
Evan Cheng388df622009-02-03 10:05:09 +0000413 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
414 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000415
Chris Lattner5d1704d2009-09-27 19:57:57 +0000416 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
417 // which has a PHI node as operand #0, see if we can fold the instruction
418 // into the PHI (which is only possible if all operands to the PHI are
419 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000420 //
421 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
422 // that would normally be unprofitable because they strongly encourage jump
423 // threading.
424 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000425
Chris Lattnerbac32862004-11-14 19:13:23 +0000426 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
427 // operator and they all are only used by the PHI, PHI together their
428 // inputs, and do the operation once, to the result of the PHI.
429 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000430 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000431 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner751a3622009-11-01 20:04:24 +0000432 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000433
Chris Lattner7da52b22006-11-01 04:51:18 +0000434
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000435 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
436 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000437
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000438 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000439 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000440 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000441 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000442 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000443 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000444 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000445 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000446 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000447
Chris Lattnerafe91a52006-06-15 19:07:26 +0000448
Reid Spencerc55b2432006-12-13 18:21:21 +0000449 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000450
Dan Gohman6de29f82009-06-15 22:12:54 +0000451 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000452 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000453 unsigned GetOrEnforceKnownAlignment(Value *V,
454 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000455
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000456 };
Chris Lattner873ff012009-08-30 05:55:36 +0000457} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000458
Dan Gohman844731a2008-05-13 00:00:25 +0000459char InstCombiner::ID = 0;
460static RegisterPass<InstCombiner>
461X("instcombine", "Combine redundant instructions");
462
Chris Lattner4f98c562003-03-10 21:43:22 +0000463// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000464// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000465static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000466 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000467 if (BinaryOperator::isNeg(V) ||
468 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000469 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000470 return 3;
471 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000472 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000473 if (isa<Argument>(V)) return 3;
474 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000475}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000476
Chris Lattnerc8802d22003-03-11 00:12:48 +0000477// isOnlyUse - Return true if this instruction will be deleted if we stop using
478// it.
479static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000480 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000481}
482
Chris Lattner4cb170c2004-02-23 06:38:22 +0000483// getPromotedType - Return the specified type promoted as it would be to pass
484// though a va_arg area...
485static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000486 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
487 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000488 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000489 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000490 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000491}
492
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000493/// ShouldChangeType - Return true if it is desirable to convert a computation
494/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
495/// type for example, or from a smaller to a larger illegal type.
496static bool ShouldChangeType(const Type *From, const Type *To,
497 const TargetData *TD) {
498 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
499
500 // If we don't have TD, we don't know if the source/dest are legal.
501 if (!TD) return false;
502
503 unsigned FromWidth = From->getPrimitiveSizeInBits();
504 unsigned ToWidth = To->getPrimitiveSizeInBits();
505 bool FromLegal = TD->isLegalInteger(FromWidth);
506 bool ToLegal = TD->isLegalInteger(ToWidth);
507
508 // If this is a legal integer from type, and the result would be an illegal
509 // type, don't do the transformation.
510 if (FromLegal && !ToLegal)
511 return false;
512
513 // Otherwise, if both are illegal, do not increase the size of the result. We
514 // do allow things like i160 -> i64, but not i64 -> i160.
515 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
516 return false;
517
518 return true;
519}
520
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000521/// getBitCastOperand - If the specified operand is a CastInst, a constant
522/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
523/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000524static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000525 if (Operator *O = dyn_cast<Operator>(V)) {
526 if (O->getOpcode() == Instruction::BitCast)
527 return O->getOperand(0);
528 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
529 if (GEP->hasAllZeroIndices())
530 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000531 }
Chris Lattnereed48272005-09-13 00:40:14 +0000532 return 0;
533}
534
Reid Spencer3da59db2006-11-27 01:05:10 +0000535/// This function is a wrapper around CastInst::isEliminableCastPair. It
536/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000537static Instruction::CastOps
538isEliminableCastPair(
539 const CastInst *CI, ///< The first cast instruction
540 unsigned opcode, ///< The opcode of the second cast instruction
541 const Type *DstTy, ///< The target type for the second cast instruction
542 TargetData *TD ///< The target data for pointer size
543) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000544
Reid Spencer3da59db2006-11-27 01:05:10 +0000545 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
546 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000547
Reid Spencer3da59db2006-11-27 01:05:10 +0000548 // Get the opcodes of the two Cast instructions
549 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
550 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000551
Chris Lattnera0e69692009-03-24 18:35:40 +0000552 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000553 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000554 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000555
556 // We don't want to form an inttoptr or ptrtoint that converts to an integer
557 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000558 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000559 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000560 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000561 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000562 Res = 0;
563
564 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000565}
566
567/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
568/// in any code being generated. It does not require codegen if V is simple
569/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000570static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
571 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000572 if (V->getType() == Ty || isa<Constant>(V)) return false;
573
Chris Lattner01575b72006-05-25 23:24:33 +0000574 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000575 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000576 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000577 return false;
578 return true;
579}
580
Chris Lattner4f98c562003-03-10 21:43:22 +0000581// SimplifyCommutative - This performs a few simplifications for commutative
582// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000583//
Chris Lattner4f98c562003-03-10 21:43:22 +0000584// 1. Order operands such that they are listed from right (least complex) to
585// left (most complex). This puts constants before unary operators before
586// binary operators.
587//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000588// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
589// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000590//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000591bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000592 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000593 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000594 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000595
Chris Lattner4f98c562003-03-10 21:43:22 +0000596 if (!I.isAssociative()) return Changed;
597 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000598 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
599 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
600 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000601 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000602 cast<Constant>(I.getOperand(1)),
603 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000604 I.setOperand(0, Op->getOperand(0));
605 I.setOperand(1, Folded);
606 return true;
607 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
608 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
609 isOnlyUse(Op) && isOnlyUse(Op1)) {
610 Constant *C1 = cast<Constant>(Op->getOperand(1));
611 Constant *C2 = cast<Constant>(Op1->getOperand(1));
612
613 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000614 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000615 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000616 Op1->getOperand(0),
617 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000618 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000619 I.setOperand(0, New);
620 I.setOperand(1, Folded);
621 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000622 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000623 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000624 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000625}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000626
Chris Lattner8d969642003-03-10 23:06:50 +0000627// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
628// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000629//
Dan Gohman186a6362009-08-12 16:04:34 +0000630static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000631 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000632 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000633
Chris Lattner0ce85802004-12-14 20:08:06 +0000634 // Constants can be considered to be negated values if they can be folded.
635 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000636 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000637
638 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
639 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000640 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000641
Chris Lattner8d969642003-03-10 23:06:50 +0000642 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000643}
644
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000645// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
646// instruction if the LHS is a constant negative zero (which is the 'negate'
647// form).
648//
Dan Gohman186a6362009-08-12 16:04:34 +0000649static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000650 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000651 return BinaryOperator::getFNegArgument(V);
652
653 // Constants can be considered to be negated values if they can be folded.
654 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000655 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000656
657 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
658 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000659 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000660
661 return 0;
662}
663
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000664/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
665/// returning the kind and providing the out parameter results if we
666/// successfully match.
667static SelectPatternFlavor
668MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
669 SelectInst *SI = dyn_cast<SelectInst>(V);
670 if (SI == 0) return SPF_UNKNOWN;
671
672 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
673 if (ICI == 0) return SPF_UNKNOWN;
674
675 LHS = ICI->getOperand(0);
676 RHS = ICI->getOperand(1);
677
678 // (icmp X, Y) ? X : Y
679 if (SI->getTrueValue() == ICI->getOperand(0) &&
680 SI->getFalseValue() == ICI->getOperand(1)) {
681 switch (ICI->getPredicate()) {
682 default: return SPF_UNKNOWN; // Equality.
683 case ICmpInst::ICMP_UGT:
684 case ICmpInst::ICMP_UGE: return SPF_UMAX;
685 case ICmpInst::ICMP_SGT:
686 case ICmpInst::ICMP_SGE: return SPF_SMAX;
687 case ICmpInst::ICMP_ULT:
688 case ICmpInst::ICMP_ULE: return SPF_UMIN;
689 case ICmpInst::ICMP_SLT:
690 case ICmpInst::ICMP_SLE: return SPF_SMIN;
691 }
692 }
693
694 // (icmp X, Y) ? Y : X
695 if (SI->getTrueValue() == ICI->getOperand(1) &&
696 SI->getFalseValue() == ICI->getOperand(0)) {
697 switch (ICI->getPredicate()) {
698 default: return SPF_UNKNOWN; // Equality.
699 case ICmpInst::ICMP_UGT:
700 case ICmpInst::ICMP_UGE: return SPF_UMIN;
701 case ICmpInst::ICMP_SGT:
702 case ICmpInst::ICMP_SGE: return SPF_SMIN;
703 case ICmpInst::ICMP_ULT:
704 case ICmpInst::ICMP_ULE: return SPF_UMAX;
705 case ICmpInst::ICMP_SLT:
706 case ICmpInst::ICMP_SLE: return SPF_SMAX;
707 }
708 }
709
710 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
711
712 return SPF_UNKNOWN;
713}
714
Chris Lattner48b59ec2009-10-26 15:40:07 +0000715/// isFreeToInvert - Return true if the specified value is free to invert (apply
716/// ~ to). This happens in cases where the ~ can be eliminated.
717static inline bool isFreeToInvert(Value *V) {
718 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000719 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000720 return true;
721
722 // Constants can be considered to be not'ed values.
723 if (isa<ConstantInt>(V))
724 return true;
725
726 // Compares can be inverted if they have a single use.
727 if (CmpInst *CI = dyn_cast<CmpInst>(V))
728 return CI->hasOneUse();
729
730 return false;
731}
732
733static inline Value *dyn_castNotVal(Value *V) {
734 // If this is not(not(x)) don't return that this is a not: we want the two
735 // not's to be folded first.
736 if (BinaryOperator::isNot(V)) {
737 Value *Operand = BinaryOperator::getNotArgument(V);
738 if (!isFreeToInvert(Operand))
739 return Operand;
740 }
Chris Lattner8d969642003-03-10 23:06:50 +0000741
742 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000743 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000744 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000745 return 0;
746}
747
Chris Lattner48b59ec2009-10-26 15:40:07 +0000748
749
Chris Lattnerc8802d22003-03-11 00:12:48 +0000750// dyn_castFoldableMul - If this value is a multiply that can be folded into
751// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000752// non-constant operand of the multiply, and set CST to point to the multiplier.
753// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000754//
Dan Gohman186a6362009-08-12 16:04:34 +0000755static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000756 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000757 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000758 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000759 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000760 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000761 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000762 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000763 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000764 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000765 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000766 CST = ConstantInt::get(V->getType()->getContext(),
767 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000768 return I->getOperand(0);
769 }
770 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000771 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000772}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000773
Reid Spencer7177c3a2007-03-25 05:33:51 +0000774/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000775static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000776 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000777 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000778}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000779/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000780static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000781 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000782 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000783}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000784/// MultiplyOverflows - True if the multiply can not be expressed in an int
785/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000786static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000787 uint32_t W = C1->getBitWidth();
788 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
789 if (sign) {
790 LHSExt.sext(W * 2);
791 RHSExt.sext(W * 2);
792 } else {
793 LHSExt.zext(W * 2);
794 RHSExt.zext(W * 2);
795 }
796
797 APInt MulExt = LHSExt * RHSExt;
798
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000799 if (!sign)
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000800 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000801
802 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
803 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
804 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000805}
Chris Lattner955f3312004-09-28 21:48:02 +0000806
Reid Spencere7816b52007-03-08 01:52:58 +0000807
Chris Lattner255d8912006-02-11 09:31:47 +0000808/// ShrinkDemandedConstant - Check to see if the specified operand of the
809/// specified instruction is a constant integer. If so, check to see if there
810/// are any bits set in the constant that are not demanded. If so, shrink the
811/// constant and return true.
812static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000813 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000814 assert(I && "No instruction?");
815 assert(OpNo < I->getNumOperands() && "Operand index too large");
816
817 // If the operand is not a constant integer, nothing to do.
818 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
819 if (!OpC) return false;
820
821 // If there are no bits set that aren't demanded, nothing to do.
822 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
823 if ((~Demanded & OpC->getValue()) == 0)
824 return false;
825
826 // This instruction is producing bits that are not demanded. Shrink the RHS.
827 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000828 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000829 return true;
830}
831
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000832// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
833// set of known zero and one bits, compute the maximum and minimum values that
834// could have the specified known zero and known one bits, returning them in
835// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000836static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000837 const APInt& KnownOne,
838 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000839 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
840 KnownZero.getBitWidth() == Min.getBitWidth() &&
841 KnownZero.getBitWidth() == Max.getBitWidth() &&
842 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000843 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000844
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000845 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
846 // bit if it is unknown.
847 Min = KnownOne;
848 Max = KnownOne|UnknownBits;
849
Dan Gohman1c8491e2009-04-25 17:12:48 +0000850 if (UnknownBits.isNegative()) { // Sign bit is unknown
851 Min.set(Min.getBitWidth()-1);
852 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000853 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000854}
855
856// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
857// a set of known zero and one bits, compute the maximum and minimum values that
858// could have the specified known zero and known one bits, returning them in
859// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000860static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000861 const APInt &KnownOne,
862 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000863 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
864 KnownZero.getBitWidth() == Min.getBitWidth() &&
865 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000866 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000867 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000868
869 // The minimum value is when the unknown bits are all zeros.
870 Min = KnownOne;
871 // The maximum value is when the unknown bits are all ones.
872 Max = KnownOne|UnknownBits;
873}
Chris Lattner255d8912006-02-11 09:31:47 +0000874
Chris Lattner886ab6c2009-01-31 08:15:18 +0000875/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
876/// SimplifyDemandedBits knows about. See if the instruction has any
877/// properties that allow us to simplify its operands.
878bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000879 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000880 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
881 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
882
883 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
884 KnownZero, KnownOne, 0);
885 if (V == 0) return false;
886 if (V == &Inst) return true;
887 ReplaceInstUsesWith(Inst, V);
888 return true;
889}
890
891/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
892/// specified instruction operand if possible, updating it in place. It returns
893/// true if it made any change and false otherwise.
894bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
895 APInt &KnownZero, APInt &KnownOne,
896 unsigned Depth) {
897 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
898 KnownZero, KnownOne, Depth);
899 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000900 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000901 return true;
902}
903
904
905/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
906/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000907/// that only the bits set in DemandedMask of the result of V are ever used
908/// downstream. Consequently, depending on the mask and V, it may be possible
909/// to replace V with a constant or one of its operands. In such cases, this
910/// function does the replacement and returns true. In all other cases, it
911/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000912/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000913/// to be zero in the expression. These are provided to potentially allow the
914/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
915/// the expression. KnownOne and KnownZero always follow the invariant that
916/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
917/// the bits in KnownOne and KnownZero may only be accurate for those bits set
918/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
919/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000920///
921/// This returns null if it did not change anything and it permits no
922/// simplification. This returns V itself if it did some simplification of V's
923/// operands based on the information about what bits are demanded. This returns
924/// some other non-null value if it found out that V is equal to another value
925/// in the context where the specified bits are demanded, but not for all users.
926Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
927 APInt &KnownZero, APInt &KnownOne,
928 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000929 assert(V != 0 && "Null pointer of Value???");
930 assert(Depth <= 6 && "Limit Search Depth");
931 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000932 const Type *VTy = V->getType();
933 assert((TD || !isa<PointerType>(VTy)) &&
934 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000935 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
936 (!VTy->isIntOrIntVector() ||
937 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000938 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000939 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000940 "Value *V, DemandedMask, KnownZero and KnownOne "
941 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000942 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
943 // We know all of the bits for a constant!
944 KnownOne = CI->getValue() & DemandedMask;
945 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000946 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000947 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000948 if (isa<ConstantPointerNull>(V)) {
949 // We know all of the bits for a constant!
950 KnownOne.clear();
951 KnownZero = DemandedMask;
952 return 0;
953 }
954
Chris Lattner08d2cc72009-01-31 07:26:06 +0000955 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000956 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000957 if (DemandedMask == 0) { // Not demanding any bits from V.
958 if (isa<UndefValue>(V))
959 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000960 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000961 }
962
Chris Lattner4598c942009-01-31 08:24:16 +0000963 if (Depth == 6) // Limit search depth.
964 return 0;
965
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000966 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
967 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
968
Dan Gohman1c8491e2009-04-25 17:12:48 +0000969 Instruction *I = dyn_cast<Instruction>(V);
970 if (!I) {
971 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
972 return 0; // Only analyze instructions.
973 }
974
Chris Lattner4598c942009-01-31 08:24:16 +0000975 // If there are multiple uses of this value and we aren't at the root, then
976 // we can't do any simplifications of the operands, because DemandedMask
977 // only reflects the bits demanded by *one* of the users.
978 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000979 // Despite the fact that we can't simplify this instruction in all User's
980 // context, we can at least compute the knownzero/knownone bits, and we can
981 // do simplifications that apply to *just* the one user if we know that
982 // this instruction has a simpler value in that context.
983 if (I->getOpcode() == Instruction::And) {
984 // If either the LHS or the RHS are Zero, the result is zero.
985 ComputeMaskedBits(I->getOperand(1), DemandedMask,
986 RHSKnownZero, RHSKnownOne, Depth+1);
987 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
988 LHSKnownZero, LHSKnownOne, Depth+1);
989
990 // If all of the demanded bits are known 1 on one side, return the other.
991 // These bits cannot contribute to the result of the 'and' in this
992 // context.
993 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
994 (DemandedMask & ~LHSKnownZero))
995 return I->getOperand(0);
996 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
997 (DemandedMask & ~RHSKnownZero))
998 return I->getOperand(1);
999
1000 // If all of the demanded bits in the inputs are known zeros, return zero.
1001 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +00001002 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +00001003
1004 } else if (I->getOpcode() == Instruction::Or) {
1005 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1006 // only bits from X or Y are demanded.
1007
1008 // If either the LHS or the RHS are One, the result is One.
1009 ComputeMaskedBits(I->getOperand(1), DemandedMask,
1010 RHSKnownZero, RHSKnownOne, Depth+1);
1011 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1012 LHSKnownZero, LHSKnownOne, Depth+1);
1013
1014 // If all of the demanded bits are known zero on one side, return the
1015 // other. These bits cannot contribute to the result of the 'or' in this
1016 // context.
1017 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1018 (DemandedMask & ~LHSKnownOne))
1019 return I->getOperand(0);
1020 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1021 (DemandedMask & ~RHSKnownOne))
1022 return I->getOperand(1);
1023
1024 // If all of the potentially set bits on one side are known to be set on
1025 // the other side, just use the 'other' side.
1026 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1027 (DemandedMask & (~RHSKnownZero)))
1028 return I->getOperand(0);
1029 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1030 (DemandedMask & (~LHSKnownZero)))
1031 return I->getOperand(1);
1032 }
1033
Chris Lattner4598c942009-01-31 08:24:16 +00001034 // Compute the KnownZero/KnownOne bits to simplify things downstream.
1035 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
1036 return 0;
1037 }
1038
1039 // If this is the root being simplified, allow it to have multiple uses,
1040 // just set the DemandedMask to all bits so that we can try to simplify the
1041 // operands. This allows visitTruncInst (for example) to simplify the
1042 // operand of a trunc without duplicating all the logic below.
1043 if (Depth == 0 && !V->hasOneUse())
1044 DemandedMask = APInt::getAllOnesValue(BitWidth);
1045
Reid Spencer8cb68342007-03-12 17:25:59 +00001046 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001047 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001048 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +00001049 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001050 case Instruction::And:
1051 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001052 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1053 RHSKnownZero, RHSKnownOne, Depth+1) ||
1054 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +00001055 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 return I;
1057 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1058 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001059
1060 // If all of the demanded bits are known 1 on one side, return the other.
1061 // These bits cannot contribute to the result of the 'and'.
1062 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1063 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001064 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001065 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1066 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001068
1069 // If all of the demanded bits in the inputs are known zeros, return zero.
1070 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +00001071 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +00001072
1073 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001074 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001075 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001076
1077 // Output known-1 bits are only known if set in both the LHS & RHS.
1078 RHSKnownOne &= LHSKnownOne;
1079 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1080 RHSKnownZero |= LHSKnownZero;
1081 break;
1082 case Instruction::Or:
1083 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001084 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1085 RHSKnownZero, RHSKnownOne, Depth+1) ||
1086 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +00001087 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001088 return I;
1089 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1090 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001091
1092 // If all of the demanded bits are known zero on one side, return the other.
1093 // These bits cannot contribute to the result of the 'or'.
1094 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1095 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001096 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1098 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001099 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001100
1101 // If all of the potentially set bits on one side are known to be set on
1102 // the other side, just use the 'other' side.
1103 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1104 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001105 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001106 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1107 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001108 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001109
1110 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001111 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001112 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001113
1114 // Output known-0 bits are only known if clear in both the LHS & RHS.
1115 RHSKnownZero &= LHSKnownZero;
1116 // Output known-1 are known to be set if set in either the LHS | RHS.
1117 RHSKnownOne |= LHSKnownOne;
1118 break;
1119 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001120 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1121 RHSKnownZero, RHSKnownOne, Depth+1) ||
1122 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001123 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001124 return I;
1125 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1126 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001127
1128 // If all of the demanded bits are known zero on one side, return the other.
1129 // These bits cannot contribute to the result of the 'xor'.
1130 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001131 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001132 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001133 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001134
1135 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1136 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1137 (RHSKnownOne & LHSKnownOne);
1138 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1139 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1140 (RHSKnownOne & LHSKnownZero);
1141
1142 // If all of the demanded bits are known to be zero on one side or the
1143 // other, turn this into an *inclusive* or.
1144 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001145 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1146 Instruction *Or =
1147 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1148 I->getName());
1149 return InsertNewInstBefore(Or, *I);
1150 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001151
1152 // If all of the demanded bits on one side are known, and all of the set
1153 // bits on that side are also known to be set on the other side, turn this
1154 // into an AND, as we know the bits will be cleared.
1155 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1156 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1157 // all known
1158 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001159 Constant *AndC = Constant::getIntegerValue(VTy,
1160 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001161 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001162 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001163 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001164 }
1165 }
1166
1167 // If the RHS is a constant, see if we can simplify it.
1168 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001169 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001170 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001171
Chris Lattnerd0883142009-10-11 22:22:13 +00001172 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1173 // are flipping are known to be set, then the xor is just resetting those
1174 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1175 // simplifying both of them.
1176 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1177 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1178 isa<ConstantInt>(I->getOperand(1)) &&
1179 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1180 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1181 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1182 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1183 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1184
1185 Constant *AndC =
1186 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1187 Instruction *NewAnd =
1188 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1189 InsertNewInstBefore(NewAnd, *I);
1190
1191 Constant *XorC =
1192 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1193 Instruction *NewXor =
1194 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1195 return InsertNewInstBefore(NewXor, *I);
1196 }
1197
1198
Reid Spencer8cb68342007-03-12 17:25:59 +00001199 RHSKnownZero = KnownZeroOut;
1200 RHSKnownOne = KnownOneOut;
1201 break;
1202 }
1203 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001204 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1205 RHSKnownZero, RHSKnownOne, Depth+1) ||
1206 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001207 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001208 return I;
1209 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1210 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001211
1212 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001213 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1214 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001215 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001216
1217 // Only known if known in both the LHS and RHS.
1218 RHSKnownOne &= LHSKnownOne;
1219 RHSKnownZero &= LHSKnownZero;
1220 break;
1221 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001222 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001223 DemandedMask.zext(truncBf);
1224 RHSKnownZero.zext(truncBf);
1225 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001226 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001227 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001228 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001229 DemandedMask.trunc(BitWidth);
1230 RHSKnownZero.trunc(BitWidth);
1231 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001232 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001233 break;
1234 }
1235 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001236 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001237 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001238
1239 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1240 if (const VectorType *SrcVTy =
1241 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1242 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1243 // Don't touch a bitcast between vectors of different element counts.
1244 return false;
1245 } else
1246 // Don't touch a scalar-to-vector bitcast.
1247 return false;
1248 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1249 // Don't touch a vector-to-scalar bitcast.
1250 return false;
1251
Chris Lattner886ab6c2009-01-31 08:15:18 +00001252 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001253 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001254 return I;
1255 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001256 break;
1257 case Instruction::ZExt: {
1258 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001259 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001260
Zhou Shengd48653a2007-03-29 04:45:55 +00001261 DemandedMask.trunc(SrcBitWidth);
1262 RHSKnownZero.trunc(SrcBitWidth);
1263 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001264 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001265 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001266 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 DemandedMask.zext(BitWidth);
1268 RHSKnownZero.zext(BitWidth);
1269 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001270 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001271 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001272 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 break;
1274 }
1275 case Instruction::SExt: {
1276 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001277 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001278
Reid Spencer8cb68342007-03-12 17:25:59 +00001279 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001280 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001281
Zhou Sheng01542f32007-03-29 02:26:30 +00001282 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001283 // If any of the sign extended bits are demanded, we know that the sign
1284 // bit is demanded.
1285 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001286 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001287
Zhou Shengd48653a2007-03-29 04:45:55 +00001288 InputDemandedBits.trunc(SrcBitWidth);
1289 RHSKnownZero.trunc(SrcBitWidth);
1290 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001291 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001292 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001293 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001294 InputDemandedBits.zext(BitWidth);
1295 RHSKnownZero.zext(BitWidth);
1296 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001297 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001298
1299 // If the sign bit of the input is known set or clear, then we know the
1300 // top bits of the result.
1301
1302 // If the input sign bit is known zero, or if the NewBits are not demanded
1303 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001304 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001305 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001306 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1307 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001308 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001309 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 }
1311 break;
1312 }
1313 case Instruction::Add: {
1314 // Figure out what the input bits are. If the top bits of the and result
1315 // are not demanded, then the add doesn't demand them from its input
1316 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001317 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001318
1319 // If there is a constant on the RHS, there are a variety of xformations
1320 // we can do.
1321 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1322 // If null, this should be simplified elsewhere. Some of the xforms here
1323 // won't work if the RHS is zero.
1324 if (RHS->isZero())
1325 break;
1326
1327 // If the top bit of the output is demanded, demand everything from the
1328 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001329 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001330
1331 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001332 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001333 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001334 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001335
1336 // If the RHS of the add has bits set that can't affect the input, reduce
1337 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001338 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001339 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001340
1341 // Avoid excess work.
1342 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1343 break;
1344
1345 // Turn it into OR if input bits are zero.
1346 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1347 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001348 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001349 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001350 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001351 }
1352
1353 // We can say something about the output known-zero and known-one bits,
1354 // depending on potential carries from the input constant and the
1355 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1356 // bits set and the RHS constant is 0x01001, then we know we have a known
1357 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1358
1359 // To compute this, we first compute the potential carry bits. These are
1360 // the bits which may be modified. I'm not aware of a better way to do
1361 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001362 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001363 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001364
1365 // Now that we know which bits have carries, compute the known-1/0 sets.
1366
1367 // Bits are known one if they are known zero in one operand and one in the
1368 // other, and there is no input carry.
1369 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1370 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1371
1372 // Bits are known zero if they are known zero in both operands and there
1373 // is no input carry.
1374 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1375 } else {
1376 // If the high-bits of this ADD are not demanded, then it does not demand
1377 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001378 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001379 // Right fill the mask of bits for this ADD to demand the most
1380 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001381 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001382 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1383 LHSKnownZero, LHSKnownOne, Depth+1) ||
1384 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001385 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001386 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001387 }
1388 }
1389 break;
1390 }
1391 case Instruction::Sub:
1392 // If the high-bits of this SUB are not demanded, then it does not demand
1393 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001394 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001395 // Right fill the mask of bits for this SUB to demand the most
1396 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001397 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001398 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001399 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1400 LHSKnownZero, LHSKnownOne, Depth+1) ||
1401 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001402 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001403 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001404 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001405 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1406 // the known zeros and ones.
1407 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001408 break;
1409 case Instruction::Shl:
1410 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001411 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001412 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001413 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001414 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001415 return I;
1416 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001417 RHSKnownZero <<= ShiftAmt;
1418 RHSKnownOne <<= ShiftAmt;
1419 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001420 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001421 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001422 }
1423 break;
1424 case Instruction::LShr:
1425 // For a logical shift right
1426 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001427 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001428
Reid Spencer8cb68342007-03-12 17:25:59 +00001429 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001430 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001431 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001432 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001433 return I;
1434 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001435 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1436 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001437 if (ShiftAmt) {
1438 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001439 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001440 RHSKnownZero |= HighBits; // high bits known zero.
1441 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001442 }
1443 break;
1444 case Instruction::AShr:
1445 // If this is an arithmetic shift right and only the low-bit is set, we can
1446 // always convert this into a logical shr, even if the shift amount is
1447 // variable. The low bit of the shift cannot be an input sign bit unless
1448 // the shift amount is >= the size of the datatype, which is undefined.
1449 if (DemandedMask == 1) {
1450 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001451 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001452 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001453 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001454 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001455
1456 // If the sign bit is the only bit demanded by this ashr, then there is no
1457 // need to do it, the shift doesn't change the high bit.
1458 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001459 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001460
1461 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001462 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001463
Reid Spencer8cb68342007-03-12 17:25:59 +00001464 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001465 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001466 // If any of the "high bits" are demanded, we should set the sign bit as
1467 // demanded.
1468 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1469 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001470 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001471 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001472 return I;
1473 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001474 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001475 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001476 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1477 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1478
1479 // Handle the sign bits.
1480 APInt SignBit(APInt::getSignBit(BitWidth));
1481 // Adjust to where it is now in the mask.
1482 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1483
1484 // If the input sign bit is known to be zero, or if none of the top bits
1485 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001486 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001487 (HighBits & ~DemandedMask) == HighBits) {
1488 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001489 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001490 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001491 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001492 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1493 RHSKnownOne |= HighBits;
1494 }
1495 }
1496 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001497 case Instruction::SRem:
1498 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001499 APInt RA = Rem->getValue().abs();
1500 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001501 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001502 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001503
Nick Lewycky8e394322008-11-02 02:41:50 +00001504 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001505 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001506 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001507 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001508 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001509
1510 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1511 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001512
1513 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001514
Chris Lattner886ab6c2009-01-31 08:15:18 +00001515 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001516 }
1517 }
1518 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001519 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001520 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1521 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001522 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1523 KnownZero2, KnownOne2, Depth+1) ||
1524 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001525 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001526 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001527
Chris Lattner455e9ab2009-01-21 18:09:24 +00001528 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001529 Leaders = std::max(Leaders,
1530 KnownZero2.countLeadingOnes());
1531 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001532 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001533 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001534 case Instruction::Call:
1535 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1536 switch (II->getIntrinsicID()) {
1537 default: break;
1538 case Intrinsic::bswap: {
1539 // If the only bits demanded come from one byte of the bswap result,
1540 // just shift the input byte into position to eliminate the bswap.
1541 unsigned NLZ = DemandedMask.countLeadingZeros();
1542 unsigned NTZ = DemandedMask.countTrailingZeros();
1543
1544 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1545 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1546 // have 14 leading zeros, round to 8.
1547 NLZ &= ~7;
1548 NTZ &= ~7;
1549 // If we need exactly one byte, we can do this transformation.
1550 if (BitWidth-NLZ-NTZ == 8) {
1551 unsigned ResultBit = NTZ;
1552 unsigned InputBit = BitWidth-NTZ-8;
1553
1554 // Replace this with either a left or right shift to get the byte into
1555 // the right place.
1556 Instruction *NewVal;
1557 if (InputBit > ResultBit)
1558 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001559 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001560 else
1561 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001562 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001563 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001564 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001565 }
1566
1567 // TODO: Could compute known zero/one bits based on the input.
1568 break;
1569 }
1570 }
1571 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001572 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001573 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001574 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001575
1576 // If the client is only demanding bits that we know, return the known
1577 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001578 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1579 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001580 return false;
1581}
1582
Chris Lattner867b99f2006-10-05 06:55:50 +00001583
Mon P Wangaeb06d22008-11-10 04:46:22 +00001584/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001585/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001586/// actually used by the caller. This method analyzes which elements of the
1587/// operand are undef and returns that information in UndefElts.
1588///
1589/// If the information about demanded elements can be used to simplify the
1590/// operation, the operation is simplified, then the resultant value is
1591/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001592Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1593 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001594 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001595 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001596 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001597 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001598
1599 if (isa<UndefValue>(V)) {
1600 // If the entire vector is undefined, just return this info.
1601 UndefElts = EltMask;
1602 return 0;
1603 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1604 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001605 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001606 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001607
Chris Lattner867b99f2006-10-05 06:55:50 +00001608 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001609 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1610 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001611 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001612
1613 std::vector<Constant*> Elts;
1614 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001615 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001616 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001617 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001618 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1619 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001620 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001621 } else { // Otherwise, defined.
1622 Elts.push_back(CP->getOperand(i));
1623 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001624
Chris Lattner867b99f2006-10-05 06:55:50 +00001625 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001626 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001627 return NewCP != CP ? NewCP : 0;
1628 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001629 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001630 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001631
1632 // Check if this is identity. If so, return 0 since we are not simplifying
1633 // anything.
1634 if (DemandedElts == ((1ULL << VWidth) -1))
1635 return 0;
1636
Reid Spencer9d6565a2007-02-15 02:26:10 +00001637 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001638 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001639 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001640 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001641 for (unsigned i = 0; i != VWidth; ++i) {
1642 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1643 Elts.push_back(Elt);
1644 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001645 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001646 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001647 }
1648
Dan Gohman488fbfc2008-09-09 18:11:14 +00001649 // Limit search depth.
1650 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001651 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001652
1653 // If multiple users are using the root value, procede with
1654 // simplification conservatively assuming that all elements
1655 // are needed.
1656 if (!V->hasOneUse()) {
1657 // Quit if we find multiple users of a non-root value though.
1658 // They'll be handled when it's their turn to be visited by
1659 // the main instcombine process.
1660 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001661 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001662 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001663
1664 // Conservatively assume that all elements are needed.
1665 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001666 }
1667
1668 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001669 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001670
1671 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001672 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001673 Value *TmpV;
1674 switch (I->getOpcode()) {
1675 default: break;
1676
1677 case Instruction::InsertElement: {
1678 // If this is a variable index, we don't know which element it overwrites.
1679 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001680 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001681 if (Idx == 0) {
1682 // Note that we can't propagate undef elt info, because we don't know
1683 // which elt is getting updated.
1684 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1685 UndefElts2, Depth+1);
1686 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1687 break;
1688 }
1689
1690 // If this is inserting an element that isn't demanded, remove this
1691 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001692 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001693 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1694 Worklist.Add(I);
1695 return I->getOperand(0);
1696 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001697
1698 // Otherwise, the element inserted overwrites whatever was there, so the
1699 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001700 APInt DemandedElts2 = DemandedElts;
1701 DemandedElts2.clear(IdxNo);
1702 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001703 UndefElts, Depth+1);
1704 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1705
1706 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001707 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001708 break;
1709 }
1710 case Instruction::ShuffleVector: {
1711 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001712 uint64_t LHSVWidth =
1713 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001714 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001715 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001716 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001717 unsigned MaskVal = Shuffle->getMaskValue(i);
1718 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001719 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001720 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001721 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001722 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001723 else
Evan Cheng388df622009-02-03 10:05:09 +00001724 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001725 }
1726 }
1727 }
1728
Nate Begeman7b254672009-02-11 22:36:25 +00001729 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001730 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001731 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001732 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1733
Nate Begeman7b254672009-02-11 22:36:25 +00001734 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001735 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1736 UndefElts3, Depth+1);
1737 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1738
1739 bool NewUndefElts = false;
1740 for (unsigned i = 0; i < VWidth; i++) {
1741 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001742 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001743 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001744 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001745 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001746 NewUndefElts = true;
1747 UndefElts.set(i);
1748 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001749 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001750 if (UndefElts3[MaskVal - LHSVWidth]) {
1751 NewUndefElts = true;
1752 UndefElts.set(i);
1753 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001754 }
1755 }
1756
1757 if (NewUndefElts) {
1758 // Add additional discovered undefs.
1759 std::vector<Constant*> Elts;
1760 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001761 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001762 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001763 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001764 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001765 Shuffle->getMaskValue(i)));
1766 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001767 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001768 MadeChange = true;
1769 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001770 break;
1771 }
Chris Lattner69878332007-04-14 22:29:23 +00001772 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001773 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001774 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1775 if (!VTy) break;
1776 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001777 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001778 unsigned Ratio;
1779
1780 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001781 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001782 // elements as are demanded of us.
1783 Ratio = 1;
1784 InputDemandedElts = DemandedElts;
1785 } else if (VWidth > InVWidth) {
1786 // Untested so far.
1787 break;
1788
1789 // If there are more elements in the result than there are in the source,
1790 // then an input element is live if any of the corresponding output
1791 // elements are live.
1792 Ratio = VWidth/InVWidth;
1793 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001794 if (DemandedElts[OutIdx])
1795 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001796 }
1797 } else {
1798 // Untested so far.
1799 break;
1800
1801 // If there are more elements in the source than there are in the result,
1802 // then an input element is live if the corresponding output element is
1803 // live.
1804 Ratio = InVWidth/VWidth;
1805 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001806 if (DemandedElts[InIdx/Ratio])
1807 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001808 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001809
Chris Lattner69878332007-04-14 22:29:23 +00001810 // div/rem demand all inputs, because they don't want divide by zero.
1811 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1812 UndefElts2, Depth+1);
1813 if (TmpV) {
1814 I->setOperand(0, TmpV);
1815 MadeChange = true;
1816 }
1817
1818 UndefElts = UndefElts2;
1819 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001820 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001821 // If there are more elements in the result than there are in the source,
1822 // then an output element is undef if the corresponding input element is
1823 // undef.
1824 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001825 if (UndefElts2[OutIdx/Ratio])
1826 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001827 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001828 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001829 // If there are more elements in the source than there are in the result,
1830 // then a result element is undef if all of the corresponding input
1831 // elements are undef.
1832 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1833 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001834 if (!UndefElts2[InIdx]) // Not undef?
1835 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001836 }
1837 break;
1838 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001839 case Instruction::And:
1840 case Instruction::Or:
1841 case Instruction::Xor:
1842 case Instruction::Add:
1843 case Instruction::Sub:
1844 case Instruction::Mul:
1845 // div/rem demand all inputs, because they don't want divide by zero.
1846 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1847 UndefElts, Depth+1);
1848 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1849 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1850 UndefElts2, Depth+1);
1851 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1852
1853 // Output elements are undefined if both are undefined. Consider things
1854 // like undef&0. The result is known zero, not undef.
1855 UndefElts &= UndefElts2;
1856 break;
1857
1858 case Instruction::Call: {
1859 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1860 if (!II) break;
1861 switch (II->getIntrinsicID()) {
1862 default: break;
1863
1864 // Binary vector operations that work column-wise. A dest element is a
1865 // function of the corresponding input elements from the two inputs.
1866 case Intrinsic::x86_sse_sub_ss:
1867 case Intrinsic::x86_sse_mul_ss:
1868 case Intrinsic::x86_sse_min_ss:
1869 case Intrinsic::x86_sse_max_ss:
1870 case Intrinsic::x86_sse2_sub_sd:
1871 case Intrinsic::x86_sse2_mul_sd:
1872 case Intrinsic::x86_sse2_min_sd:
1873 case Intrinsic::x86_sse2_max_sd:
1874 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1875 UndefElts, Depth+1);
1876 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1877 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1878 UndefElts2, Depth+1);
1879 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1880
1881 // If only the low elt is demanded and this is a scalarizable intrinsic,
1882 // scalarize it now.
1883 if (DemandedElts == 1) {
1884 switch (II->getIntrinsicID()) {
1885 default: break;
1886 case Intrinsic::x86_sse_sub_ss:
1887 case Intrinsic::x86_sse_mul_ss:
1888 case Intrinsic::x86_sse2_sub_sd:
1889 case Intrinsic::x86_sse2_mul_sd:
1890 // TODO: Lower MIN/MAX/ABS/etc
1891 Value *LHS = II->getOperand(1);
1892 Value *RHS = II->getOperand(2);
1893 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001894 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001895 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001896 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001897 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001898
1899 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001900 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001901 case Intrinsic::x86_sse_sub_ss:
1902 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001903 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001904 II->getName()), *II);
1905 break;
1906 case Intrinsic::x86_sse_mul_ss:
1907 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001908 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001909 II->getName()), *II);
1910 break;
1911 }
1912
1913 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001914 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001915 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001916 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001917 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001918 return New;
1919 }
1920 }
1921
1922 // Output elements are undefined if both are undefined. Consider things
1923 // like undef&0. The result is known zero, not undef.
1924 UndefElts &= UndefElts2;
1925 break;
1926 }
1927 break;
1928 }
1929 }
1930 return MadeChange ? I : 0;
1931}
1932
Dan Gohman45b4e482008-05-19 22:14:15 +00001933
Chris Lattner564a7272003-08-13 19:01:45 +00001934/// AssociativeOpt - Perform an optimization on an associative operator. This
1935/// function is designed to check a chain of associative operators for a
1936/// potential to apply a certain optimization. Since the optimization may be
1937/// applicable if the expression was reassociated, this checks the chain, then
1938/// reassociates the expression as necessary to expose the optimization
1939/// opportunity. This makes use of a special Functor, which must define
1940/// 'shouldApply' and 'apply' methods.
1941///
1942template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001943static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001944 unsigned Opcode = Root.getOpcode();
1945 Value *LHS = Root.getOperand(0);
1946
1947 // Quick check, see if the immediate LHS matches...
1948 if (F.shouldApply(LHS))
1949 return F.apply(Root);
1950
1951 // Otherwise, if the LHS is not of the same opcode as the root, return.
1952 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001953 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001954 // Should we apply this transform to the RHS?
1955 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1956
1957 // If not to the RHS, check to see if we should apply to the LHS...
1958 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1959 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1960 ShouldApply = true;
1961 }
1962
1963 // If the functor wants to apply the optimization to the RHS of LHSI,
1964 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1965 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001966 // Now all of the instructions are in the current basic block, go ahead
1967 // and perform the reassociation.
1968 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1969
1970 // First move the selected RHS to the LHS of the root...
1971 Root.setOperand(0, LHSI->getOperand(1));
1972
1973 // Make what used to be the LHS of the root be the user of the root...
1974 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001975 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001976 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001977 return 0;
1978 }
Chris Lattner65725312004-04-16 18:08:07 +00001979 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001980 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001981 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001982 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001983 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001984
1985 // Now propagate the ExtraOperand down the chain of instructions until we
1986 // get to LHSI.
1987 while (TmpLHSI != LHSI) {
1988 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001989 // Move the instruction to immediately before the chain we are
1990 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001991 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001992 ARI = NextLHSI;
1993
Chris Lattner564a7272003-08-13 19:01:45 +00001994 Value *NextOp = NextLHSI->getOperand(1);
1995 NextLHSI->setOperand(1, ExtraOperand);
1996 TmpLHSI = NextLHSI;
1997 ExtraOperand = NextOp;
1998 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001999
Chris Lattner564a7272003-08-13 19:01:45 +00002000 // Now that the instructions are reassociated, have the functor perform
2001 // the transformation...
2002 return F.apply(Root);
2003 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002004
Chris Lattner564a7272003-08-13 19:01:45 +00002005 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2006 }
2007 return 0;
2008}
2009
Dan Gohman844731a2008-05-13 00:00:25 +00002010namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002011
Nick Lewycky02d639f2008-05-23 04:34:58 +00002012// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00002013struct AddRHS {
2014 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00002015 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00002016 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2017 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00002018 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00002019 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002020 }
2021};
2022
2023// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2024// iff C1&C2 == 0
2025struct AddMaskingAnd {
2026 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00002027 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00002028 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002029 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00002030 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002031 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002032 }
2033 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002034 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002035 }
2036};
2037
Dan Gohman844731a2008-05-13 00:00:25 +00002038}
2039
Chris Lattner6e7ba452005-01-01 16:22:27 +00002040static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002041 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00002042 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00002043 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00002044
Chris Lattner2eefe512004-04-09 19:05:30 +00002045 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002046 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2047 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002048
Chris Lattner2eefe512004-04-09 19:05:30 +00002049 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2050 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00002051 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2052 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002053 }
2054
2055 Value *Op0 = SO, *Op1 = ConstOperand;
2056 if (!ConstIsRHS)
2057 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00002058
Chris Lattner6e7ba452005-01-01 16:22:27 +00002059 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00002060 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
2061 SO->getName()+".op");
2062 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
2063 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2064 SO->getName()+".cmp");
2065 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2066 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2067 SO->getName()+".cmp");
2068 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00002069}
2070
2071// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2072// constant as the other operand, try to fold the binary operator into the
2073// select arguments. This also works for Cast instructions, which obviously do
2074// not have a second operand.
2075static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2076 InstCombiner *IC) {
2077 // Don't modify shared select instructions
2078 if (!SI->hasOneUse()) return 0;
2079 Value *TV = SI->getOperand(1);
2080 Value *FV = SI->getOperand(2);
2081
2082 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002083 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00002084 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002085
Chris Lattner6e7ba452005-01-01 16:22:27 +00002086 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2087 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2088
Gabor Greif051a9502008-04-06 20:25:17 +00002089 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2090 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002091 }
2092 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002093}
2094
Chris Lattner4e998b22004-09-29 05:07:12 +00002095
Chris Lattner5d1704d2009-09-27 19:57:57 +00002096/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2097/// has a PHI node as operand #0, see if we can fold the instruction into the
2098/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002099///
2100/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2101/// that would normally be unprofitable because they strongly encourage jump
2102/// threading.
2103Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2104 bool AllowAggressive) {
2105 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002106 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002107 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002108 if (NumPHIValues == 0 ||
2109 // We normally only transform phis with a single use, unless we're trying
2110 // hard to make jump threading happen.
2111 (!PN->hasOneUse() && !AllowAggressive))
2112 return 0;
2113
2114
Chris Lattner5d1704d2009-09-27 19:57:57 +00002115 // Check to see if all of the operands of the PHI are simple constants
2116 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002117 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2118 // bail out. We don't do arbitrary constant expressions here because moving
2119 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002120 BasicBlock *NonConstBB = 0;
2121 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002122 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2123 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002124 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002125 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002126 NonConstBB = PN->getIncomingBlock(i);
2127
2128 // If the incoming non-constant value is in I's block, we have an infinite
2129 // loop.
2130 if (NonConstBB == I.getParent())
2131 return 0;
2132 }
2133
2134 // If there is exactly one non-constant value, we can insert a copy of the
2135 // operation in that block. However, if this is a critical edge, we would be
2136 // inserting the computation one some other paths (e.g. inside a loop). Only
2137 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002138 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002139 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2140 if (!BI || !BI->isUnconditional()) return 0;
2141 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002142
2143 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002144 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002145 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002146 InsertNewInstBefore(NewPN, *PN);
2147 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002148
2149 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002150 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2151 // We only currently try to fold the condition of a select when it is a phi,
2152 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002153 Value *TrueV = SI->getTrueValue();
2154 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002155 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002156 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002157 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002158 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2159 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002160 Value *InV = 0;
2161 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002162 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002163 } else {
2164 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002165 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2166 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002167 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002168 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002169 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002170 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002171 }
2172 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002173 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002174 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002175 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002176 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002177 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002178 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002179 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002180 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002181 } else {
2182 assert(PN->getIncomingBlock(i) == NonConstBB);
2183 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002184 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002185 PN->getIncomingValue(i), C, "phitmp",
2186 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002187 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002188 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002189 CI->getPredicate(),
2190 PN->getIncomingValue(i), C, "phitmp",
2191 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002192 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002193 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002194
2195 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002196 }
2197 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002198 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002199 } else {
2200 CastInst *CI = cast<CastInst>(&I);
2201 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002202 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002203 Value *InV;
2204 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002205 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002206 } else {
2207 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002208 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002209 I.getType(), "phitmp",
2210 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002211 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002212 }
2213 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002214 }
2215 }
2216 return ReplaceInstUsesWith(I, NewPN);
2217}
2218
Chris Lattner2454a2e2008-01-29 06:52:45 +00002219
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002220/// WillNotOverflowSignedAdd - Return true if we can prove that:
2221/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2222/// This basically requires proving that the add in the original type would not
2223/// overflow to change the sign bit or have a carry out.
2224bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2225 // There are different heuristics we can use for this. Here are some simple
2226 // ones.
2227
2228 // Add has the property that adding any two 2's complement numbers can only
2229 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002230 // have at least two sign bits, we know that the addition of the two values
2231 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002232 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2233 return true;
2234
2235
2236 // If one of the operands only has one non-zero bit, and if the other operand
2237 // has a known-zero bit in a more significant place than it (not including the
2238 // sign bit) the ripple may go up to and fill the zero, but won't change the
2239 // sign. For example, (X & ~4) + 1.
2240
2241 // TODO: Implement.
2242
2243 return false;
2244}
2245
Chris Lattner2454a2e2008-01-29 06:52:45 +00002246
Chris Lattner7e708292002-06-25 16:13:24 +00002247Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002248 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002249 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002250
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002251 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2252 I.hasNoUnsignedWrap(), TD))
2253 return ReplaceInstUsesWith(I, V);
2254
2255
Chris Lattner66331a42004-04-10 22:01:55 +00002256 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +00002257 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002258 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002259 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002260 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002261 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002262 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002263
2264 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2265 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002266 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002267 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002268
Eli Friedman709b33d2009-07-13 22:27:52 +00002269 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002270 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002271 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002272 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002273 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002274
2275 if (isa<PHINode>(LHS))
2276 if (Instruction *NV = FoldOpIntoPhi(I))
2277 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002278
Chris Lattner4f637d42006-01-06 17:59:59 +00002279 ConstantInt *XorRHS = 0;
2280 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002281 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002282 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002283 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002284 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002285
Zhou Sheng4351c642007-04-02 08:20:41 +00002286 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002287 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2288 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002289 do {
2290 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002291 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2292 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002293 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2294 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002295 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002296 if (!MaskedValueIsZero(XorLHS,
2297 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002298 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002299 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002300 }
2301 }
2302 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002303 C0080Val = APIntOps::lshr(C0080Val, Size);
2304 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2305 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002306
Reid Spencer35c38852007-03-28 01:36:16 +00002307 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002308 // with funny bit widths then this switch statement should be removed. It
2309 // is just here to get the size of the "middle" type back up to something
2310 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002311 const Type *MiddleType = 0;
2312 switch (Size) {
2313 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002314 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2315 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2316 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002317 }
2318 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002319 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002320 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002321 }
2322 }
Chris Lattner66331a42004-04-10 22:01:55 +00002323 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002324
Owen Anderson1d0be152009-08-13 21:58:54 +00002325 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002326 return BinaryOperator::CreateXor(LHS, RHS);
2327
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002328 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002329 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002330 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002331 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002332
2333 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2334 if (RHSI->getOpcode() == Instruction::Sub)
2335 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2336 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2337 }
2338 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2339 if (LHSI->getOpcode() == Instruction::Sub)
2340 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2341 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2342 }
Robert Bocchino71698282004-07-27 21:02:21 +00002343 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002344
Chris Lattner5c4afb92002-05-08 22:46:53 +00002345 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002346 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002347 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002348 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002349 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002350 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002351 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002352 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002353 }
2354
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002355 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002356 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002357
2358 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002359 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002360 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002361 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002362
Misha Brukmanfd939082005-04-21 23:48:37 +00002363
Chris Lattner50af16a2004-11-13 19:50:12 +00002364 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002365 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002366 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002367 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002368
2369 // X*C1 + X*C2 --> X * (C1+C2)
2370 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002371 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002372 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002373 }
2374
2375 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002376 if (dyn_castFoldableMul(RHS, C2) == LHS)
2377 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002378
Chris Lattnere617c9e2007-01-05 02:17:46 +00002379 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002380 if (dyn_castNotVal(LHS) == RHS ||
2381 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002382 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002383
Chris Lattnerad3448c2003-02-18 19:57:07 +00002384
Chris Lattner564a7272003-08-13 19:01:45 +00002385 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002386 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2387 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002388 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002389
2390 // A+B --> A|B iff A and B have no bits set in common.
2391 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2392 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2393 APInt LHSKnownOne(IT->getBitWidth(), 0);
2394 APInt LHSKnownZero(IT->getBitWidth(), 0);
2395 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2396 if (LHSKnownZero != 0) {
2397 APInt RHSKnownOne(IT->getBitWidth(), 0);
2398 APInt RHSKnownZero(IT->getBitWidth(), 0);
2399 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2400
2401 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002402 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002403 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002404 }
2405 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002406
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002407 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002408 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002409 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002410 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2411 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002412 if (W != Y) {
2413 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002414 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002415 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002416 std::swap(W, X);
2417 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002418 std::swap(Y, Z);
2419 std::swap(W, X);
2420 }
2421 }
2422
2423 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002424 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002425 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002426 }
2427 }
2428 }
2429
Chris Lattner6b032052003-10-02 15:11:26 +00002430 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002431 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002432 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002433 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002434
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002435 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002436 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002437 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002438 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002439 if (Anded == CRHS) {
2440 // See if all bits from the first bit set in the Add RHS up are included
2441 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002442 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002443
2444 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002445 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002446
2447 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002448 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002449
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002450 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2451 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002452 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002453 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002454 }
2455 }
2456 }
2457
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002458 // Try to fold constant add into select arguments.
2459 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002460 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002461 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002462 }
2463
Chris Lattner42790482007-12-20 01:56:58 +00002464 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002465 {
2466 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002467 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002468 if (!SI) {
2469 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002470 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002471 }
Chris Lattner42790482007-12-20 01:56:58 +00002472 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002473 Value *TV = SI->getTrueValue();
2474 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002475 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002476
2477 // Can we fold the add into the argument of the select?
2478 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002479 if (match(FV, m_Zero()) &&
2480 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002481 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002482 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002483 if (match(TV, m_Zero()) &&
2484 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002485 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002486 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002487 }
2488 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002489
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002490 // Check for (add (sext x), y), see if we can merge this into an
2491 // integer add followed by a sext.
2492 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2493 // (add (sext x), cst) --> (sext (add x, cst'))
2494 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2495 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002496 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002497 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002498 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002499 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2500 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002501 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2502 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002503 return new SExtInst(NewAdd, I.getType());
2504 }
2505 }
2506
2507 // (add (sext x), (sext y)) --> (sext (add int x, y))
2508 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2509 // Only do this if x/y have the same type, if at last one of them has a
2510 // single use (so we don't increase the number of sexts), and if the
2511 // integer add will not overflow.
2512 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2513 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2514 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2515 RHSConv->getOperand(0))) {
2516 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002517 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2518 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002519 return new SExtInst(NewAdd, I.getType());
2520 }
2521 }
2522 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002523
2524 return Changed ? &I : 0;
2525}
2526
2527Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2528 bool Changed = SimplifyCommutative(I);
2529 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2530
2531 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2532 // X + 0 --> X
2533 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002534 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002535 (I.getType())->getValueAPF()))
2536 return ReplaceInstUsesWith(I, LHS);
2537 }
2538
2539 if (isa<PHINode>(LHS))
2540 if (Instruction *NV = FoldOpIntoPhi(I))
2541 return NV;
2542 }
2543
2544 // -A + B --> B - A
2545 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002546 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002547 return BinaryOperator::CreateFSub(RHS, LHSV);
2548
2549 // A + -B --> A - B
2550 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002551 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002552 return BinaryOperator::CreateFSub(LHS, V);
2553
2554 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2555 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2556 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2557 return ReplaceInstUsesWith(I, LHS);
2558
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002559 // Check for (add double (sitofp x), y), see if we can merge this into an
2560 // integer add followed by a promotion.
2561 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2562 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2563 // ... if the constant fits in the integer value. This is useful for things
2564 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2565 // requires a constant pool load, and generally allows the add to be better
2566 // instcombined.
2567 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2568 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002569 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002570 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002571 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002572 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2573 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002574 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2575 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002576 return new SIToFPInst(NewAdd, I.getType());
2577 }
2578 }
2579
2580 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2581 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2582 // Only do this if x/y have the same type, if at last one of them has a
2583 // single use (so we don't increase the number of int->fp conversions),
2584 // and if the integer add will not overflow.
2585 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2586 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2587 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2588 RHSConv->getOperand(0))) {
2589 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002590 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002591 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002592 return new SIToFPInst(NewAdd, I.getType());
2593 }
2594 }
2595 }
2596
Chris Lattner7e708292002-06-25 16:13:24 +00002597 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002598}
2599
Chris Lattner092543c2009-11-04 08:05:20 +00002600
2601/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2602/// code necessary to compute the offset from the base pointer (without adding
2603/// in the base pointer). Return the result as a signed integer of intptr size.
2604static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2605 TargetData &TD = *IC.getTargetData();
2606 gep_type_iterator GTI = gep_type_begin(GEP);
2607 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2608 Value *Result = Constant::getNullValue(IntPtrTy);
2609
2610 // Build a mask for high order bits.
2611 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2612 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2613
2614 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2615 ++i, ++GTI) {
2616 Value *Op = *i;
2617 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2618 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2619 if (OpC->isZero()) continue;
2620
2621 // Handle a struct index, which adds its field offset to the pointer.
2622 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2623 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2624
2625 Result = IC.Builder->CreateAdd(Result,
2626 ConstantInt::get(IntPtrTy, Size),
2627 GEP->getName()+".offs");
2628 continue;
2629 }
2630
2631 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2632 Constant *OC =
2633 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2634 Scale = ConstantExpr::getMul(OC, Scale);
2635 // Emit an add instruction.
2636 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2637 continue;
2638 }
2639 // Convert to correct type.
2640 if (Op->getType() != IntPtrTy)
2641 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2642 if (Size != 1) {
2643 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2644 // We'll let instcombine(mul) convert this to a shl if possible.
2645 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2646 }
2647
2648 // Emit an add instruction.
2649 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2650 }
2651 return Result;
2652}
2653
2654
2655/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2656/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2657/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2658/// be complex, and scales are involved. The above expression would also be
2659/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2660/// This later form is less amenable to optimization though, and we are allowed
2661/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2662///
2663/// If we can't emit an optimized form for this expression, this returns null.
2664///
2665static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2666 InstCombiner &IC) {
2667 TargetData &TD = *IC.getTargetData();
2668 gep_type_iterator GTI = gep_type_begin(GEP);
2669
2670 // Check to see if this gep only has a single variable index. If so, and if
2671 // any constant indices are a multiple of its scale, then we can compute this
2672 // in terms of the scale of the variable index. For example, if the GEP
2673 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2674 // because the expression will cross zero at the same point.
2675 unsigned i, e = GEP->getNumOperands();
2676 int64_t Offset = 0;
2677 for (i = 1; i != e; ++i, ++GTI) {
2678 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2679 // Compute the aggregate offset of constant indices.
2680 if (CI->isZero()) continue;
2681
2682 // Handle a struct index, which adds its field offset to the pointer.
2683 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2684 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2685 } else {
2686 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2687 Offset += Size*CI->getSExtValue();
2688 }
2689 } else {
2690 // Found our variable index.
2691 break;
2692 }
2693 }
2694
2695 // If there are no variable indices, we must have a constant offset, just
2696 // evaluate it the general way.
2697 if (i == e) return 0;
2698
2699 Value *VariableIdx = GEP->getOperand(i);
2700 // Determine the scale factor of the variable element. For example, this is
2701 // 4 if the variable index is into an array of i32.
2702 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2703
2704 // Verify that there are no other variable indices. If so, emit the hard way.
2705 for (++i, ++GTI; i != e; ++i, ++GTI) {
2706 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2707 if (!CI) return 0;
2708
2709 // Compute the aggregate offset of constant indices.
2710 if (CI->isZero()) continue;
2711
2712 // Handle a struct index, which adds its field offset to the pointer.
2713 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2714 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2715 } else {
2716 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2717 Offset += Size*CI->getSExtValue();
2718 }
2719 }
2720
2721 // Okay, we know we have a single variable index, which must be a
2722 // pointer/array/vector index. If there is no offset, life is simple, return
2723 // the index.
2724 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2725 if (Offset == 0) {
2726 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2727 // we don't need to bother extending: the extension won't affect where the
2728 // computation crosses zero.
2729 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2730 VariableIdx = new TruncInst(VariableIdx,
2731 TD.getIntPtrType(VariableIdx->getContext()),
2732 VariableIdx->getName(), &I);
2733 return VariableIdx;
2734 }
2735
2736 // Otherwise, there is an index. The computation we will do will be modulo
2737 // the pointer size, so get it.
2738 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2739
2740 Offset &= PtrSizeMask;
2741 VariableScale &= PtrSizeMask;
2742
2743 // To do this transformation, any constant index must be a multiple of the
2744 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2745 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2746 // multiple of the variable scale.
2747 int64_t NewOffs = Offset / (int64_t)VariableScale;
2748 if (Offset != NewOffs*(int64_t)VariableScale)
2749 return 0;
2750
2751 // Okay, we can do this evaluation. Start by converting the index to intptr.
2752 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2753 if (VariableIdx->getType() != IntPtrTy)
2754 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2755 true /*SExt*/,
2756 VariableIdx->getName(), &I);
2757 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2758 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2759}
2760
2761
2762/// Optimize pointer differences into the same array into a size. Consider:
2763/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2764/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2765///
2766Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2767 const Type *Ty) {
2768 assert(TD && "Must have target data info for this");
2769
2770 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2771 // this.
2772 bool Swapped;
2773 GetElementPtrInst *GEP;
2774
2775 if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2776 GEP->getOperand(0) == RHS)
2777 Swapped = false;
2778 else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2779 GEP->getOperand(0) == LHS)
2780 Swapped = true;
2781 else
2782 return 0;
2783
2784 // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2785
2786 // Emit the offset of the GEP and an intptr_t.
2787 Value *Result = EmitGEPOffset(GEP, *this);
2788
2789 // If we have p - gep(p, ...) then we have to negate the result.
2790 if (Swapped)
2791 Result = Builder->CreateNeg(Result, "diff.neg");
2792
2793 return Builder->CreateIntCast(Result, Ty, true);
2794}
2795
2796
Chris Lattner7e708292002-06-25 16:13:24 +00002797Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002798 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002799
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002800 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002801 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002802
Chris Lattner3bf68152009-12-21 04:04:05 +00002803 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
2804 if (Value *V = dyn_castNegVal(Op1)) {
2805 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2806 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2807 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2808 return Res;
2809 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002810
Chris Lattnere87597f2004-10-16 18:11:37 +00002811 if (isa<UndefValue>(Op0))
2812 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2813 if (isa<UndefValue>(Op1))
2814 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner092543c2009-11-04 08:05:20 +00002815 if (I.getType() == Type::getInt1Ty(*Context))
2816 return BinaryOperator::CreateXor(Op0, Op1);
2817
Chris Lattnerd65460f2003-11-05 01:06:05 +00002818 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002819 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002820 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002821 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002822
Chris Lattnerd65460f2003-11-05 01:06:05 +00002823 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002824 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002825 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002826 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002827
Chris Lattner76b7a062007-01-15 07:02:54 +00002828 // -(X >>u 31) -> (X >>s 31)
2829 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002830 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002831 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002832 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002833 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002834 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002835 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002836 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002837 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002838 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002839 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002840 }
2841 }
Chris Lattner092543c2009-11-04 08:05:20 +00002842 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002843 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2844 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002845 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002846 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002847 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002848 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002849 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002850 }
2851 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002852 }
2853 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002854 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002855
2856 // Try to fold constant sub into select arguments.
2857 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002858 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002859 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002860
2861 // C - zext(bool) -> bool ? C - 1 : C
2862 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002863 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002864 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002865 }
2866
Chris Lattner43d84d62005-04-07 16:15:25 +00002867 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002868 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002869 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002870 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002871 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002872 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002873 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002874 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002875 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2876 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2877 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002878 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002879 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002880 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002881 }
2882
Chris Lattnerfd059242003-10-15 16:48:29 +00002883 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002884 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2885 // is not used by anyone else...
2886 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002887 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002888 // Swap the two operands of the subexpr...
2889 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2890 Op1I->setOperand(0, IIOp1);
2891 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002892
Chris Lattnera2881962003-02-18 19:28:33 +00002893 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002894 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002895 }
2896
2897 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2898 //
2899 if (Op1I->getOpcode() == Instruction::And &&
2900 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2901 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2902
Chris Lattner74381062009-08-30 07:44:24 +00002903 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002904 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002905 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002906
Reid Spencerac5209e2006-10-16 23:08:08 +00002907 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002908 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002909 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002910 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002911 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002912 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002913 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002914
Chris Lattnerad3448c2003-02-18 19:57:07 +00002915 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002916 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002917 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002918 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002919 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002920 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002921 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002922 }
Chris Lattner40371712002-05-09 01:29:19 +00002923 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002924 }
Chris Lattnera2881962003-02-18 19:28:33 +00002925
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002926 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2927 if (Op0I->getOpcode() == Instruction::Add) {
2928 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2929 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2930 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2931 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2932 } else if (Op0I->getOpcode() == Instruction::Sub) {
2933 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002934 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002935 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002936 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002937 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002938
Chris Lattner50af16a2004-11-13 19:50:12 +00002939 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002940 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002941 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002942 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002943
Chris Lattner50af16a2004-11-13 19:50:12 +00002944 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002945 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002946 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002947 }
Chris Lattner092543c2009-11-04 08:05:20 +00002948
2949 // Optimize pointer differences into the same array into a size. Consider:
2950 // &A[10] - &A[0]: we should compile this to "10".
2951 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00002952 Value *LHSOp, *RHSOp;
2953 if (match(Op0, m_Cast<PtrToIntInst>(m_Value(LHSOp))) &&
2954 match(Op1, m_Cast<PtrToIntInst>(m_Value(RHSOp))))
2955 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2956 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00002957
2958 // trunc(p)-trunc(q) -> trunc(p-q)
2959 if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2960 if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2961 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2962 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2963 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2964 RHS->getOperand(0),
2965 I.getType()))
2966 return ReplaceInstUsesWith(I, Res);
2967 }
2968
Chris Lattner3f5b8772002-05-06 16:14:14 +00002969 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002970}
2971
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002972Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2973 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2974
2975 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002976 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002977 return BinaryOperator::CreateFAdd(Op0, V);
2978
2979 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2980 if (Op1I->getOpcode() == Instruction::FAdd) {
2981 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002982 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002983 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002984 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002985 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002986 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002987 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002988 }
2989
2990 return 0;
2991}
2992
Chris Lattnera0141b92007-07-15 20:42:37 +00002993/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2994/// comparison only checks the sign bit. If it only checks the sign bit, set
2995/// TrueIfSigned if the result of the comparison is true when the input value is
2996/// signed.
2997static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2998 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002999 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003000 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3001 TrueIfSigned = true;
3002 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003003 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3004 TrueIfSigned = true;
3005 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00003006 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3007 TrueIfSigned = false;
3008 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003009 case ICmpInst::ICMP_UGT:
3010 // True if LHS u> RHS and RHS == high-bit-mask - 1
3011 TrueIfSigned = true;
3012 return RHS->getValue() ==
3013 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3014 case ICmpInst::ICMP_UGE:
3015 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3016 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00003017 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00003018 default:
3019 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00003020 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00003021}
3022
Chris Lattner7e708292002-06-25 16:13:24 +00003023Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003024 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003025 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003026
Chris Lattnera2498472009-10-11 21:36:10 +00003027 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003028 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003029
Chris Lattner8af304a2009-10-11 07:53:15 +00003030 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00003031 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3032 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00003033
3034 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00003035 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00003036 if (SI->getOpcode() == Instruction::Shl)
3037 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003038 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003039 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00003040
Zhou Sheng843f07672007-04-19 05:39:12 +00003041 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00003042 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00003043 if (CI->equalsInt(1)) // X * 1 == X
3044 return ReplaceInstUsesWith(I, Op0);
3045 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00003046 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003047
Zhou Sheng97b52c22007-03-29 01:57:21 +00003048 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003049 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003050 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003051 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003052 }
Chris Lattnera2498472009-10-11 21:36:10 +00003053 } else if (isa<VectorType>(Op1C->getType())) {
3054 if (Op1C->isNullValue())
3055 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00003056
Chris Lattnera2498472009-10-11 21:36:10 +00003057 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003058 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00003059 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00003060
3061 // As above, vector X*splat(1.0) -> X in all defined cases.
3062 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003063 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3064 if (CI->equalsInt(1))
3065 return ReplaceInstUsesWith(I, Op0);
3066 }
3067 }
Chris Lattnera2881962003-02-18 19:28:33 +00003068 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003069
3070 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3071 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003072 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003073 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00003074 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3075 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003076 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003077
3078 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003079
3080 // Try to fold constant mul into select arguments.
3081 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003082 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003083 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003084
3085 if (isa<PHINode>(Op0))
3086 if (Instruction *NV = FoldOpIntoPhi(I))
3087 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003088 }
3089
Dan Gohman186a6362009-08-12 16:04:34 +00003090 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003091 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003092 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003093
Nick Lewycky0c730792008-11-21 07:33:58 +00003094 // (X / Y) * Y = X - (X % Y)
3095 // (X / Y) * -Y = (X % Y) - X
3096 {
Chris Lattnera2498472009-10-11 21:36:10 +00003097 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00003098 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3099 if (!BO ||
3100 (BO->getOpcode() != Instruction::UDiv &&
3101 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00003102 Op1C = Op0;
3103 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00003104 }
Chris Lattnera2498472009-10-11 21:36:10 +00003105 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00003106 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003107 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00003108 (BO->getOpcode() == Instruction::UDiv ||
3109 BO->getOpcode() == Instruction::SDiv)) {
3110 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3111
Dan Gohmanfa94b942009-08-12 16:33:09 +00003112 // If the division is exact, X % Y is zero.
3113 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3114 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00003115 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00003116 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00003117 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00003118 }
3119
Chris Lattner74381062009-08-30 07:44:24 +00003120 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00003121 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00003122 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003123 else
Chris Lattner74381062009-08-30 07:44:24 +00003124 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003125 Rem->takeName(BO);
3126
Chris Lattnera2498472009-10-11 21:36:10 +00003127 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00003128 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00003129 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003130 }
3131 }
3132
Chris Lattner8af304a2009-10-11 07:53:15 +00003133 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00003134 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00003135 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003136
Chris Lattner8af304a2009-10-11 07:53:15 +00003137 // X*(1 << Y) --> X << Y
3138 // (1 << Y)*X --> X << Y
3139 {
3140 Value *Y;
3141 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00003142 return BinaryOperator::CreateShl(Op1, Y);
3143 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00003144 return BinaryOperator::CreateShl(Op0, Y);
3145 }
3146
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003147 // If one of the operands of the multiply is a cast from a boolean value, then
3148 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00003149 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3150 if (!isa<VectorType>(I.getType())) {
3151 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00003152 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00003153
Chris Lattnerd2c58362009-10-11 21:29:45 +00003154 Value *BoolCast = 0, *OtherOp = 0;
3155 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00003156 BoolCast = Op0, OtherOp = Op1;
3157 else if (MaskedValueIsZero(Op1, Negative2))
3158 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00003159
Chris Lattner0036e3a2009-10-11 21:22:21 +00003160 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00003161 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3162 BoolCast, "tmp");
3163 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003164 }
3165 }
3166
Chris Lattner7e708292002-06-25 16:13:24 +00003167 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003168}
3169
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003170Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3171 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003172 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003173
3174 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00003175 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3176 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003177 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3178 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3179 if (Op1F->isExactlyValue(1.0))
3180 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00003181 } else if (isa<VectorType>(Op1C->getType())) {
3182 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003183 // As above, vector X*splat(1.0) -> X in all defined cases.
3184 if (Constant *Splat = Op1V->getSplatValue()) {
3185 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3186 if (F->isExactlyValue(1.0))
3187 return ReplaceInstUsesWith(I, Op0);
3188 }
3189 }
3190 }
3191
3192 // Try to fold constant mul into select arguments.
3193 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3194 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3195 return R;
3196
3197 if (isa<PHINode>(Op0))
3198 if (Instruction *NV = FoldOpIntoPhi(I))
3199 return NV;
3200 }
3201
Dan Gohman186a6362009-08-12 16:04:34 +00003202 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003203 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003204 return BinaryOperator::CreateFMul(Op0v, Op1v);
3205
3206 return Changed ? &I : 0;
3207}
3208
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003209/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3210/// instruction.
3211bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3212 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3213
3214 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3215 int NonNullOperand = -1;
3216 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3217 if (ST->isNullValue())
3218 NonNullOperand = 2;
3219 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3220 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3221 if (ST->isNullValue())
3222 NonNullOperand = 1;
3223
3224 if (NonNullOperand == -1)
3225 return false;
3226
3227 Value *SelectCond = SI->getOperand(0);
3228
3229 // Change the div/rem to use 'Y' instead of the select.
3230 I.setOperand(1, SI->getOperand(NonNullOperand));
3231
3232 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3233 // problem. However, the select, or the condition of the select may have
3234 // multiple uses. Based on our knowledge that the operand must be non-zero,
3235 // propagate the known value for the select into other uses of it, and
3236 // propagate a known value of the condition into its other users.
3237
3238 // If the select and condition only have a single use, don't bother with this,
3239 // early exit.
3240 if (SI->use_empty() && SelectCond->hasOneUse())
3241 return true;
3242
3243 // Scan the current block backward, looking for other uses of SI.
3244 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3245
3246 while (BBI != BBFront) {
3247 --BBI;
3248 // If we found a call to a function, we can't assume it will return, so
3249 // information from below it cannot be propagated above it.
3250 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3251 break;
3252
3253 // Replace uses of the select or its condition with the known values.
3254 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3255 I != E; ++I) {
3256 if (*I == SI) {
3257 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003258 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003259 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00003260 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3261 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003262 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003263 }
3264 }
3265
3266 // If we past the instruction, quit looking for it.
3267 if (&*BBI == SI)
3268 SI = 0;
3269 if (&*BBI == SelectCond)
3270 SelectCond = 0;
3271
3272 // If we ran out of things to eliminate, break out of the loop.
3273 if (SelectCond == 0 && SI == 0)
3274 break;
3275
3276 }
3277 return true;
3278}
3279
3280
Reid Spencer1628cec2006-10-26 06:15:43 +00003281/// This function implements the transforms on div instructions that work
3282/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3283/// used by the visitors to those instructions.
3284/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003285Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003286 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003287
Chris Lattner50b2ca42008-02-19 06:12:18 +00003288 // undef / X -> 0 for integer.
3289 // undef / X -> undef for FP (the undef could be a snan).
3290 if (isa<UndefValue>(Op0)) {
3291 if (Op0->getType()->isFPOrFPVector())
3292 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003293 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003294 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003295
3296 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003297 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003298 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003299
Reid Spencer1628cec2006-10-26 06:15:43 +00003300 return 0;
3301}
Misha Brukmanfd939082005-04-21 23:48:37 +00003302
Reid Spencer1628cec2006-10-26 06:15:43 +00003303/// This function implements the transforms common to both integer division
3304/// instructions (udiv and sdiv). It is called by the visitors to those integer
3305/// division instructions.
3306/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003307Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003308 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3309
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003310 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003311 if (Op0 == Op1) {
3312 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003313 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003314 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003315 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003316 }
3317
Owen Andersoneed707b2009-07-24 23:12:02 +00003318 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003319 return ReplaceInstUsesWith(I, CI);
3320 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003321
Reid Spencer1628cec2006-10-26 06:15:43 +00003322 if (Instruction *Common = commonDivTransforms(I))
3323 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003324
3325 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3326 // This does not apply for fdiv.
3327 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3328 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003329
3330 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3331 // div X, 1 == X
3332 if (RHS->equalsInt(1))
3333 return ReplaceInstUsesWith(I, Op0);
3334
3335 // (X / C1) / C2 -> X / (C1*C2)
3336 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3337 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3338 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003339 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003340 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003341 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003342 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003343 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003344 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003345 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003346
Reid Spencerbca0e382007-03-23 20:05:17 +00003347 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003348 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3349 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3350 return R;
3351 if (isa<PHINode>(Op0))
3352 if (Instruction *NV = FoldOpIntoPhi(I))
3353 return NV;
3354 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003355 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003356
Chris Lattnera2881962003-02-18 19:28:33 +00003357 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003358 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003359 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003360 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003361
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003362 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003363 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003364 return ReplaceInstUsesWith(I, Op0);
3365
Nick Lewycky895f0852008-11-27 20:21:08 +00003366 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3367 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3368 // div X, 1 == X
3369 if (X->isOne())
3370 return ReplaceInstUsesWith(I, Op0);
3371 }
3372
Reid Spencer1628cec2006-10-26 06:15:43 +00003373 return 0;
3374}
3375
3376Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3377 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3378
3379 // Handle the integer div common cases
3380 if (Instruction *Common = commonIDivTransforms(I))
3381 return Common;
3382
Reid Spencer1628cec2006-10-26 06:15:43 +00003383 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003384 // X udiv C^2 -> X >> C
3385 // Check to see if this is an unsigned division with an exact power of 2,
3386 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003387 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003388 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003389 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003390
3391 // X udiv C, where C >= signbit
3392 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003393 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003394 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003395 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003396 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003397 }
3398
3399 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003400 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003401 if (RHSI->getOpcode() == Instruction::Shl &&
3402 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003403 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003404 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003405 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003406 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003407 if (uint32_t C2 = C1.logBase2())
3408 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003409 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003410 }
3411 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003412 }
3413
Reid Spencer1628cec2006-10-26 06:15:43 +00003414 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3415 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003416 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003417 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003418 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003419 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003420 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003421 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003422 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003423 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003424 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003425 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003426
3427 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003428 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003429 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003430
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003431 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003432 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003433 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003434 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003435 return 0;
3436}
3437
Reid Spencer1628cec2006-10-26 06:15:43 +00003438Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3439 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3440
3441 // Handle the integer div common cases
3442 if (Instruction *Common = commonIDivTransforms(I))
3443 return Common;
3444
3445 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3446 // sdiv X, -1 == -X
3447 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003448 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003449
Dan Gohmanfa94b942009-08-12 16:33:09 +00003450 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003451 if (cast<SDivOperator>(&I)->isExact() &&
3452 RHS->getValue().isNonNegative() &&
3453 RHS->getValue().isPowerOf2()) {
3454 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3455 RHS->getValue().exactLogBase2());
3456 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3457 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003458
3459 // -X/C --> X/-C provided the negation doesn't overflow.
3460 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3461 if (isa<Constant>(Sub->getOperand(0)) &&
3462 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003463 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003464 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3465 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003466 }
3467
3468 // If the sign bits of both operands are zero (i.e. we can prove they are
3469 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003470 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003471 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003472 if (MaskedValueIsZero(Op0, Mask)) {
3473 if (MaskedValueIsZero(Op1, Mask)) {
3474 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3475 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3476 }
3477 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003478 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003479 ShiftedInt->getValue().isPowerOf2()) {
3480 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3481 // Safe because the only negative value (1 << Y) can take on is
3482 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3483 // the sign bit set.
3484 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3485 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003486 }
Eli Friedman8be17392009-07-18 09:53:21 +00003487 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003488
3489 return 0;
3490}
3491
3492Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3493 return commonDivTransforms(I);
3494}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003495
Reid Spencer0a783f72006-11-02 01:53:59 +00003496/// This function implements the transforms on rem instructions that work
3497/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3498/// is used by the visitors to those instructions.
3499/// @brief Transforms common to all three rem instructions
3500Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003501 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003502
Chris Lattner50b2ca42008-02-19 06:12:18 +00003503 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3504 if (I.getType()->isFPOrFPVector())
3505 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003506 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003507 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003508 if (isa<UndefValue>(Op1))
3509 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003510
3511 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003512 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3513 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003514
Reid Spencer0a783f72006-11-02 01:53:59 +00003515 return 0;
3516}
3517
3518/// This function implements the transforms common to both integer remainder
3519/// instructions (urem and srem). It is called by the visitors to those integer
3520/// remainder instructions.
3521/// @brief Common integer remainder transforms
3522Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3523 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3524
3525 if (Instruction *common = commonRemTransforms(I))
3526 return common;
3527
Dale Johannesened6af242009-01-21 00:35:19 +00003528 // 0 % X == 0 for integer, we don't need to preserve faults!
3529 if (Constant *LHS = dyn_cast<Constant>(Op0))
3530 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003531 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003532
Chris Lattner857e8cd2004-12-12 21:48:58 +00003533 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003534 // X % 0 == undef, we don't need to preserve faults!
3535 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003536 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003537
Chris Lattnera2881962003-02-18 19:28:33 +00003538 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003539 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003540
Chris Lattner97943922006-02-28 05:49:21 +00003541 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3542 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3543 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3544 return R;
3545 } else if (isa<PHINode>(Op0I)) {
3546 if (Instruction *NV = FoldOpIntoPhi(I))
3547 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003548 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003549
3550 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003551 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003552 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003553 }
Chris Lattnera2881962003-02-18 19:28:33 +00003554 }
3555
Reid Spencer0a783f72006-11-02 01:53:59 +00003556 return 0;
3557}
3558
3559Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3560 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3561
3562 if (Instruction *common = commonIRemTransforms(I))
3563 return common;
3564
3565 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3566 // X urem C^2 -> X and C
3567 // Check to see if this is an unsigned remainder with an exact power of 2,
3568 // if so, convert to a bitwise and.
3569 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003570 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003571 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003572 }
3573
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003574 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003575 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3576 if (RHSI->getOpcode() == Instruction::Shl &&
3577 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003578 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003579 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003580 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003581 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003582 }
3583 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003584 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003585
Reid Spencer0a783f72006-11-02 01:53:59 +00003586 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3587 // where C1&C2 are powers of two.
3588 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3589 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3590 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3591 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003592 if ((STO->getValue().isPowerOf2()) &&
3593 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003594 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3595 SI->getName()+".t");
3596 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3597 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003598 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003599 }
3600 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003601 }
3602
Chris Lattner3f5b8772002-05-06 16:14:14 +00003603 return 0;
3604}
3605
Reid Spencer0a783f72006-11-02 01:53:59 +00003606Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3607 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3608
Dan Gohmancff55092007-11-05 23:16:33 +00003609 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003610 if (Instruction *Common = commonIRemTransforms(I))
3611 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003612
Dan Gohman186a6362009-08-12 16:04:34 +00003613 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003614 if (!isa<Constant>(RHSNeg) ||
3615 (isa<ConstantInt>(RHSNeg) &&
3616 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003617 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003618 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003619 I.setOperand(1, RHSNeg);
3620 return &I;
3621 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003622
Dan Gohmancff55092007-11-05 23:16:33 +00003623 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003624 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003625 if (I.getType()->isInteger()) {
3626 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3627 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3628 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003629 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003630 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003631 }
3632
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003633 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003634 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3635 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003636
Nick Lewycky9dce8732008-12-20 16:48:00 +00003637 bool hasNegative = false;
3638 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3639 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3640 if (RHS->getValue().isNegative())
3641 hasNegative = true;
3642
3643 if (hasNegative) {
3644 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003645 for (unsigned i = 0; i != VWidth; ++i) {
3646 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3647 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003648 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003649 else
3650 Elts[i] = RHS;
3651 }
3652 }
3653
Owen Andersonaf7ec972009-07-28 21:19:26 +00003654 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003655 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003656 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003657 I.setOperand(1, NewRHSV);
3658 return &I;
3659 }
3660 }
3661 }
3662
Reid Spencer0a783f72006-11-02 01:53:59 +00003663 return 0;
3664}
3665
3666Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003667 return commonRemTransforms(I);
3668}
3669
Chris Lattner457dd822004-06-09 07:59:58 +00003670// isOneBitSet - Return true if there is exactly one bit set in the specified
3671// constant.
3672static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003673 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003674}
3675
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003676// isHighOnes - Return true if the constant is of the form 1+0+.
3677// This is the same as lowones(~X).
3678static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003679 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003680}
3681
Reid Spencere4d87aa2006-12-23 06:05:41 +00003682/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003683/// are carefully arranged to allow folding of expressions such as:
3684///
3685/// (A < B) | (A > B) --> (A != B)
3686///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003687/// Note that this is only valid if the first and second predicates have the
3688/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003689///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003690/// Three bits are used to represent the condition, as follows:
3691/// 0 A > B
3692/// 1 A == B
3693/// 2 A < B
3694///
3695/// <=> Value Definition
3696/// 000 0 Always false
3697/// 001 1 A > B
3698/// 010 2 A == B
3699/// 011 3 A >= B
3700/// 100 4 A < B
3701/// 101 5 A != B
3702/// 110 6 A <= B
3703/// 111 7 Always true
3704///
3705static unsigned getICmpCode(const ICmpInst *ICI) {
3706 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003707 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003708 case ICmpInst::ICMP_UGT: return 1; // 001
3709 case ICmpInst::ICMP_SGT: return 1; // 001
3710 case ICmpInst::ICMP_EQ: return 2; // 010
3711 case ICmpInst::ICMP_UGE: return 3; // 011
3712 case ICmpInst::ICMP_SGE: return 3; // 011
3713 case ICmpInst::ICMP_ULT: return 4; // 100
3714 case ICmpInst::ICMP_SLT: return 4; // 100
3715 case ICmpInst::ICMP_NE: return 5; // 101
3716 case ICmpInst::ICMP_ULE: return 6; // 110
3717 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003718 // True -> 7
3719 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003720 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003721 return 0;
3722 }
3723}
3724
Evan Cheng8db90722008-10-14 17:15:11 +00003725/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3726/// predicate into a three bit mask. It also returns whether it is an ordered
3727/// predicate by reference.
3728static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3729 isOrdered = false;
3730 switch (CC) {
3731 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3732 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003733 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3734 case FCmpInst::FCMP_UGT: return 1; // 001
3735 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3736 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003737 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3738 case FCmpInst::FCMP_UGE: return 3; // 011
3739 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3740 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003741 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3742 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003743 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3744 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003745 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003746 default:
3747 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003748 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003749 return 0;
3750 }
3751}
3752
Reid Spencere4d87aa2006-12-23 06:05:41 +00003753/// getICmpValue - This is the complement of getICmpCode, which turns an
3754/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003755/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003756/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003757static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003758 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003759 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003760 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003761 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003762 case 1:
3763 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003764 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003765 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003766 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3767 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003768 case 3:
3769 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003770 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003771 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003772 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003773 case 4:
3774 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003775 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003776 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003777 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3778 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003779 case 6:
3780 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003781 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003782 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003783 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003784 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003785 }
3786}
3787
Evan Cheng8db90722008-10-14 17:15:11 +00003788/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3789/// opcode and two operands into either a FCmp instruction. isordered is passed
3790/// in to determine which kind of predicate to use in the new fcmp instruction.
3791static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003792 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003793 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003794 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003795 case 0:
3796 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003797 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003798 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003799 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003800 case 1:
3801 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003802 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003803 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003804 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003805 case 2:
3806 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003807 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003808 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003809 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003810 case 3:
3811 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003812 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003813 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003814 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003815 case 4:
3816 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003817 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003818 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003819 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003820 case 5:
3821 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003822 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003823 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003824 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003825 case 6:
3826 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003827 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003828 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003829 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003830 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003831 }
3832}
3833
Chris Lattnerb9553d62008-11-16 04:55:20 +00003834/// PredicatesFoldable - Return true if both predicates match sign or if at
3835/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003836static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003837 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3838 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3839 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003840}
3841
3842namespace {
3843// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3844struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003845 InstCombiner &IC;
3846 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003847 ICmpInst::Predicate pred;
3848 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3849 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3850 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003851 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003852 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3853 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003854 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3855 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003856 return false;
3857 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003858 Instruction *apply(Instruction &Log) const {
3859 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3860 if (ICI->getOperand(0) != LHS) {
3861 assert(ICI->getOperand(1) == LHS);
3862 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003863 }
3864
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003865 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003866 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003867 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003868 unsigned Code;
3869 switch (Log.getOpcode()) {
3870 case Instruction::And: Code = LHSCode & RHSCode; break;
3871 case Instruction::Or: Code = LHSCode | RHSCode; break;
3872 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003873 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003874 }
3875
Nick Lewycky4a134af2009-10-25 05:20:17 +00003876 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003877 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003878 if (Instruction *I = dyn_cast<Instruction>(RV))
3879 return I;
3880 // Otherwise, it's a constant boolean value...
3881 return IC.ReplaceInstUsesWith(Log, RV);
3882 }
3883};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003884} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003885
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003886// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3887// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003888// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003889Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003890 ConstantInt *OpRHS,
3891 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003892 BinaryOperator &TheAnd) {
3893 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003894 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003895 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003896 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003897
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003898 switch (Op->getOpcode()) {
3899 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003900 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003901 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003902 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003903 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003904 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003905 }
3906 break;
3907 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003908 if (Together == AndRHS) // (X | C) & C --> C
3909 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003910
Chris Lattner6e7ba452005-01-01 16:22:27 +00003911 if (Op->hasOneUse() && Together != OpRHS) {
3912 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003913 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003914 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003915 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003916 }
3917 break;
3918 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003919 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003920 // Adding a one to a single bit bit-field should be turned into an XOR
3921 // of the bit. First thing to check is to see if this AND is with a
3922 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003923 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003924
3925 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003926 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003927 // Ok, at this point, we know that we are masking the result of the
3928 // ADD down to exactly one bit. If the constant we are adding has
3929 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003930 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003931
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003932 // Check to see if any bits below the one bit set in AndRHSV are set.
3933 if ((AddRHS & (AndRHSV-1)) == 0) {
3934 // If not, the only thing that can effect the output of the AND is
3935 // the bit specified by AndRHSV. If that bit is set, the effect of
3936 // the XOR is to toggle the bit. If it is clear, then the ADD has
3937 // no effect.
3938 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3939 TheAnd.setOperand(0, X);
3940 return &TheAnd;
3941 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003942 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003943 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003944 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003945 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003946 }
3947 }
3948 }
3949 }
3950 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003951
3952 case Instruction::Shl: {
3953 // We know that the AND will not produce any of the bits shifted in, so if
3954 // the anded constant includes them, clear them now!
3955 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003956 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003957 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003958 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003959 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003960
Zhou Sheng290bec52007-03-29 08:15:12 +00003961 if (CI->getValue() == ShlMask) {
3962 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003963 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3964 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003965 TheAnd.setOperand(1, CI);
3966 return &TheAnd;
3967 }
3968 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003969 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003970 case Instruction::LShr:
3971 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003972 // We know that the AND will not produce any of the bits shifted in, so if
3973 // the anded constant includes them, clear them now! This only applies to
3974 // unsigned shifts, because a signed shr may bring in set bits!
3975 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003976 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003977 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003978 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003979 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003980
Zhou Sheng290bec52007-03-29 08:15:12 +00003981 if (CI->getValue() == ShrMask) {
3982 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003983 return ReplaceInstUsesWith(TheAnd, Op);
3984 } else if (CI != AndRHS) {
3985 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3986 return &TheAnd;
3987 }
3988 break;
3989 }
3990 case Instruction::AShr:
3991 // Signed shr.
3992 // See if this is shifting in some sign extension, then masking it out
3993 // with an and.
3994 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003995 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003996 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003997 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003998 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003999 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00004000 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00004001 // Make the argument unsigned.
4002 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00004003 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004004 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00004005 }
Chris Lattner62a355c2003-09-19 19:05:02 +00004006 }
4007 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004008 }
4009 return 0;
4010}
4011
Chris Lattner8b170942002-08-09 23:47:40 +00004012
Chris Lattnera96879a2004-09-29 17:40:11 +00004013/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
4014/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00004015/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
4016/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00004017/// insert new instructions.
4018Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004019 bool isSigned, bool Inside,
4020 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004021 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00004022 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00004023 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004024
Chris Lattnera96879a2004-09-29 17:40:11 +00004025 if (Inside) {
4026 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004027 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00004028
Reid Spencere4d87aa2006-12-23 06:05:41 +00004029 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004030 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00004031 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00004032 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004033 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004034 }
4035
4036 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00004037 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00004038 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00004039 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004040 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004041 }
4042
4043 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004044 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00004045
Reid Spencere4e40032007-03-21 23:19:50 +00004046 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00004047 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004048 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004049 ICmpInst::Predicate pred = (isSigned ?
4050 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004051 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004052 }
Reid Spencerb83eb642006-10-20 07:07:24 +00004053
Reid Spencere4e40032007-03-21 23:19:50 +00004054 // Emit V-Lo >u Hi-1-Lo
4055 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00004056 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00004057 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00004058 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004059 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004060}
4061
Chris Lattner7203e152005-09-18 07:22:02 +00004062// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
4063// any number of 0s on either side. The 1s are allowed to wrap from LSB to
4064// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
4065// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00004066static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004067 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00004068 uint32_t BitWidth = Val->getType()->getBitWidth();
4069 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00004070
4071 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00004072 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00004073 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00004074 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00004075 return true;
4076}
4077
Chris Lattner7203e152005-09-18 07:22:02 +00004078/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4079/// where isSub determines whether the operator is a sub. If we can fold one of
4080/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00004081///
4082/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4083/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4084/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4085///
4086/// return (A +/- B).
4087///
4088Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004089 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00004090 Instruction &I) {
4091 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4092 if (!LHSI || LHSI->getNumOperands() != 2 ||
4093 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4094
4095 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4096
4097 switch (LHSI->getOpcode()) {
4098 default: return 0;
4099 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00004100 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004101 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004102 if ((Mask->getValue().countLeadingZeros() +
4103 Mask->getValue().countPopulation()) ==
4104 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004105 break;
4106
4107 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4108 // part, we don't need any explicit masks to take them out of A. If that
4109 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004110 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004111 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004112 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004113 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004114 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004115 break;
4116 }
4117 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004118 return 0;
4119 case Instruction::Or:
4120 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004121 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004122 if ((Mask->getValue().countLeadingZeros() +
4123 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00004124 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004125 break;
4126 return 0;
4127 }
4128
Chris Lattnerc8e77562005-09-18 04:24:45 +00004129 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00004130 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4131 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004132}
4133
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004134/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4135Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4136 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner3f40e232009-11-29 00:51:17 +00004137 // (icmp eq A, null) & (icmp eq B, null) -->
4138 // (icmp eq (ptrtoint(A)|ptrtoint(B)), 0)
4139 if (TD &&
4140 LHS->getPredicate() == ICmpInst::ICMP_EQ &&
4141 RHS->getPredicate() == ICmpInst::ICMP_EQ &&
4142 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4143 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4144 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4145 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4146 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4147 Value *NewOr = Builder->CreateOr(A, B);
4148 return new ICmpInst(ICmpInst::ICMP_EQ, NewOr,
4149 Constant::getNullValue(IntPtrTy));
4150 }
4151
Chris Lattnerea065fb2008-11-16 05:10:52 +00004152 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004153 ConstantInt *LHSCst, *RHSCst;
4154 ICmpInst::Predicate LHSCC, RHSCC;
4155
Chris Lattnerea065fb2008-11-16 05:10:52 +00004156 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004157 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004158 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004159 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004160 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004161 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00004162
Chris Lattner3f40e232009-11-29 00:51:17 +00004163 if (LHSCst == RHSCst && LHSCC == RHSCC) {
4164 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4165 // where C is a power of 2
4166 if (LHSCC == ICmpInst::ICMP_ULT &&
4167 LHSCst->getValue().isPowerOf2()) {
4168 Value *NewOr = Builder->CreateOr(Val, Val2);
4169 return new ICmpInst(LHSCC, NewOr, LHSCst);
4170 }
4171
4172 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4173 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4174 Value *NewOr = Builder->CreateOr(Val, Val2);
4175 return new ICmpInst(LHSCC, NewOr, LHSCst);
4176 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00004177 }
4178
4179 // From here on, we only handle:
4180 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4181 if (Val != Val2) return 0;
4182
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004183 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4184 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4185 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4186 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4187 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4188 return 0;
4189
4190 // We can't fold (ugt x, C) & (sgt x, C2).
4191 if (!PredicatesFoldable(LHSCC, RHSCC))
4192 return 0;
4193
4194 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00004195 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004196 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004197 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004198 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00004199 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004200 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00004201 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4202
4203 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004204 std::swap(LHS, RHS);
4205 std::swap(LHSCst, RHSCst);
4206 std::swap(LHSCC, RHSCC);
4207 }
4208
4209 // At this point, we know we have have two icmp instructions
4210 // comparing a value against two constants and and'ing the result
4211 // together. Because of the above check, we know that we only have
4212 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4213 // (from the FoldICmpLogical check above), that the two constants
4214 // are not equal and that the larger constant is on the RHS
4215 assert(LHSCst != RHSCst && "Compares not folded above?");
4216
4217 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004218 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004219 case ICmpInst::ICMP_EQ:
4220 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004221 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004222 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4223 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4224 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004225 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004226 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4227 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4228 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4229 return ReplaceInstUsesWith(I, LHS);
4230 }
4231 case ICmpInst::ICMP_NE:
4232 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004233 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004234 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00004235 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004236 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004237 break; // (X != 13 & X u< 15) -> no change
4238 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00004239 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004240 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004241 break; // (X != 13 & X s< 15) -> no change
4242 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4243 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4244 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4245 return ReplaceInstUsesWith(I, RHS);
4246 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004247 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00004248 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004249 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004250 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00004251 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004252 }
4253 break; // (X != 13 & X != 15) -> no change
4254 }
4255 break;
4256 case ICmpInst::ICMP_ULT:
4257 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004258 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004259 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4260 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004261 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004262 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4263 break;
4264 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4265 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4266 return ReplaceInstUsesWith(I, LHS);
4267 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4268 break;
4269 }
4270 break;
4271 case ICmpInst::ICMP_SLT:
4272 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004273 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004274 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4275 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004276 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004277 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4278 break;
4279 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4280 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4281 return ReplaceInstUsesWith(I, LHS);
4282 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4283 break;
4284 }
4285 break;
4286 case ICmpInst::ICMP_UGT:
4287 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004288 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004289 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4290 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4291 return ReplaceInstUsesWith(I, RHS);
4292 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4293 break;
4294 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004295 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004296 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004297 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004298 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004299 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004300 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004301 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4302 break;
4303 }
4304 break;
4305 case ICmpInst::ICMP_SGT:
4306 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004307 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004308 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4309 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4310 return ReplaceInstUsesWith(I, RHS);
4311 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4312 break;
4313 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004314 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004315 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004316 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004317 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004318 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004319 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004320 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4321 break;
4322 }
4323 break;
4324 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004325
4326 return 0;
4327}
4328
Chris Lattner42d1be02009-07-23 05:14:02 +00004329Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4330 FCmpInst *RHS) {
4331
4332 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4333 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4334 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4335 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4336 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4337 // If either of the constants are nans, then the whole thing returns
4338 // false.
4339 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004340 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004341 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004342 LHS->getOperand(0), RHS->getOperand(0));
4343 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004344
4345 // Handle vector zeros. This occurs because the canonical form of
4346 // "fcmp ord x,x" is "fcmp ord x, 0".
4347 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4348 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004349 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004350 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004351 return 0;
4352 }
4353
4354 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4355 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4356 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4357
4358
4359 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4360 // Swap RHS operands to match LHS.
4361 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4362 std::swap(Op1LHS, Op1RHS);
4363 }
4364
4365 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4366 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4367 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004368 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004369
4370 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004371 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004372 if (Op0CC == FCmpInst::FCMP_TRUE)
4373 return ReplaceInstUsesWith(I, RHS);
4374 if (Op1CC == FCmpInst::FCMP_TRUE)
4375 return ReplaceInstUsesWith(I, LHS);
4376
4377 bool Op0Ordered;
4378 bool Op1Ordered;
4379 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4380 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4381 if (Op1Pred == 0) {
4382 std::swap(LHS, RHS);
4383 std::swap(Op0Pred, Op1Pred);
4384 std::swap(Op0Ordered, Op1Ordered);
4385 }
4386 if (Op0Pred == 0) {
4387 // uno && ueq -> uno && (uno || eq) -> ueq
4388 // ord && olt -> ord && (ord && lt) -> olt
4389 if (Op0Ordered == Op1Ordered)
4390 return ReplaceInstUsesWith(I, RHS);
4391
4392 // uno && oeq -> uno && (ord && eq) -> false
4393 // uno && ord -> false
4394 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004395 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004396 // ord && ueq -> ord && (uno || eq) -> oeq
4397 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4398 Op0LHS, Op0RHS, Context));
4399 }
4400 }
4401
4402 return 0;
4403}
4404
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004405
Chris Lattner7e708292002-06-25 16:13:24 +00004406Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004407 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004408 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004409
Chris Lattnerd06094f2009-11-10 00:55:12 +00004410 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4411 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004412
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004413 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004414 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004415 if (SimplifyDemandedInstructionBits(I))
4416 return &I;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004417
Dan Gohman6de29f82009-06-15 22:12:54 +00004418
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004419 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004420 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004421 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004422
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004423 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004424 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004425 Value *Op0LHS = Op0I->getOperand(0);
4426 Value *Op0RHS = Op0I->getOperand(1);
4427 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004428 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004429 case Instruction::Xor:
4430 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004431 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004432 if (!Op0I->hasOneUse()) break;
4433
4434 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4435 // Not masking anything out for the LHS, move to RHS.
4436 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4437 Op0RHS->getName()+".masked");
4438 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4439 }
4440 if (!isa<Constant>(Op0RHS) &&
4441 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4442 // Not masking anything out for the RHS, move to LHS.
4443 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4444 Op0LHS->getName()+".masked");
4445 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004446 }
4447
Chris Lattner6e7ba452005-01-01 16:22:27 +00004448 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004449 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004450 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4451 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4452 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4453 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004454 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004455 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004456 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004457 break;
4458
4459 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004460 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4461 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4462 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4463 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004464 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004465
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004466 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4467 // has 1's for all bits that the subtraction with A might affect.
4468 if (Op0I->hasOneUse()) {
4469 uint32_t BitWidth = AndRHSMask.getBitWidth();
4470 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4471 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4472
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004473 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004474 if (!(A && A->isZero()) && // avoid infinite recursion.
4475 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004476 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004477 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4478 }
4479 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004480 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004481
4482 case Instruction::Shl:
4483 case Instruction::LShr:
4484 // (1 << x) & 1 --> zext(x == 0)
4485 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004486 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004487 Value *NewICmp =
4488 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004489 return new ZExtInst(NewICmp, I.getType());
4490 }
4491 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004492 }
4493
Chris Lattner58403262003-07-23 19:25:52 +00004494 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004495 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004496 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004497 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004498 // If this is an integer truncation or change from signed-to-unsigned, and
4499 // if the source is an and/or with immediate, transform it. This
4500 // frequently occurs for bitfield accesses.
4501 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004502 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004503 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004504 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004505 if (CastOp->getOpcode() == Instruction::And) {
4506 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004507 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4508 // This will fold the two constants together, which may allow
4509 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004510 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004511 CastOp->getOperand(0), I.getType(),
4512 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004513 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004514 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004515 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004516 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004517 } else if (CastOp->getOpcode() == Instruction::Or) {
4518 // Change: and (cast (or X, C1) to T), C2
4519 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004520 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004521 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004522 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004523 return ReplaceInstUsesWith(I, AndRHS);
4524 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004525 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004526 }
Chris Lattner06782f82003-07-23 19:36:21 +00004527 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004528
4529 // Try to fold constant and into select arguments.
4530 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004531 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004532 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004533 if (isa<PHINode>(Op0))
4534 if (Instruction *NV = FoldOpIntoPhi(I))
4535 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004536 }
4537
Chris Lattner5b62aa72004-06-18 06:07:51 +00004538
Misha Brukmancb6267b2004-07-30 12:50:08 +00004539 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00004540 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4541 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4542 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4543 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4544 I.getName()+".demorgan");
4545 return BinaryOperator::CreateNot(Or);
4546 }
4547
Chris Lattner2082ad92006-02-13 23:07:23 +00004548 {
Chris Lattner003b6202007-06-15 05:58:24 +00004549 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004550 // (A|B) & ~(A&B) -> A^B
4551 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4552 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4553 ((A == C && B == D) || (A == D && B == C)))
4554 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004555
Chris Lattnerd06094f2009-11-10 00:55:12 +00004556 // ~(A&B) & (A|B) -> A^B
4557 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4558 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4559 ((A == C && B == D) || (A == D && B == C)))
4560 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00004561
4562 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004563 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004564 if (A == Op1) { // (A^B)&A -> A&(A^B)
4565 I.swapOperands(); // Simplify below
4566 std::swap(Op0, Op1);
4567 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4568 cast<BinaryOperator>(Op0)->swapOperands();
4569 I.swapOperands(); // Simplify below
4570 std::swap(Op0, Op1);
4571 }
4572 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004573
Chris Lattner64daab52006-04-01 08:03:55 +00004574 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004575 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004576 if (B == Op0) { // B&(A^B) -> B&(B^A)
4577 cast<BinaryOperator>(Op1)->swapOperands();
4578 std::swap(A, B);
4579 }
Chris Lattner74381062009-08-30 07:44:24 +00004580 if (A == Op0) // A&(A^B) -> A & ~B
4581 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004582 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004583
4584 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004585 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4586 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004587 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004588 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4589 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004590 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004591 }
4592
Reid Spencere4d87aa2006-12-23 06:05:41 +00004593 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4594 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004595 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004596 return R;
4597
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004598 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4599 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4600 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004601 }
4602
Chris Lattner6fc205f2006-05-05 06:39:07 +00004603 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004604 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4605 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4606 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4607 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004608 if (SrcTy == Op1C->getOperand(0)->getType() &&
4609 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004610 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004611 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4612 I.getType(), TD) &&
4613 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4614 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004615 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4616 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004617 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004618 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004619 }
Chris Lattnere511b742006-11-14 07:46:50 +00004620
4621 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004622 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4623 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4624 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004625 SI0->getOperand(1) == SI1->getOperand(1) &&
4626 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004627 Value *NewOp =
4628 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4629 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004630 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004631 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004632 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004633 }
4634
Evan Cheng8db90722008-10-14 17:15:11 +00004635 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004636 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004637 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4638 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4639 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004640 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004641
Chris Lattner7e708292002-06-25 16:13:24 +00004642 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004643}
4644
Chris Lattner8c34cd22008-10-05 02:13:19 +00004645/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4646/// capable of providing pieces of a bswap. The subexpression provides pieces
4647/// of a bswap if it is proven that each of the non-zero bytes in the output of
4648/// the expression came from the corresponding "byte swapped" byte in some other
4649/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4650/// we know that the expression deposits the low byte of %X into the high byte
4651/// of the bswap result and that all other bytes are zero. This expression is
4652/// accepted, the high byte of ByteValues is set to X to indicate a correct
4653/// match.
4654///
4655/// This function returns true if the match was unsuccessful and false if so.
4656/// On entry to the function the "OverallLeftShift" is a signed integer value
4657/// indicating the number of bytes that the subexpression is later shifted. For
4658/// example, if the expression is later right shifted by 16 bits, the
4659/// OverallLeftShift value would be -2 on entry. This is used to specify which
4660/// byte of ByteValues is actually being set.
4661///
4662/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4663/// byte is masked to zero by a user. For example, in (X & 255), X will be
4664/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4665/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4666/// always in the local (OverallLeftShift) coordinate space.
4667///
4668static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4669 SmallVector<Value*, 8> &ByteValues) {
4670 if (Instruction *I = dyn_cast<Instruction>(V)) {
4671 // If this is an or instruction, it may be an inner node of the bswap.
4672 if (I->getOpcode() == Instruction::Or) {
4673 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4674 ByteValues) ||
4675 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4676 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004677 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004678
4679 // If this is a logical shift by a constant multiple of 8, recurse with
4680 // OverallLeftShift and ByteMask adjusted.
4681 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4682 unsigned ShAmt =
4683 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4684 // Ensure the shift amount is defined and of a byte value.
4685 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4686 return true;
4687
4688 unsigned ByteShift = ShAmt >> 3;
4689 if (I->getOpcode() == Instruction::Shl) {
4690 // X << 2 -> collect(X, +2)
4691 OverallLeftShift += ByteShift;
4692 ByteMask >>= ByteShift;
4693 } else {
4694 // X >>u 2 -> collect(X, -2)
4695 OverallLeftShift -= ByteShift;
4696 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004697 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004698 }
4699
4700 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4701 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4702
4703 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4704 ByteValues);
4705 }
4706
4707 // If this is a logical 'and' with a mask that clears bytes, clear the
4708 // corresponding bytes in ByteMask.
4709 if (I->getOpcode() == Instruction::And &&
4710 isa<ConstantInt>(I->getOperand(1))) {
4711 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4712 unsigned NumBytes = ByteValues.size();
4713 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4714 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4715
4716 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4717 // If this byte is masked out by a later operation, we don't care what
4718 // the and mask is.
4719 if ((ByteMask & (1 << i)) == 0)
4720 continue;
4721
4722 // If the AndMask is all zeros for this byte, clear the bit.
4723 APInt MaskB = AndMask & Byte;
4724 if (MaskB == 0) {
4725 ByteMask &= ~(1U << i);
4726 continue;
4727 }
4728
4729 // If the AndMask is not all ones for this byte, it's not a bytezap.
4730 if (MaskB != Byte)
4731 return true;
4732
4733 // Otherwise, this byte is kept.
4734 }
4735
4736 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4737 ByteValues);
4738 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004739 }
4740
Chris Lattner8c34cd22008-10-05 02:13:19 +00004741 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4742 // the input value to the bswap. Some observations: 1) if more than one byte
4743 // is demanded from this input, then it could not be successfully assembled
4744 // into a byteswap. At least one of the two bytes would not be aligned with
4745 // their ultimate destination.
4746 if (!isPowerOf2_32(ByteMask)) return true;
4747 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004748
Chris Lattner8c34cd22008-10-05 02:13:19 +00004749 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4750 // is demanded, it needs to go into byte 0 of the result. This means that the
4751 // byte needs to be shifted until it lands in the right byte bucket. The
4752 // shift amount depends on the position: if the byte is coming from the high
4753 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4754 // low part, it must be shifted left.
4755 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4756 if (InputByteNo < ByteValues.size()/2) {
4757 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4758 return true;
4759 } else {
4760 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4761 return true;
4762 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004763
4764 // If the destination byte value is already defined, the values are or'd
4765 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004766 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004767 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004768 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004769 return false;
4770}
4771
4772/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4773/// If so, insert the new bswap intrinsic and return it.
4774Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004775 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004776 if (!ITy || ITy->getBitWidth() % 16 ||
4777 // ByteMask only allows up to 32-byte values.
4778 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004779 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004780
4781 /// ByteValues - For each byte of the result, we keep track of which value
4782 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004783 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004784 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004785
4786 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004787 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4788 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004789 return 0;
4790
4791 // Check to see if all of the bytes come from the same value.
4792 Value *V = ByteValues[0];
4793 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4794
4795 // Check to make sure that all of the bytes come from the same value.
4796 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4797 if (ByteValues[i] != V)
4798 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004799 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004800 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004801 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004802 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004803}
4804
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004805/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4806/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4807/// we can simplify this expression to "cond ? C : D or B".
4808static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004809 Value *C, Value *D,
4810 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004811 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004812 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004813 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004814 return 0;
4815
Chris Lattnera6a474d2008-11-16 04:26:55 +00004816 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004817 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004818 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004819 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004820 return SelectInst::Create(Cond, C, B);
4821 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004822 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004823 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004824 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004825 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004826 return 0;
4827}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004828
Chris Lattner69d4ced2008-11-16 05:20:07 +00004829/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4830Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4831 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner3f40e232009-11-29 00:51:17 +00004832 // (icmp ne A, null) | (icmp ne B, null) -->
4833 // (icmp ne (ptrtoint(A)|ptrtoint(B)), 0)
4834 if (TD &&
4835 LHS->getPredicate() == ICmpInst::ICMP_NE &&
4836 RHS->getPredicate() == ICmpInst::ICMP_NE &&
4837 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4838 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4839 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4840 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4841 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4842 Value *NewOr = Builder->CreateOr(A, B);
4843 return new ICmpInst(ICmpInst::ICMP_NE, NewOr,
4844 Constant::getNullValue(IntPtrTy));
4845 }
4846
Chris Lattner69d4ced2008-11-16 05:20:07 +00004847 Value *Val, *Val2;
4848 ConstantInt *LHSCst, *RHSCst;
4849 ICmpInst::Predicate LHSCC, RHSCC;
4850
4851 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00004852 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4853 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004854 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00004855
4856
4857 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4858 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4859 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4860 Value *NewOr = Builder->CreateOr(Val, Val2);
4861 return new ICmpInst(LHSCC, NewOr, LHSCst);
4862 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00004863
4864 // From here on, we only handle:
4865 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4866 if (Val != Val2) return 0;
4867
4868 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4869 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4870 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4871 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4872 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4873 return 0;
4874
4875 // We can't fold (ugt x, C) | (sgt x, C2).
4876 if (!PredicatesFoldable(LHSCC, RHSCC))
4877 return 0;
4878
4879 // Ensure that the larger constant is on the RHS.
4880 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004881 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004882 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004883 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004884 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4885 else
4886 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4887
4888 if (ShouldSwap) {
4889 std::swap(LHS, RHS);
4890 std::swap(LHSCst, RHSCst);
4891 std::swap(LHSCC, RHSCC);
4892 }
4893
4894 // At this point, we know we have have two icmp instructions
4895 // comparing a value against two constants and or'ing the result
4896 // together. Because of the above check, we know that we only have
4897 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4898 // FoldICmpLogical check above), that the two constants are not
4899 // equal.
4900 assert(LHSCst != RHSCst && "Compares not folded above?");
4901
4902 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004903 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004904 case ICmpInst::ICMP_EQ:
4905 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004906 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004907 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004908 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004909 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004910 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004911 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004912 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004913 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004914 }
4915 break; // (X == 13 | X == 15) -> no change
4916 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4917 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4918 break;
4919 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4920 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4921 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4922 return ReplaceInstUsesWith(I, RHS);
4923 }
4924 break;
4925 case ICmpInst::ICMP_NE:
4926 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004927 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004928 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4929 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4930 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4931 return ReplaceInstUsesWith(I, LHS);
4932 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4933 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4934 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004935 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004936 }
4937 break;
4938 case ICmpInst::ICMP_ULT:
4939 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004940 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004941 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4942 break;
4943 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4944 // If RHSCst is [us]MAXINT, it is always false. Not handling
4945 // this can cause overflow.
4946 if (RHSCst->isMaxValue(false))
4947 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004948 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004949 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004950 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4951 break;
4952 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4953 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4954 return ReplaceInstUsesWith(I, RHS);
4955 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4956 break;
4957 }
4958 break;
4959 case ICmpInst::ICMP_SLT:
4960 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004961 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004962 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4963 break;
4964 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4965 // If RHSCst is [us]MAXINT, it is always false. Not handling
4966 // this can cause overflow.
4967 if (RHSCst->isMaxValue(true))
4968 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004969 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004970 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004971 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4972 break;
4973 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4974 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4975 return ReplaceInstUsesWith(I, RHS);
4976 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4977 break;
4978 }
4979 break;
4980 case ICmpInst::ICMP_UGT:
4981 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004982 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004983 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4984 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4985 return ReplaceInstUsesWith(I, LHS);
4986 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4987 break;
4988 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4989 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004990 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004991 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4992 break;
4993 }
4994 break;
4995 case ICmpInst::ICMP_SGT:
4996 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004997 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004998 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4999 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
5000 return ReplaceInstUsesWith(I, LHS);
5001 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
5002 break;
5003 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
5004 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005005 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00005006 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
5007 break;
5008 }
5009 break;
5010 }
5011 return 0;
5012}
5013
Chris Lattner5414cc52009-07-23 05:46:22 +00005014Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
5015 FCmpInst *RHS) {
5016 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
5017 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
5018 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
5019 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
5020 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
5021 // If either of the constants are nans, then the whole thing returns
5022 // true.
5023 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00005024 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00005025
5026 // Otherwise, no need to compare the two constants, compare the
5027 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005028 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00005029 LHS->getOperand(0), RHS->getOperand(0));
5030 }
5031
5032 // Handle vector zeros. This occurs because the canonical form of
5033 // "fcmp uno x,x" is "fcmp uno x, 0".
5034 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
5035 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005036 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00005037 LHS->getOperand(0), RHS->getOperand(0));
5038
5039 return 0;
5040 }
5041
5042 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
5043 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
5044 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
5045
5046 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
5047 // Swap RHS operands to match LHS.
5048 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
5049 std::swap(Op1LHS, Op1RHS);
5050 }
5051 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
5052 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
5053 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005054 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00005055 Op0LHS, Op0RHS);
5056 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005057 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00005058 if (Op0CC == FCmpInst::FCMP_FALSE)
5059 return ReplaceInstUsesWith(I, RHS);
5060 if (Op1CC == FCmpInst::FCMP_FALSE)
5061 return ReplaceInstUsesWith(I, LHS);
5062 bool Op0Ordered;
5063 bool Op1Ordered;
5064 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
5065 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
5066 if (Op0Ordered == Op1Ordered) {
5067 // If both are ordered or unordered, return a new fcmp with
5068 // or'ed predicates.
5069 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5070 Op0LHS, Op0RHS, Context);
5071 if (Instruction *I = dyn_cast<Instruction>(RV))
5072 return I;
5073 // Otherwise, it's a constant boolean value...
5074 return ReplaceInstUsesWith(I, RV);
5075 }
5076 }
5077 return 0;
5078}
5079
Bill Wendlinga698a472008-12-01 08:23:25 +00005080/// FoldOrWithConstants - This helper function folds:
5081///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005082/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00005083///
5084/// into:
5085///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005086/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00005087///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005088/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00005089Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00005090 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00005091 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5092 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005093
Bill Wendling286a0542008-12-02 06:24:20 +00005094 Value *V1 = 0;
5095 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005096 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005097
Bill Wendling29976b92008-12-02 06:18:11 +00005098 APInt Xor = CI1->getValue() ^ CI2->getValue();
5099 if (!Xor.isAllOnesValue()) return 0;
5100
Bill Wendling286a0542008-12-02 06:24:20 +00005101 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00005102 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00005103 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00005104 }
5105
5106 return 0;
5107}
5108
Chris Lattner7e708292002-06-25 16:13:24 +00005109Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005110 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005111 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005112
Chris Lattnerd06094f2009-11-10 00:55:12 +00005113 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5114 return ReplaceInstUsesWith(I, V);
5115
5116
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005117 // See if we can simplify any instructions used by the instruction whose sole
5118 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005119 if (SimplifyDemandedInstructionBits(I))
5120 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00005121
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005122 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00005123 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005124 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005125 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005126 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005127 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005128 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005129 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005130 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005131 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005132
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005133 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005134 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005135 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005136 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005137 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005138 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005139 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005140 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005141
5142 // Try to fold constant and into select arguments.
5143 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005144 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005145 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005146 if (isa<PHINode>(Op0))
5147 if (Instruction *NV = FoldOpIntoPhi(I))
5148 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005149 }
5150
Chris Lattner4f637d42006-01-06 17:59:59 +00005151 Value *A = 0, *B = 0;
5152 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005153
Chris Lattner6423d4c2006-07-10 20:25:24 +00005154 // (A | B) | C and A | (B | C) -> bswap if possible.
5155 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00005156 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5157 match(Op1, m_Or(m_Value(), m_Value())) ||
5158 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5159 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00005160 if (Instruction *BSwap = MatchBSwap(I))
5161 return BSwap;
5162 }
5163
Chris Lattner6e4c6492005-05-09 04:58:36 +00005164 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005165 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005166 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005167 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005168 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00005169 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005170 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005171 }
5172
5173 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005174 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005175 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005176 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005177 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00005178 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005179 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005180 }
5181
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005182 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00005183 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005184 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5185 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005186 Value *V1 = 0, *V2 = 0, *V3 = 0;
5187 C1 = dyn_cast<ConstantInt>(C);
5188 C2 = dyn_cast<ConstantInt>(D);
5189 if (C1 && C2) { // (A & C1)|(B & C2)
5190 // If we have: ((V + N) & C1) | (V & C2)
5191 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5192 // replace with V+N.
5193 if (C1->getValue() == ~C2->getValue()) {
5194 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00005195 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005196 // Add commutes, try both ways.
5197 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5198 return ReplaceInstUsesWith(I, A);
5199 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5200 return ReplaceInstUsesWith(I, A);
5201 }
5202 // Or commutes, try both ways.
5203 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005204 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005205 // Add commutes, try both ways.
5206 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5207 return ReplaceInstUsesWith(I, B);
5208 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5209 return ReplaceInstUsesWith(I, B);
5210 }
5211 }
Chris Lattner044e5332007-04-08 08:01:49 +00005212 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00005213 }
5214
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005215 // Check to see if we have any common things being and'ed. If so, find the
5216 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005217 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5218 if (A == B) // (A & C)|(A & D) == A & (C|D)
5219 V1 = A, V2 = C, V3 = D;
5220 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5221 V1 = A, V2 = B, V3 = C;
5222 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5223 V1 = C, V2 = A, V3 = D;
5224 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5225 V1 = C, V2 = A, V3 = B;
5226
5227 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00005228 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005229 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00005230 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005231 }
Dan Gohmanb493b272008-10-28 22:38:57 +00005232
Dan Gohman1975d032008-10-30 20:40:10 +00005233 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005234 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005235 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005236 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005237 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005238 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005239 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005240 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005241 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00005242
Bill Wendlingb01865c2008-11-30 13:52:49 +00005243 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005244 if ((match(C, m_Not(m_Specific(D))) &&
5245 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005246 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005247 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005248 if ((match(A, m_Not(m_Specific(D))) &&
5249 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005250 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005251 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005252 if ((match(C, m_Not(m_Specific(B))) &&
5253 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005254 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005255 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005256 if ((match(A, m_Not(m_Specific(B))) &&
5257 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005258 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005259 }
Chris Lattnere511b742006-11-14 07:46:50 +00005260
5261 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00005262 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5263 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5264 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00005265 SI0->getOperand(1) == SI1->getOperand(1) &&
5266 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005267 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5268 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005269 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005270 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005271 }
5272 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005273
Bill Wendlingb3833d12008-12-01 01:07:11 +00005274 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005275 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5276 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005277 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005278 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005279 }
5280 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005281 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5282 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005283 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005284 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005285 }
5286
Chris Lattnerd06094f2009-11-10 00:55:12 +00005287 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5288 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5289 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5290 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5291 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5292 I.getName()+".demorgan");
5293 return BinaryOperator::CreateNot(And);
5294 }
Chris Lattnera2881962003-02-18 19:28:33 +00005295
Reid Spencere4d87aa2006-12-23 06:05:41 +00005296 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5297 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005298 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005299 return R;
5300
Chris Lattner69d4ced2008-11-16 05:20:07 +00005301 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5302 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5303 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005304 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005305
5306 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005307 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005308 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005309 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005310 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5311 !isa<ICmpInst>(Op1C->getOperand(0))) {
5312 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005313 if (SrcTy == Op1C->getOperand(0)->getType() &&
5314 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005315 // Only do this if the casts both really cause code to be
5316 // generated.
5317 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5318 I.getType(), TD) &&
5319 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5320 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005321 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5322 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005323 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005324 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005325 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005326 }
Chris Lattner99c65742007-10-24 05:38:08 +00005327 }
5328
5329
5330 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5331 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005332 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5333 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5334 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005335 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005336
Chris Lattner7e708292002-06-25 16:13:24 +00005337 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005338}
5339
Dan Gohman844731a2008-05-13 00:00:25 +00005340namespace {
5341
Chris Lattnerc317d392004-02-16 01:20:27 +00005342// XorSelf - Implements: X ^ X --> 0
5343struct XorSelf {
5344 Value *RHS;
5345 XorSelf(Value *rhs) : RHS(rhs) {}
5346 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5347 Instruction *apply(BinaryOperator &Xor) const {
5348 return &Xor;
5349 }
5350};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005351
Dan Gohman844731a2008-05-13 00:00:25 +00005352}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005353
Chris Lattner7e708292002-06-25 16:13:24 +00005354Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005355 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005356 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005357
Evan Chengd34af782008-03-25 20:07:13 +00005358 if (isa<UndefValue>(Op1)) {
5359 if (isa<UndefValue>(Op0))
5360 // Handle undef ^ undef -> 0 special case. This is a common
5361 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005362 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005363 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005364 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005365
Chris Lattnerc317d392004-02-16 01:20:27 +00005366 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005367 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005368 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005369 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005370 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005371
5372 // See if we can simplify any instructions used by the instruction whose sole
5373 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005374 if (SimplifyDemandedInstructionBits(I))
5375 return &I;
5376 if (isa<VectorType>(I.getType()))
5377 if (isa<ConstantAggregateZero>(Op1))
5378 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005379
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005380 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005381 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005382 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5383 if (Op0I->getOpcode() == Instruction::And ||
5384 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005385 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5386 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5387 if (dyn_castNotVal(Op0I->getOperand(1)))
5388 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005389 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005390 Value *NotY =
5391 Builder->CreateNot(Op0I->getOperand(1),
5392 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005393 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005394 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005395 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005396 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005397
5398 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5399 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5400 if (isFreeToInvert(Op0I->getOperand(0)) &&
5401 isFreeToInvert(Op0I->getOperand(1))) {
5402 Value *NotX =
5403 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5404 Value *NotY =
5405 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5406 if (Op0I->getOpcode() == Instruction::And)
5407 return BinaryOperator::CreateOr(NotX, NotY);
5408 return BinaryOperator::CreateAnd(NotX, NotY);
5409 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005410 }
5411 }
5412 }
5413
5414
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005415 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005416 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005417 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005418 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005419 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005420 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005421
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005422 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005423 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005424 FCI->getOperand(0), FCI->getOperand(1));
5425 }
5426
Nick Lewycky517e1f52008-05-31 19:01:33 +00005427 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5428 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5429 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5430 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5431 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005432 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5433 (RHS == ConstantExpr::getCast(Opcode,
5434 ConstantInt::getTrue(*Context),
5435 Op0C->getDestTy()))) {
5436 CI->setPredicate(CI->getInversePredicate());
5437 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005438 }
5439 }
5440 }
5441 }
5442
Reid Spencere4d87aa2006-12-23 06:05:41 +00005443 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005444 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005445 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5446 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005447 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5448 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005449 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005450 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005451 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005452
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005453 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005454 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005455 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005456 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005457 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005458 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005459 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005460 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005461 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005462 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005463 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005464 Constant *C = ConstantInt::get(*Context,
5465 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005466 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005467
Chris Lattner7c4049c2004-01-12 19:35:11 +00005468 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005469 } else if (Op0I->getOpcode() == Instruction::Or) {
5470 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005471 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005472 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005473 // Anything in both C1 and C2 is known to be zero, remove it from
5474 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005475 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5476 NewRHS = ConstantExpr::getAnd(NewRHS,
5477 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005478 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005479 I.setOperand(0, Op0I->getOperand(0));
5480 I.setOperand(1, NewRHS);
5481 return &I;
5482 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005483 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005484 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005485 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005486
5487 // Try to fold constant and into select arguments.
5488 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005489 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005490 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005491 if (isa<PHINode>(Op0))
5492 if (Instruction *NV = FoldOpIntoPhi(I))
5493 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005494 }
5495
Dan Gohman186a6362009-08-12 16:04:34 +00005496 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005497 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005498 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005499
Dan Gohman186a6362009-08-12 16:04:34 +00005500 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005501 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005502 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005503
Chris Lattner318bf792007-03-18 22:51:34 +00005504
5505 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5506 if (Op1I) {
5507 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005508 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005509 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005510 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005511 I.swapOperands();
5512 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005513 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005514 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005515 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005516 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005517 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005518 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005519 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005520 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005521 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005522 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005523 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005524 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005525 std::swap(A, B);
5526 }
Chris Lattner318bf792007-03-18 22:51:34 +00005527 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005528 I.swapOperands(); // Simplified below.
5529 std::swap(Op0, Op1);
5530 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005531 }
Chris Lattner318bf792007-03-18 22:51:34 +00005532 }
5533
5534 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5535 if (Op0I) {
5536 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005537 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005538 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005539 if (A == Op1) // (B|A)^B == (A|B)^B
5540 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005541 if (B == Op1) // (A|B)^B == A & ~B
5542 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005543 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005544 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005545 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005546 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005547 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005548 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005549 if (A == Op1) // (A&B)^A -> (B&A)^A
5550 std::swap(A, B);
5551 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005552 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005553 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005554 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005555 }
Chris Lattner318bf792007-03-18 22:51:34 +00005556 }
5557
5558 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5559 if (Op0I && Op1I && Op0I->isShift() &&
5560 Op0I->getOpcode() == Op1I->getOpcode() &&
5561 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5562 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005563 Value *NewOp =
5564 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5565 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005566 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005567 Op1I->getOperand(1));
5568 }
5569
5570 if (Op0I && Op1I) {
5571 Value *A, *B, *C, *D;
5572 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005573 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5574 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005575 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005576 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005577 }
5578 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005579 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5580 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005581 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005582 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005583 }
5584
5585 // (A & B)^(C & D)
5586 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005587 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5588 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005589 // (X & Y)^(X & Y) -> (Y^Z) & X
5590 Value *X = 0, *Y = 0, *Z = 0;
5591 if (A == C)
5592 X = A, Y = B, Z = D;
5593 else if (A == D)
5594 X = A, Y = B, Z = C;
5595 else if (B == C)
5596 X = B, Y = A, Z = D;
5597 else if (B == D)
5598 X = B, Y = A, Z = C;
5599
5600 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005601 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005602 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005603 }
5604 }
5605 }
5606
Reid Spencere4d87aa2006-12-23 06:05:41 +00005607 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5608 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005609 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005610 return R;
5611
Chris Lattner6fc205f2006-05-05 06:39:07 +00005612 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005613 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005614 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005615 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5616 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005617 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005618 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005619 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5620 I.getType(), TD) &&
5621 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5622 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005623 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5624 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005625 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005626 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005627 }
Chris Lattner99c65742007-10-24 05:38:08 +00005628 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005629
Chris Lattner7e708292002-06-25 16:13:24 +00005630 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005631}
5632
Owen Andersond672ecb2009-07-03 00:17:18 +00005633static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005634 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005635 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005636}
Chris Lattnera96879a2004-09-29 17:40:11 +00005637
Dan Gohman6de29f82009-06-15 22:12:54 +00005638static bool HasAddOverflow(ConstantInt *Result,
5639 ConstantInt *In1, ConstantInt *In2,
5640 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005641 if (IsSigned)
5642 if (In2->getValue().isNegative())
5643 return Result->getValue().sgt(In1->getValue());
5644 else
5645 return Result->getValue().slt(In1->getValue());
5646 else
5647 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005648}
5649
Dan Gohman6de29f82009-06-15 22:12:54 +00005650/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005651/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005652static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005653 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005654 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005655 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005656
Dan Gohman6de29f82009-06-15 22:12:54 +00005657 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5658 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005659 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005660 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5661 ExtractElement(In1, Idx, Context),
5662 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005663 IsSigned))
5664 return true;
5665 }
5666 return false;
5667 }
5668
5669 return HasAddOverflow(cast<ConstantInt>(Result),
5670 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5671 IsSigned);
5672}
5673
5674static bool HasSubOverflow(ConstantInt *Result,
5675 ConstantInt *In1, ConstantInt *In2,
5676 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005677 if (IsSigned)
5678 if (In2->getValue().isNegative())
5679 return Result->getValue().slt(In1->getValue());
5680 else
5681 return Result->getValue().sgt(In1->getValue());
5682 else
5683 return Result->getValue().ugt(In1->getValue());
5684}
5685
Dan Gohman6de29f82009-06-15 22:12:54 +00005686/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5687/// overflowed for this type.
5688static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005689 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005690 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005691 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005692
5693 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5694 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005695 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005696 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5697 ExtractElement(In1, Idx, Context),
5698 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005699 IsSigned))
5700 return true;
5701 }
5702 return false;
5703 }
5704
5705 return HasSubOverflow(cast<ConstantInt>(Result),
5706 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5707 IsSigned);
5708}
5709
Chris Lattner10c0d912008-04-22 02:53:33 +00005710
Reid Spencere4d87aa2006-12-23 06:05:41 +00005711/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005712/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005713Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005714 ICmpInst::Predicate Cond,
5715 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005716 // Look through bitcasts.
5717 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5718 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005719
Chris Lattner574da9b2005-01-13 20:14:25 +00005720 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005721 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005722 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005723 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005724 // know pointers can't overflow since the gep is inbounds. See if we can
5725 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005726 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5727
5728 // If not, synthesize the offset the hard way.
5729 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005730 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005731 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005732 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005733 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005734 // If the base pointers are different, but the indices are the same, just
5735 // compare the base pointer.
5736 if (PtrBase != GEPRHS->getOperand(0)) {
5737 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005738 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005739 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005740 if (IndicesTheSame)
5741 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5742 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5743 IndicesTheSame = false;
5744 break;
5745 }
5746
5747 // If all indices are the same, just compare the base pointers.
5748 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005749 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005750 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005751
5752 // Otherwise, the base pointers are different and the indices are
5753 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005754 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005755 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005756
Chris Lattnere9d782b2005-01-13 22:25:21 +00005757 // If one of the GEPs has all zero indices, recurse.
5758 bool AllZeros = true;
5759 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5760 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5761 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5762 AllZeros = false;
5763 break;
5764 }
5765 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005766 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5767 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005768
5769 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005770 AllZeros = true;
5771 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5772 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5773 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5774 AllZeros = false;
5775 break;
5776 }
5777 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005778 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005779
Chris Lattner4401c9c2005-01-14 00:20:05 +00005780 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5781 // If the GEPs only differ by one index, compare it.
5782 unsigned NumDifferences = 0; // Keep track of # differences.
5783 unsigned DiffOperand = 0; // The operand that differs.
5784 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5785 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005786 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5787 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005788 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005789 NumDifferences = 2;
5790 break;
5791 } else {
5792 if (NumDifferences++) break;
5793 DiffOperand = i;
5794 }
5795 }
5796
5797 if (NumDifferences == 0) // SAME GEP?
5798 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005799 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005800 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005801
Chris Lattner4401c9c2005-01-14 00:20:05 +00005802 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005803 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5804 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005805 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005806 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005807 }
5808 }
5809
Reid Spencere4d87aa2006-12-23 06:05:41 +00005810 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005811 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005812 if (TD &&
5813 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005814 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5815 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005816 Value *L = EmitGEPOffset(GEPLHS, *this);
5817 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005818 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005819 }
5820 }
5821 return 0;
5822}
5823
Chris Lattnera5406232008-05-19 20:18:56 +00005824/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5825///
5826Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5827 Instruction *LHSI,
5828 Constant *RHSC) {
5829 if (!isa<ConstantFP>(RHSC)) return 0;
5830 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5831
5832 // Get the width of the mantissa. We don't want to hack on conversions that
5833 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005834 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005835 if (MantissaWidth == -1) return 0; // Unknown.
5836
5837 // Check to see that the input is converted from an integer type that is small
5838 // enough that preserves all bits. TODO: check here for "known" sign bits.
5839 // 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 +00005840 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005841
5842 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005843 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5844 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005845 ++InputSize;
5846
5847 // If the conversion would lose info, don't hack on this.
5848 if ((int)InputSize > MantissaWidth)
5849 return 0;
5850
5851 // Otherwise, we can potentially simplify the comparison. We know that it
5852 // will always come through as an integer value and we know the constant is
5853 // not a NAN (it would have been previously simplified).
5854 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5855
5856 ICmpInst::Predicate Pred;
5857 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005858 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005859 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005860 case FCmpInst::FCMP_OEQ:
5861 Pred = ICmpInst::ICMP_EQ;
5862 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005863 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005864 case FCmpInst::FCMP_OGT:
5865 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5866 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005867 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005868 case FCmpInst::FCMP_OGE:
5869 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5870 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005871 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005872 case FCmpInst::FCMP_OLT:
5873 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5874 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005875 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005876 case FCmpInst::FCMP_OLE:
5877 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5878 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005879 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005880 case FCmpInst::FCMP_ONE:
5881 Pred = ICmpInst::ICMP_NE;
5882 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005883 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005884 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005885 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005886 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005887 }
5888
5889 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5890
5891 // Now we know that the APFloat is a normal number, zero or inf.
5892
Chris Lattner85162782008-05-20 03:50:52 +00005893 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005894 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005895 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005896
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005897 if (!LHSUnsigned) {
5898 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5899 // and large values.
5900 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5901 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5902 APFloat::rmNearestTiesToEven);
5903 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5904 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5905 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005906 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5907 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005908 }
5909 } else {
5910 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5911 // +INF and large values.
5912 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5913 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5914 APFloat::rmNearestTiesToEven);
5915 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5916 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5917 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005918 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5919 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005920 }
Chris Lattnera5406232008-05-19 20:18:56 +00005921 }
5922
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005923 if (!LHSUnsigned) {
5924 // See if the RHS value is < SignedMin.
5925 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5926 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5927 APFloat::rmNearestTiesToEven);
5928 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5929 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5930 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005931 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5932 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005933 }
Chris Lattnera5406232008-05-19 20:18:56 +00005934 }
5935
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005936 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5937 // [0, UMAX], but it may still be fractional. See if it is fractional by
5938 // casting the FP value to the integer value and back, checking for equality.
5939 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005940 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005941 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5942 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005943 if (!RHS.isZero()) {
5944 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005945 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5946 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005947 if (!Equal) {
5948 // If we had a comparison against a fractional value, we have to adjust
5949 // the compare predicate and sometimes the value. RHSC is rounded towards
5950 // zero at this point.
5951 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005952 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005953 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005954 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005955 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005956 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005957 case ICmpInst::ICMP_ULE:
5958 // (float)int <= 4.4 --> int <= 4
5959 // (float)int <= -4.4 --> false
5960 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005961 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005962 break;
5963 case ICmpInst::ICMP_SLE:
5964 // (float)int <= 4.4 --> int <= 4
5965 // (float)int <= -4.4 --> int < -4
5966 if (RHS.isNegative())
5967 Pred = ICmpInst::ICMP_SLT;
5968 break;
5969 case ICmpInst::ICMP_ULT:
5970 // (float)int < -4.4 --> false
5971 // (float)int < 4.4 --> int <= 4
5972 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005973 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005974 Pred = ICmpInst::ICMP_ULE;
5975 break;
5976 case ICmpInst::ICMP_SLT:
5977 // (float)int < -4.4 --> int < -4
5978 // (float)int < 4.4 --> int <= 4
5979 if (!RHS.isNegative())
5980 Pred = ICmpInst::ICMP_SLE;
5981 break;
5982 case ICmpInst::ICMP_UGT:
5983 // (float)int > 4.4 --> int > 4
5984 // (float)int > -4.4 --> true
5985 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005986 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005987 break;
5988 case ICmpInst::ICMP_SGT:
5989 // (float)int > 4.4 --> int > 4
5990 // (float)int > -4.4 --> int >= -4
5991 if (RHS.isNegative())
5992 Pred = ICmpInst::ICMP_SGE;
5993 break;
5994 case ICmpInst::ICMP_UGE:
5995 // (float)int >= -4.4 --> true
5996 // (float)int >= 4.4 --> int > 4
5997 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005998 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005999 Pred = ICmpInst::ICMP_UGT;
6000 break;
6001 case ICmpInst::ICMP_SGE:
6002 // (float)int >= -4.4 --> int >= -4
6003 // (float)int >= 4.4 --> int > 4
6004 if (!RHS.isNegative())
6005 Pred = ICmpInst::ICMP_SGT;
6006 break;
6007 }
Chris Lattnera5406232008-05-19 20:18:56 +00006008 }
6009 }
6010
6011 // Lower this FP comparison into an appropriate integer version of the
6012 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006013 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00006014}
6015
Reid Spencere4d87aa2006-12-23 06:05:41 +00006016Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006017 bool Changed = false;
6018
6019 /// Orders the operands of the compare so that they are listed from most
6020 /// complex to least complex. This puts constants before unary operators,
6021 /// before binary operators.
6022 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6023 I.swapOperands();
6024 Changed = true;
6025 }
6026
Chris Lattner8b170942002-08-09 23:47:40 +00006027 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner58e97462007-01-14 19:42:17 +00006028
Chris Lattner210c5d42009-11-09 23:55:12 +00006029 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
6030 return ReplaceInstUsesWith(I, V);
6031
Chris Lattner58e97462007-01-14 19:42:17 +00006032 // Simplify 'fcmp pred X, X'
6033 if (Op0 == Op1) {
6034 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006035 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00006036 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
6037 case FCmpInst::FCMP_ULT: // True if unordered or less than
6038 case FCmpInst::FCMP_UGT: // True if unordered or greater than
6039 case FCmpInst::FCMP_UNE: // True if unordered or not equal
6040 // Canonicalize these to be 'fcmp uno %X, 0.0'.
6041 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00006042 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00006043 return &I;
6044
6045 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
6046 case FCmpInst::FCMP_OEQ: // True if ordered and equal
6047 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
6048 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
6049 // Canonicalize these to be 'fcmp ord %X, 0.0'.
6050 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00006051 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00006052 return &I;
6053 }
6054 }
6055
Reid Spencere4d87aa2006-12-23 06:05:41 +00006056 // Handle fcmp with constant RHS
6057 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6058 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6059 switch (LHSI->getOpcode()) {
6060 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006061 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6062 // block. If in the same block, we're encouraging jump threading. If
6063 // not, we are just pessimizing the code by making an i1 phi.
6064 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006065 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006066 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006067 break;
Chris Lattnera5406232008-05-19 20:18:56 +00006068 case Instruction::SIToFP:
6069 case Instruction::UIToFP:
6070 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6071 return NV;
6072 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006073 case Instruction::Select:
6074 // If either operand of the select is a constant, we can fold the
6075 // comparison into the select arms, which will cause one to be
6076 // constant folded and the select turned into a bitwise or.
6077 Value *Op1 = 0, *Op2 = 0;
6078 if (LHSI->hasOneUse()) {
6079 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6080 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006081 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006082 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006083 Op2 = Builder->CreateFCmp(I.getPredicate(),
6084 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006085 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6086 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006087 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006088 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006089 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6090 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006091 }
6092 }
6093
6094 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006095 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006096 break;
6097 }
6098 }
6099
6100 return Changed ? &I : 0;
6101}
6102
6103Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006104 bool Changed = false;
6105
6106 /// Orders the operands of the compare so that they are listed from most
6107 /// complex to least complex. This puts constants before unary operators,
6108 /// before binary operators.
6109 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6110 I.swapOperands();
6111 Changed = true;
6112 }
6113
Reid Spencere4d87aa2006-12-23 06:05:41 +00006114 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006115
Chris Lattner210c5d42009-11-09 23:55:12 +00006116 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6117 return ReplaceInstUsesWith(I, V);
6118
6119 const Type *Ty = Op0->getType();
Chris Lattner8b170942002-08-09 23:47:40 +00006120
Reid Spencere4d87aa2006-12-23 06:05:41 +00006121 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006122 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006123 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006124 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006125 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006126 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006127 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006128 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006129 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006130 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006131
Reid Spencere4d87aa2006-12-23 06:05:41 +00006132 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006133 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006134 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006135 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006136 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006137 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006138 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006139 case ICmpInst::ICMP_SGT:
6140 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006141 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006142 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006143 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006144 return BinaryOperator::CreateAnd(Not, Op0);
6145 }
6146 case ICmpInst::ICMP_UGE:
6147 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6148 // FALL THROUGH
6149 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006150 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006151 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006152 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006153 case ICmpInst::ICMP_SGE:
6154 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6155 // FALL THROUGH
6156 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006157 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006158 return BinaryOperator::CreateOr(Not, Op0);
6159 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006160 }
Chris Lattner8b170942002-08-09 23:47:40 +00006161 }
6162
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163 unsigned BitWidth = 0;
6164 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006165 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6166 else if (Ty->isIntOrIntVector())
6167 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006168
6169 bool isSignBit = false;
6170
Dan Gohman81b28ce2008-09-16 18:46:06 +00006171 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006172 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006173 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006174
Chris Lattnerb6566012008-01-05 01:18:20 +00006175 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6176 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006177 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006178 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006179 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006180 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006181
Dan Gohman81b28ce2008-09-16 18:46:06 +00006182 // If we have an icmp le or icmp ge instruction, turn it into the
6183 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner210c5d42009-11-09 23:55:12 +00006184 // them being folded in the code below. The SimplifyICmpInst code has
6185 // already handled the edge cases for us, so we just assert on them.
Chris Lattner84dff672008-07-11 05:08:55 +00006186 switch (I.getPredicate()) {
6187 default: break;
6188 case ICmpInst::ICMP_ULE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006189 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006190 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006191 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006192 case ICmpInst::ICMP_SLE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006193 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006194 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006195 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006196 case ICmpInst::ICMP_UGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006197 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006198 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006199 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006200 case ICmpInst::ICMP_SGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006201 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006202 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006203 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006204 }
6205
Chris Lattner183661e2008-07-11 05:40:05 +00006206 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006207 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006208 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006209 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6210 }
6211
6212 // See if we can fold the comparison based on range information we can get
6213 // by checking whether bits are known to be zero or one in the input.
6214 if (BitWidth != 0) {
6215 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6216 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6217
6218 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006219 isSignBit ? APInt::getSignBit(BitWidth)
6220 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006221 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006222 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006223 if (SimplifyDemandedBits(I.getOperandUse(1),
6224 APInt::getAllOnesValue(BitWidth),
6225 Op1KnownZero, Op1KnownOne, 0))
6226 return &I;
6227
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006228 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006229 // in. Compute the Min, Max and RHS values based on the known bits. For the
6230 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6232 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006233 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006234 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6235 Op0Min, Op0Max);
6236 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6237 Op1Min, Op1Max);
6238 } else {
6239 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6240 Op0Min, Op0Max);
6241 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6242 Op1Min, Op1Max);
6243 }
6244
Chris Lattner183661e2008-07-11 05:40:05 +00006245 // If Min and Max are known to be the same, then SimplifyDemandedBits
6246 // figured out that the LHS is a constant. Just constant fold this now so
6247 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006248 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006249 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006250 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006251 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006252 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006253 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006254
Chris Lattner183661e2008-07-11 05:40:05 +00006255 // Based on the range information we know about the LHS, see if we can
6256 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006257 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006258 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006259 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006260 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006261 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006262 break;
6263 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006264 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006265 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006266 break;
6267 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006268 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006269 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006270 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006271 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006272 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006273 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006274 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6275 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006276 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006277 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006278
6279 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6280 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006281 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006282 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006283 }
Chris Lattner84dff672008-07-11 05:08:55 +00006284 break;
6285 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006286 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006287 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006288 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006289 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006290
6291 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006292 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006293 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6294 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006295 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006296 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006297
6298 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6299 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006300 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006301 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006302 }
Chris Lattner84dff672008-07-11 05:08:55 +00006303 break;
6304 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006305 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006306 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006307 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006308 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006309 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006310 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006311 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6312 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006313 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006314 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006315 }
Chris Lattner84dff672008-07-11 05:08:55 +00006316 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006317 case ICmpInst::ICMP_SGT:
6318 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006319 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006320 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006321 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006322
6323 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006324 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006325 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6326 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006327 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006328 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006329 }
6330 break;
6331 case ICmpInst::ICMP_SGE:
6332 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6333 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006334 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006335 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006336 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006337 break;
6338 case ICmpInst::ICMP_SLE:
6339 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6340 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006341 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006342 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006343 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006344 break;
6345 case ICmpInst::ICMP_UGE:
6346 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6347 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006348 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006349 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006350 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006351 break;
6352 case ICmpInst::ICMP_ULE:
6353 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6354 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006355 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006356 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006357 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006358 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006359 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006360
6361 // Turn a signed comparison into an unsigned one if both operands
6362 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006363 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006364 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6365 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006366 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006367 }
6368
6369 // Test if the ICmpInst instruction is used exclusively by a select as
6370 // part of a minimum or maximum operation. If so, refrain from doing
6371 // any other folding. This helps out other analyses which understand
6372 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6373 // and CodeGen. And in this case, at least one of the comparison
6374 // operands has at least one user besides the compare (the select),
6375 // which would often largely negate the benefit of folding anyway.
6376 if (I.hasOneUse())
6377 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6378 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6379 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6380 return 0;
6381
6382 // See if we are doing a comparison between a constant and an instruction that
6383 // can be folded into the comparison.
6384 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006385 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006386 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006387 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006388 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006389 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6390 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006391 }
6392
Chris Lattner01deb9d2007-04-03 17:43:25 +00006393 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006394 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6395 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6396 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006397 case Instruction::GetElementPtr:
6398 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006399 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006400 bool isAllZeros = true;
6401 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6402 if (!isa<Constant>(LHSI->getOperand(i)) ||
6403 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6404 isAllZeros = false;
6405 break;
6406 }
6407 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006408 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006409 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006410 }
6411 break;
6412
Chris Lattner6970b662005-04-23 15:31:55 +00006413 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006414 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006415 // block. If in the same block, we're encouraging jump threading. If
6416 // not, we are just pessimizing the code by making an i1 phi.
6417 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006418 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006419 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006420 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006421 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006422 // If either operand of the select is a constant, we can fold the
6423 // comparison into the select arms, which will cause one to be
6424 // constant folded and the select turned into a bitwise or.
6425 Value *Op1 = 0, *Op2 = 0;
Eli Friedman97b087c2009-12-18 08:22:35 +00006426 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6427 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6428 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6429 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6430
6431 // We only want to perform this transformation if it will not lead to
6432 // additional code. This is true if either both sides of the select
6433 // fold to a constant (in which case the icmp is replaced with a select
6434 // which will usually simplify) or this is the only user of the
6435 // select (in which case we are trading a select+icmp for a simpler
6436 // select+icmp).
6437 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6438 if (!Op1)
Chris Lattner74381062009-08-30 07:44:24 +00006439 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6440 RHSC, I.getName());
Eli Friedman97b087c2009-12-18 08:22:35 +00006441 if (!Op2)
6442 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6443 RHSC, I.getName());
Gabor Greif051a9502008-04-06 20:25:17 +00006444 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman97b087c2009-12-18 08:22:35 +00006445 }
Chris Lattner6970b662005-04-23 15:31:55 +00006446 break;
6447 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006448 case Instruction::Call:
6449 // If we have (malloc != null), and if the malloc has a single use, we
6450 // can assume it is successful and remove the malloc.
6451 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6452 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006453 // Need to explicitly erase malloc call here, instead of adding it to
6454 // Worklist, because it won't get DCE'd from the Worklist since
6455 // isInstructionTriviallyDead() returns false for function calls.
6456 // It is OK to replace LHSI/MallocCall with Undef because the
6457 // instruction that uses it will be erased via Worklist.
6458 if (extractMallocCall(LHSI)) {
6459 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6460 EraseInstFromFunction(*LHSI);
6461 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006462 ConstantInt::get(Type::getInt1Ty(*Context),
6463 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006464 }
6465 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6466 if (MallocCall->hasOneUse()) {
6467 MallocCall->replaceAllUsesWith(
6468 UndefValue::get(MallocCall->getType()));
6469 EraseInstFromFunction(*MallocCall);
6470 Worklist.Add(LHSI); // The malloc's bitcast use.
6471 return ReplaceInstUsesWith(I,
6472 ConstantInt::get(Type::getInt1Ty(*Context),
6473 !I.isTrueWhenEqual()));
6474 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006475 }
6476 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006477 }
Chris Lattner6970b662005-04-23 15:31:55 +00006478 }
6479
Reid Spencere4d87aa2006-12-23 06:05:41 +00006480 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006481 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006482 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006483 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006484 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006485 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6486 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006487 return NI;
6488
Reid Spencere4d87aa2006-12-23 06:05:41 +00006489 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006490 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6491 // now.
6492 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6493 if (isa<PointerType>(Op0->getType()) &&
6494 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006495 // We keep moving the cast from the left operand over to the right
6496 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006497 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006498
Chris Lattner57d86372007-01-06 01:45:59 +00006499 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6500 // so eliminate it as well.
6501 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6502 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006503
Chris Lattnerde90b762003-11-03 04:25:02 +00006504 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006505 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006506 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006507 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006508 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006509 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006510 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006511 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006512 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006513 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006514 }
Chris Lattner57d86372007-01-06 01:45:59 +00006515 }
6516
6517 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006518 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006519 // This comes up when you have code like
6520 // int X = A < B;
6521 // if (X) ...
6522 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006523 // with a constant or another cast from the same type.
Eli Friedman8e4b1972009-12-17 21:27:47 +00006524 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006525 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006526 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006527 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006528
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006529 // See if it's the same type of instruction on the left and right.
6530 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6531 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006532 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006533 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006534 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006535 default: break;
6536 case Instruction::Add:
6537 case Instruction::Sub:
6538 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006539 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006540 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006541 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006542 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6543 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6544 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006545 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006546 ? I.getUnsignedPredicate()
6547 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006548 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006549 Op1I->getOperand(0));
6550 }
6551
6552 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006553 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006554 ? I.getUnsignedPredicate()
6555 : I.getSignedPredicate();
6556 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006557 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006558 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006559 }
6560 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006561 break;
6562 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006563 if (!I.isEquality())
6564 break;
6565
Nick Lewycky5d52c452008-08-21 05:56:10 +00006566 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6567 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6568 // Mask = -1 >> count-trailing-zeros(Cst).
6569 if (!CI->isZero() && !CI->isOne()) {
6570 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006571 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006572 APInt::getLowBitsSet(AP.getBitWidth(),
6573 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006574 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006575 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6576 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006577 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006578 }
6579 }
6580 break;
6581 }
6582 }
6583 }
6584 }
6585
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006586 // ~x < ~y --> y < x
6587 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006588 if (match(Op0, m_Not(m_Value(A))) &&
6589 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006590 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006591 }
6592
Chris Lattner65b72ba2006-09-18 04:22:48 +00006593 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006594 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006595
6596 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006597 if (match(Op0, m_Neg(m_Value(A))) &&
6598 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006599 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006600
Dan Gohman4ae51262009-08-12 16:23:25 +00006601 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006602 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6603 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006604 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006605 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006606 }
6607
Dan Gohman4ae51262009-08-12 16:23:25 +00006608 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006609 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006610 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006611 if (match(B, m_ConstantInt(C1)) &&
6612 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006613 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006614 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006615 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6616 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006617 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006618
6619 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006620 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6621 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6622 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6623 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006624 }
6625 }
6626
Dan Gohman4ae51262009-08-12 16:23:25 +00006627 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006628 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006629 // A == (A^B) -> B == 0
6630 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006631 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006632 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006633 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006634
6635 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006636 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006637 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006638 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006639
6640 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006641 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006642 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006643 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006644
Chris Lattner9c2328e2006-11-14 06:06:06 +00006645 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6646 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006647 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6648 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006649 Value *X = 0, *Y = 0, *Z = 0;
6650
6651 if (A == C) {
6652 X = B; Y = D; Z = A;
6653 } else if (A == D) {
6654 X = B; Y = C; Z = A;
6655 } else if (B == C) {
6656 X = A; Y = D; Z = B;
6657 } else if (B == D) {
6658 X = A; Y = C; Z = B;
6659 }
6660
6661 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006662 Op1 = Builder->CreateXor(X, Y, "tmp");
6663 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006664 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006665 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006666 return &I;
6667 }
6668 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006669 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006670
6671 {
6672 Value *X; ConstantInt *Cst;
Chris Lattner3bf68152009-12-21 04:04:05 +00006673 // icmp X+Cst, X
Chris Lattner2799baf2009-12-21 03:19:28 +00006674 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006675 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6676
Chris Lattner2799baf2009-12-21 03:19:28 +00006677 // icmp X, X+Cst
6678 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006679 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
Chris Lattner2799baf2009-12-21 03:19:28 +00006680 }
Chris Lattner7e708292002-06-25 16:13:24 +00006681 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006682}
6683
Chris Lattner2799baf2009-12-21 03:19:28 +00006684/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6685Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6686 Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +00006687 ICmpInst::Predicate Pred,
6688 Value *TheAdd) {
Chris Lattner2799baf2009-12-21 03:19:28 +00006689 // If we have X+0, exit early (simplifying logic below) and let it get folded
6690 // elsewhere. icmp X+0, X -> icmp X, X
6691 if (CI->isZero()) {
6692 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6693 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6694 }
6695
6696 // (X+4) == X -> false.
6697 if (Pred == ICmpInst::ICMP_EQ)
6698 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6699
6700 // (X+4) != X -> true.
6701 if (Pred == ICmpInst::ICMP_NE)
6702 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner3bf68152009-12-21 04:04:05 +00006703
6704 // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
6705 bool isNUW = false, isNSW = false;
6706 if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
6707 isNUW = Add->hasNoUnsignedWrap();
6708 isNSW = Add->hasNoSignedWrap();
6709 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006710
6711 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6712 // so the values can never be equal. Similiarly for all other "or equals"
6713 // operators.
6714
6715 // (X+1) <u X --> X >u (MAXUINT-1) --> X != 255
6716 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
6717 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
6718 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Chris Lattner3bf68152009-12-21 04:04:05 +00006719 // If this is an NUW add, then this is always false.
6720 if (isNUW)
6721 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6722
Chris Lattner2799baf2009-12-21 03:19:28 +00006723 Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6724 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6725 }
6726
6727 // (X+1) >u X --> X <u (0-1) --> X != 255
6728 // (X+2) >u X --> X <u (0-2) --> X <u 254
6729 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Chris Lattner3bf68152009-12-21 04:04:05 +00006730 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
6731 // If this is an NUW add, then this is always true.
6732 if (isNUW)
6733 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner2799baf2009-12-21 03:19:28 +00006734 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00006735 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006736
6737 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
6738 ConstantInt *SMax = ConstantInt::get(X->getContext(),
6739 APInt::getSignedMaxValue(BitWidth));
6740
6741 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
6742 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
6743 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
6744 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
6745 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
6746 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Chris Lattner3bf68152009-12-21 04:04:05 +00006747 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
6748 // If this is an NSW add, then we have two cases: if the constant is
6749 // positive, then this is always false, if negative, this is always true.
6750 if (isNSW) {
6751 bool isTrue = CI->getValue().isNegative();
6752 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6753 }
6754
Chris Lattner2799baf2009-12-21 03:19:28 +00006755 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00006756 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006757
6758 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
6759 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
6760 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
6761 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
6762 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
6763 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Chris Lattner3bf68152009-12-21 04:04:05 +00006764
6765 // If this is an NSW add, then we have two cases: if the constant is
6766 // positive, then this is always true, if negative, this is always false.
6767 if (isNSW) {
6768 bool isTrue = !CI->getValue().isNegative();
6769 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6770 }
6771
Chris Lattner2799baf2009-12-21 03:19:28 +00006772 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
6773 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
6774 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
6775}
Chris Lattner562ef782007-06-20 23:46:26 +00006776
6777/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6778/// and CmpRHS are both known to be integer constants.
6779Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6780 ConstantInt *DivRHS) {
6781 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6782 const APInt &CmpRHSV = CmpRHS->getValue();
6783
6784 // FIXME: If the operand types don't match the type of the divide
6785 // then don't attempt this transform. The code below doesn't have the
6786 // logic to deal with a signed divide and an unsigned compare (and
6787 // vice versa). This is because (x /s C1) <s C2 produces different
6788 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6789 // (x /u C1) <u C2. Simply casting the operands and result won't
6790 // work. :( The if statement below tests that condition and bails
6791 // if it finds it.
6792 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006793 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00006794 return 0;
6795 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006796 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006797 if (DivIsSigned && DivRHS->isAllOnesValue())
6798 return 0; // The overflow computation also screws up here
6799 if (DivRHS->isOne())
6800 return 0; // Not worth bothering, and eliminates some funny cases
6801 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006802
6803 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6804 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6805 // C2 (CI). By solving for X we can turn this into a range check
6806 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006807 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006808
6809 // Determine if the product overflows by seeing if the product is
6810 // not equal to the divide. Make sure we do the same kind of divide
6811 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006812 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6813 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006814
6815 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006816 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006817
Chris Lattner1dbfd482007-06-21 18:11:19 +00006818 // Figure out the interval that is being checked. For example, a comparison
6819 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6820 // Compute this interval based on the constants involved and the signedness of
6821 // the compare/divide. This computes a half-open interval, keeping track of
6822 // whether either value in the interval overflows. After analysis each
6823 // overflow variable is set to 0 if it's corresponding bound variable is valid
6824 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6825 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006826 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006827
Chris Lattner562ef782007-06-20 23:46:26 +00006828 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006829 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006830 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006831 HiOverflow = LoOverflow = ProdOV;
6832 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006833 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006834 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006835 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006836 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006837 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006838 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006839 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006840 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6841 HiOverflow = LoOverflow = ProdOV;
6842 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006843 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006844 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006845 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006846 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006847 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6848 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006849 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006850 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006851 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006852 true) ? -1 : 0;
6853 }
Chris Lattner562ef782007-06-20 23:46:26 +00006854 }
Dan Gohman76491272008-02-13 22:09:18 +00006855 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006856 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006857 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006858 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006859 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006860 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6861 HiOverflow = 1; // [INTMIN+1, overflow)
6862 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6863 }
Dan Gohman76491272008-02-13 22:09:18 +00006864 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006865 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006866 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006867 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006868 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006869 LoOverflow = AddWithOverflow(LoBound, HiBound,
6870 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006871 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006872 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6873 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006874 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006875 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006876 }
6877
Chris Lattner1dbfd482007-06-21 18:11:19 +00006878 // Dividing by a negative swaps the condition. LT <-> GT
6879 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006880 }
6881
6882 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006883 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006884 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006885 case ICmpInst::ICMP_EQ:
6886 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006887 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006888 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006889 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006890 ICmpInst::ICMP_UGE, X, LoBound);
6891 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006892 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006893 ICmpInst::ICMP_ULT, X, HiBound);
6894 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006895 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006896 case ICmpInst::ICMP_NE:
6897 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006898 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006899 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006900 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006901 ICmpInst::ICMP_ULT, X, LoBound);
6902 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006903 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006904 ICmpInst::ICMP_UGE, X, HiBound);
6905 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006906 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006907 case ICmpInst::ICMP_ULT:
6908 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006909 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006910 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006911 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006912 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006913 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006914 case ICmpInst::ICMP_UGT:
6915 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006916 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006917 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006918 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006919 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006920 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006921 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006922 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006923 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006924 }
6925}
6926
6927
Chris Lattner01deb9d2007-04-03 17:43:25 +00006928/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6929///
6930Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6931 Instruction *LHSI,
6932 ConstantInt *RHS) {
6933 const APInt &RHSV = RHS->getValue();
6934
6935 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006936 case Instruction::Trunc:
6937 if (ICI.isEquality() && LHSI->hasOneUse()) {
6938 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6939 // of the high bits truncated out of x are known.
6940 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6941 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6942 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6943 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6944 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6945
6946 // If all the high bits are known, we can do this xform.
6947 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6948 // Pull in the high bits from known-ones set.
6949 APInt NewRHS(RHS->getValue());
6950 NewRHS.zext(SrcBits);
6951 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006952 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006953 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006954 }
6955 }
6956 break;
6957
Duncan Sands0091bf22007-04-04 06:42:45 +00006958 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006959 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6960 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6961 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006962 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6963 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006964 Value *CompareVal = LHSI->getOperand(0);
6965
6966 // If the sign bit of the XorCST is not set, there is no change to
6967 // the operation, just stop using the Xor.
6968 if (!XorCST->getValue().isNegative()) {
6969 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006970 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006971 return &ICI;
6972 }
6973
6974 // Was the old condition true if the operand is positive?
6975 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6976
6977 // If so, the new one isn't.
6978 isTrueIfPositive ^= true;
6979
6980 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006981 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006982 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006983 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006984 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006985 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006986 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006987
6988 if (LHSI->hasOneUse()) {
6989 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6990 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6991 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006992 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006993 ? ICI.getUnsignedPredicate()
6994 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006995 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006996 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006997 }
6998
6999 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00007000 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00007001 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00007002 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00007003 ? ICI.getUnsignedPredicate()
7004 : ICI.getSignedPredicate();
7005 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007006 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007007 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00007008 }
7009 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007010 }
7011 break;
7012 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
7013 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
7014 LHSI->getOperand(0)->hasOneUse()) {
7015 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
7016
7017 // If the LHS is an AND of a truncating cast, we can widen the
7018 // and/compare to be the input width without changing the value
7019 // produced, eliminating a cast.
7020 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
7021 // We can do this transformation if either the AND constant does not
7022 // have its sign bit set or if it is an equality comparison.
7023 // Extending a relational comparison when we're checking the sign
7024 // bit would not work.
7025 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00007026 (ICI.isEquality() ||
7027 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007028 uint32_t BitWidth =
7029 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
7030 APInt NewCST = AndCST->getValue();
7031 NewCST.zext(BitWidth);
7032 APInt NewCI = RHSV;
7033 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00007034 Value *NewAnd =
7035 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007036 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007037 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00007038 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007039 }
7040 }
7041
7042 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
7043 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
7044 // happens a LOT in code produced by the C front-end, for bitfield
7045 // access.
7046 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
7047 if (Shift && !Shift->isShift())
7048 Shift = 0;
7049
7050 ConstantInt *ShAmt;
7051 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
7052 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
7053 const Type *AndTy = AndCST->getType(); // Type of the and.
7054
7055 // We can fold this as long as we can't shift unknown bits
7056 // into the mask. This can only happen with signed shift
7057 // rights, as they sign-extend.
7058 if (ShAmt) {
7059 bool CanFold = Shift->isLogicalShift();
7060 if (!CanFold) {
7061 // To test for the bad case of the signed shr, see if any
7062 // of the bits shifted in could be tested after the mask.
7063 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
7064 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
7065
7066 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
7067 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
7068 AndCST->getValue()) == 0)
7069 CanFold = true;
7070 }
7071
7072 if (CanFold) {
7073 Constant *NewCst;
7074 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007075 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007076 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007077 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007078
7079 // Check to see if we are shifting out any of the bits being
7080 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007081 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007082 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007083 // If we shifted bits out, the fold is not going to work out.
7084 // As a special case, check to see if this means that the
7085 // result is always true or false now.
7086 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007087 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007088 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007089 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007090 } else {
7091 ICI.setOperand(1, NewCst);
7092 Constant *NewAndCST;
7093 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007094 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007095 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007096 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007097 LHSI->setOperand(1, NewAndCST);
7098 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00007099 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00007100 return &ICI;
7101 }
7102 }
7103 }
7104
7105 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
7106 // preferable because it allows the C<<Y expression to be hoisted out
7107 // of a loop if Y is invariant and X is not.
7108 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00007109 ICI.isEquality() && !Shift->isArithmeticShift() &&
7110 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007111 // Compute C << Y.
7112 Value *NS;
7113 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00007114 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007115 } else {
7116 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00007117 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007118 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007119
7120 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00007121 Value *NewAnd =
7122 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007123
7124 ICI.setOperand(0, NewAnd);
7125 return &ICI;
7126 }
7127 }
7128 break;
7129
Chris Lattnera0141b92007-07-15 20:42:37 +00007130 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
7131 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7132 if (!ShAmt) break;
7133
7134 uint32_t TypeBits = RHSV.getBitWidth();
7135
7136 // Check that the shift amount is in range. If not, don't perform
7137 // undefined shifts. When the shift is visited it will be
7138 // simplified.
7139 if (ShAmt->uge(TypeBits))
7140 break;
7141
7142 if (ICI.isEquality()) {
7143 // If we are comparing against bits always shifted out, the
7144 // comparison cannot succeed.
7145 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00007146 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00007147 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00007148 if (Comp != RHS) {// Comparing against a bit that we know is zero.
7149 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007150 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00007151 return ReplaceInstUsesWith(ICI, Cst);
7152 }
7153
7154 if (LHSI->hasOneUse()) {
7155 // Otherwise strength reduce the shift into an and.
7156 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7157 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00007158 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00007159 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007160
Chris Lattner74381062009-08-30 07:44:24 +00007161 Value *And =
7162 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007163 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00007164 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007165 }
7166 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007167
7168 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7169 bool TrueIfSigned = false;
7170 if (LHSI->hasOneUse() &&
7171 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7172 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00007173 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00007174 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00007175 Value *And =
7176 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007177 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00007178 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00007179 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007180 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007181 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007182
7183 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00007184 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007185 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00007186 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007187 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007188
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007189 // Check that the shift amount is in range. If not, don't perform
7190 // undefined shifts. When the shift is visited it will be
7191 // simplified.
7192 uint32_t TypeBits = RHSV.getBitWidth();
7193 if (ShAmt->uge(TypeBits))
7194 break;
7195
7196 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007197
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007198 // If we are comparing against bits always shifted out, the
7199 // comparison cannot succeed.
7200 APInt Comp = RHSV << ShAmtVal;
7201 if (LHSI->getOpcode() == Instruction::LShr)
7202 Comp = Comp.lshr(ShAmtVal);
7203 else
7204 Comp = Comp.ashr(ShAmtVal);
7205
7206 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7207 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007208 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007209 return ReplaceInstUsesWith(ICI, Cst);
7210 }
7211
7212 // Otherwise, check to see if the bits shifted out are known to be zero.
7213 // If so, we can compare against the unshifted value:
7214 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007215 if (LHSI->hasOneUse() &&
7216 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007217 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007218 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007219 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007220 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007221
Evan Chengf30752c2008-04-23 00:38:06 +00007222 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007223 // Otherwise strength reduce the shift into an and.
7224 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007225 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007226
Chris Lattner74381062009-08-30 07:44:24 +00007227 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7228 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007229 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007230 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007231 }
7232 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007233 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007234
7235 case Instruction::SDiv:
7236 case Instruction::UDiv:
7237 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7238 // Fold this div into the comparison, producing a range check.
7239 // Determine, based on the divide type, what the range is being
7240 // checked. If there is an overflow on the low or high side, remember
7241 // it, otherwise compute the range [low, hi) bounding the new value.
7242 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007243 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7244 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7245 DivRHS))
7246 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007247 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007248
7249 case Instruction::Add:
Chris Lattner2799baf2009-12-21 03:19:28 +00007250 // Fold: icmp pred (add X, C1), C2
Nick Lewycky5be29202008-02-03 16:33:09 +00007251 if (!ICI.isEquality()) {
7252 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7253 if (!LHSC) break;
7254 const APInt &LHSV = LHSC->getValue();
7255
7256 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7257 .subtract(LHSV);
7258
Nick Lewycky4a134af2009-10-25 05:20:17 +00007259 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007260 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007261 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007262 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007263 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007264 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007265 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007266 }
7267 } else {
7268 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007269 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007270 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007271 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007272 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007273 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007274 }
7275 }
7276 }
7277 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007278 }
7279
7280 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7281 if (ICI.isEquality()) {
7282 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7283
7284 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7285 // the second operand is a constant, simplify a bit.
7286 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7287 switch (BO->getOpcode()) {
7288 case Instruction::SRem:
7289 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7290 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7291 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7292 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007293 Value *NewRem =
7294 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7295 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007296 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007297 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007298 }
7299 }
7300 break;
7301 case Instruction::Add:
7302 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7303 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7304 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007305 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007306 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007307 } else if (RHSV == 0) {
7308 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7309 // efficiently invertible, or if the add has just this one use.
7310 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7311
Dan Gohman186a6362009-08-12 16:04:34 +00007312 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007313 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007314 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007315 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007316 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007317 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007318 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007319 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007320 }
7321 }
7322 break;
7323 case Instruction::Xor:
7324 // For the xor case, we can xor two constants together, eliminating
7325 // the explicit xor.
7326 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007327 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007328 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007329
7330 // FALLTHROUGH
7331 case Instruction::Sub:
7332 // Replace (([sub|xor] A, B) != 0) with (A != B)
7333 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007334 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007335 BO->getOperand(1));
7336 break;
7337
7338 case Instruction::Or:
7339 // If bits are being or'd in that are not present in the constant we
7340 // are comparing against, then the comparison could never succeed!
7341 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007342 Constant *NotCI = ConstantExpr::getNot(RHS);
7343 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007344 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007345 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007346 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007347 }
7348 break;
7349
7350 case Instruction::And:
7351 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7352 // If bits are being compared against that are and'd out, then the
7353 // comparison can never succeed!
7354 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007355 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007356 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007357 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007358
7359 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7360 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007361 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007362 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007363 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007364
7365 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007366 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007367 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007368 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007369 ICmpInst::Predicate pred = isICMP_NE ?
7370 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007371 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007372 }
7373
7374 // ((X & ~7) == 0) --> X < 8
7375 if (RHSV == 0 && isHighOnes(BOC)) {
7376 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007377 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007378 ICmpInst::Predicate pred = isICMP_NE ?
7379 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007380 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007381 }
7382 }
7383 default: break;
7384 }
7385 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7386 // Handle icmp {eq|ne} <intrinsic>, intcst.
7387 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007388 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007389 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007390 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007391 return &ICI;
7392 }
7393 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007394 }
7395 return 0;
7396}
7397
7398/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7399/// We only handle extending casts so far.
7400///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007401Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7402 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007403 Value *LHSCIOp = LHSCI->getOperand(0);
7404 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007405 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007406 Value *RHSCIOp;
7407
Chris Lattner8c756c12007-05-05 22:41:33 +00007408 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7409 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007410 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7411 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007412 cast<IntegerType>(DestTy)->getBitWidth()) {
7413 Value *RHSOp = 0;
7414 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007415 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007416 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7417 RHSOp = RHSC->getOperand(0);
7418 // If the pointer types don't match, insert a bitcast.
7419 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007420 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007421 }
7422
7423 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007424 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007425 }
7426
7427 // The code below only handles extension cast instructions, so far.
7428 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007429 if (LHSCI->getOpcode() != Instruction::ZExt &&
7430 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007431 return 0;
7432
Reid Spencere4d87aa2006-12-23 06:05:41 +00007433 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007434 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007435
Reid Spencere4d87aa2006-12-23 06:05:41 +00007436 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007437 // Not an extension from the same type?
7438 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007439 if (RHSCIOp->getType() != LHSCIOp->getType())
7440 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007441
Nick Lewycky4189a532008-01-28 03:48:02 +00007442 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007443 // and the other is a zext), then we can't handle this.
7444 if (CI->getOpcode() != LHSCI->getOpcode())
7445 return 0;
7446
Nick Lewycky4189a532008-01-28 03:48:02 +00007447 // Deal with equality cases early.
7448 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007449 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007450
7451 // A signed comparison of sign extended values simplifies into a
7452 // signed comparison.
7453 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007454 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007455
7456 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007457 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007458 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007459
Reid Spencere4d87aa2006-12-23 06:05:41 +00007460 // If we aren't dealing with a constant on the RHS, exit early
7461 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7462 if (!CI)
7463 return 0;
7464
7465 // Compute the constant that would happen if we truncated to SrcTy then
7466 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007467 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7468 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007469 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007470
7471 // If the re-extended constant didn't change...
7472 if (Res2 == CI) {
Eli Friedmanb17cb062009-12-17 22:42:29 +00007473 // Deal with equality cases early.
7474 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007475 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedmanb17cb062009-12-17 22:42:29 +00007476
7477 // A signed comparison of sign extended values simplifies into a
7478 // signed comparison.
7479 if (isSignedExt && isSignedCmp)
7480 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7481
7482 // The other three cases all fold into an unsigned comparison.
7483 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007484 }
7485
7486 // The re-extended constant changed so the constant cannot be represented
7487 // in the shorter type. Consequently, we cannot emit a simple comparison.
7488
7489 // First, handle some easy cases. We know the result cannot be equal at this
7490 // point so handle the ICI.isEquality() cases
7491 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007492 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007493 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007494 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007495
7496 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7497 // should have been folded away previously and not enter in here.
7498 Value *Result;
7499 if (isSignedCmp) {
7500 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007501 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007502 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007503 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007504 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007505 } else {
7506 // We're performing an unsigned comparison.
7507 if (isSignedExt) {
7508 // We're performing an unsigned comp with a sign extended value.
7509 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007510 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007511 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007512 } else {
7513 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007514 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007515 }
7516 }
7517
7518 // Finally, return the value computed.
7519 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007520 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007521 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007522
7523 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7524 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7525 "ICmp should be folded!");
7526 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007527 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007528 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007529}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007530
Reid Spencer832254e2007-02-02 02:16:23 +00007531Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7532 return commonShiftTransforms(I);
7533}
7534
7535Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7536 return commonShiftTransforms(I);
7537}
7538
7539Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007540 if (Instruction *R = commonShiftTransforms(I))
7541 return R;
7542
7543 Value *Op0 = I.getOperand(0);
7544
7545 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7546 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7547 if (CSI->isAllOnesValue())
7548 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007549
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007550 // See if we can turn a signed shr into an unsigned shr.
7551 if (MaskedValueIsZero(Op0,
7552 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7553 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7554
7555 // Arithmetic shifting an all-sign-bit value is a no-op.
7556 unsigned NumSignBits = ComputeNumSignBits(Op0);
7557 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7558 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007559
Chris Lattner348f6652007-12-06 01:59:46 +00007560 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007561}
7562
7563Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7564 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007565 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007566
7567 // shl X, 0 == X and shr X, 0 == X
7568 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007569 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7570 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007571 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007572
Reid Spencere4d87aa2006-12-23 06:05:41 +00007573 if (isa<UndefValue>(Op0)) {
7574 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007575 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007576 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007577 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007578 }
7579 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007580 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7581 return ReplaceInstUsesWith(I, Op0);
7582 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007583 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007584 }
7585
Dan Gohman9004c8a2009-05-21 02:28:33 +00007586 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007587 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007588 return &I;
7589
Chris Lattner2eefe512004-04-09 19:05:30 +00007590 // Try to fold constant and into select arguments.
7591 if (isa<Constant>(Op0))
7592 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007593 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007594 return R;
7595
Reid Spencerb83eb642006-10-20 07:07:24 +00007596 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007597 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7598 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007599 return 0;
7600}
7601
Reid Spencerb83eb642006-10-20 07:07:24 +00007602Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007603 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007604 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007605
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007606 // See if we can simplify any instructions used by the instruction whose sole
7607 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007608 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007609
Dan Gohmana119de82009-06-14 23:30:43 +00007610 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7611 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007612 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007613 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007614 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007615 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007616 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007617 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007618 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007619 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007620 }
7621
7622 // ((X*C1) << C2) == (X * (C1 << C2))
7623 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7624 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7625 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007626 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007627 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007628
7629 // Try to fold constant and into select arguments.
7630 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7631 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7632 return R;
7633 if (isa<PHINode>(Op0))
7634 if (Instruction *NV = FoldOpIntoPhi(I))
7635 return NV;
7636
Chris Lattner8999dd32007-12-22 09:07:47 +00007637 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7638 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7639 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7640 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7641 // place. Don't try to do this transformation in this case. Also, we
7642 // require that the input operand is a shift-by-constant so that we have
7643 // confidence that the shifts will get folded together. We could do this
7644 // xform in more cases, but it is unlikely to be profitable.
7645 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7646 isa<ConstantInt>(TrOp->getOperand(1))) {
7647 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007648 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007649 // (shift2 (shift1 & 0x00FF), c2)
7650 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007651
7652 // For logical shifts, the truncation has the effect of making the high
7653 // part of the register be zeros. Emulate this by inserting an AND to
7654 // clear the top bits as needed. This 'and' will usually be zapped by
7655 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007656 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7657 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007658 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7659
7660 // The mask we constructed says what the trunc would do if occurring
7661 // between the shifts. We want to know the effect *after* the second
7662 // shift. We know that it is a logical shift by a constant, so adjust the
7663 // mask as appropriate.
7664 if (I.getOpcode() == Instruction::Shl)
7665 MaskV <<= Op1->getZExtValue();
7666 else {
7667 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7668 MaskV = MaskV.lshr(Op1->getZExtValue());
7669 }
7670
Chris Lattner74381062009-08-30 07:44:24 +00007671 // shift1 & 0x00FF
7672 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7673 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007674
7675 // Return the value truncated to the interesting size.
7676 return new TruncInst(And, I.getType());
7677 }
7678 }
7679
Chris Lattner4d5542c2006-01-06 07:12:35 +00007680 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007681 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7682 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7683 Value *V1, *V2;
7684 ConstantInt *CC;
7685 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007686 default: break;
7687 case Instruction::Add:
7688 case Instruction::And:
7689 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007690 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007691 // These operators commute.
7692 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007693 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007694 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007695 m_Specific(Op1)))) {
7696 Value *YS = // (Y << C)
7697 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7698 // (X + (Y << C))
7699 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7700 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007701 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007702 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007703 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007704 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007705
Chris Lattner150f12a2005-09-18 06:30:59 +00007706 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007707 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007708 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007709 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007710 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007711 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007712 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007713 Value *YS = // (Y << C)
7714 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7715 Op0BO->getName());
7716 // X & (CC << C)
7717 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7718 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007719 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007720 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007721 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007722
Reid Spencera07cb7d2007-02-02 14:41:37 +00007723 // FALL THROUGH.
7724 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007725 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007726 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007727 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007728 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007729 Value *YS = // (Y << C)
7730 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7731 // (X + (Y << C))
7732 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7733 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007734 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007735 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007736 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007737 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007738
Chris Lattner13d4ab42006-05-31 21:14:00 +00007739 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007740 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7741 match(Op0BO->getOperand(0),
7742 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007743 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007744 cast<BinaryOperator>(Op0BO->getOperand(0))
7745 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007746 Value *YS = // (Y << C)
7747 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7748 // X & (CC << C)
7749 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7750 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007751
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007752 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007753 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007754
Chris Lattner11021cb2005-09-18 05:12:10 +00007755 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007756 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007757 }
7758
7759
7760 // If the operand is an bitwise operator with a constant RHS, and the
7761 // shift is the only use, we can pull it out of the shift.
7762 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7763 bool isValid = true; // Valid only for And, Or, Xor
7764 bool highBitSet = false; // Transform if high bit of constant set?
7765
7766 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007767 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007768 case Instruction::Add:
7769 isValid = isLeftShift;
7770 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007771 case Instruction::Or:
7772 case Instruction::Xor:
7773 highBitSet = false;
7774 break;
7775 case Instruction::And:
7776 highBitSet = true;
7777 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007778 }
7779
7780 // If this is a signed shift right, and the high bit is modified
7781 // by the logical operation, do not perform the transformation.
7782 // The highBitSet boolean indicates the value of the high bit of
7783 // the constant which would cause it to be modified for this
7784 // operation.
7785 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007786 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007787 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007788
7789 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007790 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007791
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007792 Value *NewShift =
7793 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007794 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007795
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007796 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007797 NewRHS);
7798 }
7799 }
7800 }
7801 }
7802
Chris Lattnerad0124c2006-01-06 07:52:12 +00007803 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007804 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7805 if (ShiftOp && !ShiftOp->isShift())
7806 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007807
Reid Spencerb83eb642006-10-20 07:07:24 +00007808 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007809 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007810 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7811 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007812 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7813 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7814 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007815
Zhou Sheng4351c642007-04-02 08:20:41 +00007816 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007817
7818 const IntegerType *Ty = cast<IntegerType>(I.getType());
7819
7820 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007821 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007822 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7823 // saturates.
7824 if (AmtSum >= TypeBits) {
7825 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007826 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007827 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7828 }
7829
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007830 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007831 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007832 }
7833
7834 if (ShiftOp->getOpcode() == Instruction::LShr &&
7835 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007836 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007837 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007838
Chris Lattnerb87056f2007-02-05 00:57:54 +00007839 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007840 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007841 }
7842
7843 if (ShiftOp->getOpcode() == Instruction::AShr &&
7844 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007845 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007846 if (AmtSum >= TypeBits)
7847 AmtSum = TypeBits-1;
7848
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007849 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007850
Zhou Shenge9e03f62007-03-28 15:02:20 +00007851 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007852 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007853 }
7854
Chris Lattnerb87056f2007-02-05 00:57:54 +00007855 // Okay, if we get here, one shift must be left, and the other shift must be
7856 // right. See if the amounts are equal.
7857 if (ShiftAmt1 == ShiftAmt2) {
7858 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7859 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007860 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007861 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007862 }
7863 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7864 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007865 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007866 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007867 }
7868 // We can simplify ((X << C) >>s C) into a trunc + sext.
7869 // NOTE: we could do this for any C, but that would make 'unusual' integer
7870 // types. For now, just stick to ones well-supported by the code
7871 // generators.
7872 const Type *SExtType = 0;
7873 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007874 case 1 :
7875 case 8 :
7876 case 16 :
7877 case 32 :
7878 case 64 :
7879 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007880 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007881 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007882 default: break;
7883 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007884 if (SExtType)
7885 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007886 // Otherwise, we can't handle it yet.
7887 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007888 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007889
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007890 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007891 if (I.getOpcode() == Instruction::Shl) {
7892 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7893 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007894 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007895
Reid Spencer55702aa2007-03-25 21:11:44 +00007896 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007897 return BinaryOperator::CreateAnd(Shift,
7898 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007899 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007900
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007901 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007902 if (I.getOpcode() == Instruction::LShr) {
7903 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007904 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007905
Reid Spencerd5e30f02007-03-26 17:18:58 +00007906 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007907 return BinaryOperator::CreateAnd(Shift,
7908 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007909 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007910
7911 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7912 } else {
7913 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007914 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007915
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007916 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007917 if (I.getOpcode() == Instruction::Shl) {
7918 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7919 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007920 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7921 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007922
Reid Spencer55702aa2007-03-25 21:11:44 +00007923 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007924 return BinaryOperator::CreateAnd(Shift,
7925 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007926 }
7927
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007928 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007929 if (I.getOpcode() == Instruction::LShr) {
7930 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007931 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007932
Reid Spencer68d27cf2007-03-26 23:45:51 +00007933 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007934 return BinaryOperator::CreateAnd(Shift,
7935 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007936 }
7937
7938 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007939 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007940 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007941 return 0;
7942}
7943
Chris Lattnera1be5662002-05-02 17:06:02 +00007944
Chris Lattnercfd65102005-10-29 04:36:15 +00007945/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7946/// expression. If so, decompose it, returning some value X, such that Val is
7947/// X*Scale+Offset.
7948///
7949static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007950 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007951 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7952 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007953 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007954 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007955 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007956 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007957 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7958 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7959 if (I->getOpcode() == Instruction::Shl) {
7960 // This is a value scaled by '1 << the shift amt'.
7961 Scale = 1U << RHS->getZExtValue();
7962 Offset = 0;
7963 return I->getOperand(0);
7964 } else if (I->getOpcode() == Instruction::Mul) {
7965 // This value is scaled by 'RHS'.
7966 Scale = RHS->getZExtValue();
7967 Offset = 0;
7968 return I->getOperand(0);
7969 } else if (I->getOpcode() == Instruction::Add) {
7970 // We have X+C. Check to see if we really have (X*C2)+C1,
7971 // where C1 is divisible by C2.
7972 unsigned SubScale;
7973 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007974 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7975 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007976 Offset += RHS->getZExtValue();
7977 Scale = SubScale;
7978 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007979 }
7980 }
7981 }
7982
7983 // Otherwise, we can't look past this.
7984 Scale = 1;
7985 Offset = 0;
7986 return Val;
7987}
7988
7989
Chris Lattnerb3f83972005-10-24 06:03:58 +00007990/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7991/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007992Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00007993 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007994 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007995
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007996 BuilderTy AllocaBuilder(*Builder);
7997 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7998
Chris Lattnerb53c2382005-10-24 06:22:12 +00007999 // Remove any uses of AI that are dead.
8000 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00008001
Chris Lattnerb53c2382005-10-24 06:22:12 +00008002 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
8003 Instruction *User = cast<Instruction>(*UI++);
8004 if (isInstructionTriviallyDead(User)) {
8005 while (UI != E && *UI == User)
8006 ++UI; // If this instruction uses AI more than once, don't break UI.
8007
Chris Lattnerb53c2382005-10-24 06:22:12 +00008008 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00008009 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008010 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00008011 }
8012 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008013
8014 // This requires TargetData to get the alloca alignment and size information.
8015 if (!TD) return 0;
8016
Chris Lattnerb3f83972005-10-24 06:03:58 +00008017 // Get the type really allocated and the type casted to.
8018 const Type *AllocElTy = AI.getAllocatedType();
8019 const Type *CastElTy = PTy->getElementType();
8020 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00008021
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008022 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
8023 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00008024 if (CastElTyAlign < AllocElTyAlign) return 0;
8025
Chris Lattner39387a52005-10-24 06:35:18 +00008026 // If the allocation has multiple uses, only promote it if we are strictly
8027 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00008028 // same, we open the door to infinite loops of various kinds. (A reference
8029 // from a dbg.declare doesn't count as a use for this purpose.)
8030 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
8031 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00008032
Duncan Sands777d2302009-05-09 07:06:46 +00008033 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
8034 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008035 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00008036
Chris Lattner455fcc82005-10-29 03:19:53 +00008037 // See if we can satisfy the modulus by pulling a scale out of the array
8038 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00008039 unsigned ArraySizeScale;
8040 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00008041 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00008042 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
8043 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00008044
Chris Lattner455fcc82005-10-29 03:19:53 +00008045 // If we can now satisfy the modulus, by using a non-1 scale, we really can
8046 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00008047 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
8048 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00008049
Chris Lattner455fcc82005-10-29 03:19:53 +00008050 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
8051 Value *Amt = 0;
8052 if (Scale == 1) {
8053 Amt = NumElements;
8054 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00008055 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008056 // Insert before the alloca, not before the cast.
8057 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008058 }
8059
Jeff Cohen86796be2007-04-04 16:58:57 +00008060 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008061 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008062 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00008063 }
8064
Victor Hernandez7b929da2009-10-23 21:09:37 +00008065 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008066 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00008067 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00008068
Dale Johannesena0a66372009-03-05 00:39:02 +00008069 // If the allocation has one real use plus a dbg.declare, just remove the
8070 // declare.
8071 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8072 EraseInstFromFunction(*DI);
8073 }
8074 // If the allocation has multiple real uses, insert a cast and change all
8075 // things that used it to use the new cast. This will also hack on CI, but it
8076 // will die soon.
8077 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008078 // New is the allocation instruction, pointer typed. AI is the original
8079 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008080 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00008081 AI.replaceAllUsesWith(NewCast);
8082 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00008083 return ReplaceInstUsesWith(CI, New);
8084}
8085
Chris Lattner70074e02006-05-13 02:06:03 +00008086/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00008087/// and return it as type Ty without inserting any new casts and without
8088/// changing the computed value. This is used by code that tries to decide
8089/// whether promoting or shrinking integer operations to wider or smaller types
8090/// will allow us to eliminate a truncate or extend.
8091///
8092/// This is a truncation operation if Ty is smaller than V->getType(), or an
8093/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00008094///
8095/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
8096/// should return true if trunc(V) can be computed by computing V in the smaller
8097/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
8098/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8099/// efficiently truncated.
8100///
8101/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8102/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8103/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00008104bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008105 unsigned CastOpc,
8106 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00008107 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00008108 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00008109 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00008110
8111 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008112 if (!I) return false;
8113
Dan Gohman6de29f82009-06-15 22:12:54 +00008114 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00008115
Chris Lattner951626b2007-08-02 06:11:14 +00008116 // If this is an extension or truncate, we can often eliminate it.
8117 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8118 // If this is a cast from the destination type, we can trivially eliminate
8119 // it, and this will remove a cast overall.
8120 if (I->getOperand(0)->getType() == Ty) {
8121 // If the first operand is itself a cast, and is eliminable, do not count
8122 // this as an eliminable cast. We would prefer to eliminate those two
8123 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00008124 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00008125 ++NumCastsRemoved;
8126 return true;
8127 }
8128 }
8129
8130 // We can't extend or shrink something that has multiple uses: doing so would
8131 // require duplicating the instruction in general, which isn't profitable.
8132 if (!I->hasOneUse()) return false;
8133
Evan Chengf35fd542009-01-15 17:01:23 +00008134 unsigned Opc = I->getOpcode();
8135 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008136 case Instruction::Add:
8137 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008138 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008139 case Instruction::And:
8140 case Instruction::Or:
8141 case Instruction::Xor:
8142 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00008143 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008144 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00008145 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008146 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008147
Eli Friedman070a9812009-07-13 22:46:01 +00008148 case Instruction::UDiv:
8149 case Instruction::URem: {
8150 // UDiv and URem can be truncated if all the truncated bits are zero.
8151 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8152 uint32_t BitWidth = Ty->getScalarSizeInBits();
8153 if (BitWidth < OrigBitWidth) {
8154 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8155 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8156 MaskedValueIsZero(I->getOperand(1), Mask)) {
8157 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8158 NumCastsRemoved) &&
8159 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8160 NumCastsRemoved);
8161 }
8162 }
8163 break;
8164 }
Chris Lattner46b96052006-11-29 07:18:39 +00008165 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008166 // If we are truncating the result of this SHL, and if it's a shift of a
8167 // constant amount, we can always perform a SHL in a smaller type.
8168 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008169 uint32_t BitWidth = Ty->getScalarSizeInBits();
8170 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008171 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008172 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008173 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008174 }
8175 break;
8176 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008177 // If this is a truncate of a logical shr, we can truncate it to a smaller
8178 // lshr iff we know that the bits we would otherwise be shifting in are
8179 // already zeros.
8180 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008181 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8182 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008183 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008184 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008185 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8186 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008187 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008188 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008189 }
8190 }
Chris Lattner46b96052006-11-29 07:18:39 +00008191 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008192 case Instruction::ZExt:
8193 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008194 case Instruction::Trunc:
8195 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008196 // can safely replace it. Note that replacing it does not reduce the number
8197 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008198 if (Opc == CastOpc)
8199 return true;
8200
8201 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008202 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008203 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008204 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008205 case Instruction::Select: {
8206 SelectInst *SI = cast<SelectInst>(I);
8207 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008208 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008209 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008210 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008211 }
Chris Lattner8114b712008-06-18 04:00:49 +00008212 case Instruction::PHI: {
8213 // We can change a phi if we can change all operands.
8214 PHINode *PN = cast<PHINode>(I);
8215 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8216 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008217 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008218 return false;
8219 return true;
8220 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008221 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008222 // TODO: Can handle more cases here.
8223 break;
8224 }
8225
8226 return false;
8227}
8228
8229/// EvaluateInDifferentType - Given an expression that
8230/// CanEvaluateInDifferentType returns true for, actually insert the code to
8231/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008232Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008233 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008234 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00008235 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008236
8237 // Otherwise, it must be an instruction.
8238 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008239 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008240 unsigned Opc = I->getOpcode();
8241 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008242 case Instruction::Add:
8243 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008244 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008245 case Instruction::And:
8246 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008247 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008248 case Instruction::AShr:
8249 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008250 case Instruction::Shl:
8251 case Instruction::UDiv:
8252 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008253 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008254 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008255 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008256 break;
8257 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008258 case Instruction::Trunc:
8259 case Instruction::ZExt:
8260 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008261 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008262 // just return the source. There's no need to insert it because it is not
8263 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008264 if (I->getOperand(0)->getType() == Ty)
8265 return I->getOperand(0);
8266
Chris Lattner8114b712008-06-18 04:00:49 +00008267 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00008268 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008269 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008270 case Instruction::Select: {
8271 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8272 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8273 Res = SelectInst::Create(I->getOperand(0), True, False);
8274 break;
8275 }
Chris Lattner8114b712008-06-18 04:00:49 +00008276 case Instruction::PHI: {
8277 PHINode *OPN = cast<PHINode>(I);
8278 PHINode *NPN = PHINode::Create(Ty);
8279 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8280 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8281 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8282 }
8283 Res = NPN;
8284 break;
8285 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008286 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008287 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008288 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008289 break;
8290 }
8291
Chris Lattner8114b712008-06-18 04:00:49 +00008292 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008293 return InsertNewInstBefore(Res, *I);
8294}
8295
Reid Spencer3da59db2006-11-27 01:05:10 +00008296/// @brief Implement the transforms common to all CastInst visitors.
8297Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008298 Value *Src = CI.getOperand(0);
8299
Dan Gohman23d9d272007-05-11 21:10:54 +00008300 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008301 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008302 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008303 if (Instruction::CastOps opc =
8304 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8305 // The first cast (CSrc) is eliminable so we need to fix up or replace
8306 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008307 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008308 }
8309 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008310
Reid Spencer3da59db2006-11-27 01:05:10 +00008311 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008312 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8313 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8314 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008315
8316 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00008317 if (isa<PHINode>(Src)) {
8318 // We don't do this if this would create a PHI node with an illegal type if
8319 // it is currently legal.
8320 if (!isa<IntegerType>(Src->getType()) ||
8321 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerc22d4d12009-11-10 07:23:37 +00008322 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner9956c052009-11-08 19:23:30 +00008323 if (Instruction *NV = FoldOpIntoPhi(CI))
8324 return NV;
Chris Lattner9956c052009-11-08 19:23:30 +00008325 }
Chris Lattner9fb92132006-04-12 18:09:35 +00008326
Reid Spencer3da59db2006-11-27 01:05:10 +00008327 return 0;
8328}
8329
Chris Lattner46cd5a12009-01-09 05:44:56 +00008330/// FindElementAtOffset - Given a type and a constant offset, determine whether
8331/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008332/// the specified offset. If so, fill them into NewIndices and return the
8333/// resultant element type, otherwise return null.
8334static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8335 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008336 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008337 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008338 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008339 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008340
8341 // Start with the index over the outer type. Note that the type size
8342 // might be zero (even if the offset isn't zero) if the indexed type
8343 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008344 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008345 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008346 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008347 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008348 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008349
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008350 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008351 if (Offset < 0) {
8352 --FirstIdx;
8353 Offset += TySize;
8354 assert(Offset >= 0);
8355 }
8356 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8357 }
8358
Owen Andersoneed707b2009-07-24 23:12:02 +00008359 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008360
8361 // Index into the types. If we fail, set OrigBase to null.
8362 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008363 // Indexing into tail padding between struct/array elements.
8364 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008365 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008366
Chris Lattner46cd5a12009-01-09 05:44:56 +00008367 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8368 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008369 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8370 "Offset must stay within the indexed type");
8371
Chris Lattner46cd5a12009-01-09 05:44:56 +00008372 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008373 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008374
8375 Offset -= SL->getElementOffset(Elt);
8376 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008377 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008378 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008379 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008380 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008381 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008382 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008383 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008384 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008385 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008386 }
8387 }
8388
Chris Lattner3914f722009-01-24 01:00:13 +00008389 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008390}
8391
Chris Lattnerd3e28342007-04-27 17:44:50 +00008392/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8393Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8394 Value *Src = CI.getOperand(0);
8395
Chris Lattnerd3e28342007-04-27 17:44:50 +00008396 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008397 // If casting the result of a getelementptr instruction with no offset, turn
8398 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008399 if (GEP->hasAllZeroIndices()) {
8400 // Changing the cast operand is usually not a good idea but it is safe
8401 // here because the pointer operand is being replaced with another
8402 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008403 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008404 CI.setOperand(0, GEP->getOperand(0));
8405 return &CI;
8406 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008407
8408 // If the GEP has a single use, and the base pointer is a bitcast, and the
8409 // GEP computes a constant offset, see if we can convert these three
8410 // instructions into fewer. This typically happens with unions and other
8411 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008412 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008413 if (GEP->hasAllConstantIndices()) {
8414 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008415 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008416 int64_t Offset = OffsetV->getSExtValue();
8417
8418 // Get the base pointer input of the bitcast, and the type it points to.
8419 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8420 const Type *GEPIdxTy =
8421 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008422 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008423 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008424 // If we were able to index down into an element, create the GEP
8425 // and bitcast the result. This eliminates one bitcast, potentially
8426 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008427 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8428 Builder->CreateInBoundsGEP(OrigBase,
8429 NewIndices.begin(), NewIndices.end()) :
8430 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008431 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008432
Chris Lattner46cd5a12009-01-09 05:44:56 +00008433 if (isa<BitCastInst>(CI))
8434 return new BitCastInst(NGEP, CI.getType());
8435 assert(isa<PtrToIntInst>(CI));
8436 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008437 }
8438 }
8439 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008440 }
8441
8442 return commonCastTransforms(CI);
8443}
8444
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008445/// commonIntCastTransforms - This function implements the common transforms
8446/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008447Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8448 if (Instruction *Result = commonCastTransforms(CI))
8449 return Result;
8450
8451 Value *Src = CI.getOperand(0);
8452 const Type *SrcTy = Src->getType();
8453 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008454 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8455 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008456
Reid Spencer3da59db2006-11-27 01:05:10 +00008457 // See if we can simplify any instructions used by the LHS whose sole
8458 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008459 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008460 return &CI;
8461
8462 // If the source isn't an instruction or has more than one use then we
8463 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008464 Instruction *SrcI = dyn_cast<Instruction>(Src);
8465 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008466 return 0;
8467
Chris Lattnerc739cd62007-03-03 05:27:34 +00008468 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008469 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008470 // Only do this if the dest type is a simple type, don't convert the
8471 // expression tree to something weird like i93 unless the source is also
8472 // strange.
Chris Lattner6b583912009-11-10 17:00:47 +00008473 if ((isa<VectorType>(DestTy) ||
8474 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8475 CanEvaluateInDifferentType(SrcI, DestTy,
8476 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008477 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008478 // eliminates the cast, so it is always a win. If this is a zero-extension,
8479 // we need to do an AND to maintain the clear top-part of the computation,
8480 // so we require that the input have eliminated at least one cast. If this
8481 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008482 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008483 bool DoXForm = false;
8484 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008485 switch (CI.getOpcode()) {
8486 default:
8487 // All the others use floating point so we shouldn't actually
8488 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008489 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008490 case Instruction::Trunc:
8491 DoXForm = true;
8492 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008493 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008494 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00008495
Chris Lattner39c27ed2009-01-31 19:05:27 +00008496 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008497 // If it's unnecessary to issue an AND to clear the high bits, it's
8498 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008499 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008500 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8501 if (MaskedValueIsZero(TryRes, Mask))
8502 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008503
8504 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008505 if (TryI->use_empty())
8506 EraseInstFromFunction(*TryI);
8507 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008508 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008509 }
Evan Chengf35fd542009-01-15 17:01:23 +00008510 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008511 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008512 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008513 // If we do not have to emit the truncate + sext pair, then it's always
8514 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008515 //
8516 // It's not safe to eliminate the trunc + sext pair if one of the
8517 // eliminated cast is a truncate. e.g.
8518 // t2 = trunc i32 t1 to i16
8519 // t3 = sext i16 t2 to i32
8520 // !=
8521 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008522 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008523 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8524 if (NumSignBits > (DestBitSize - SrcBitSize))
8525 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008526
8527 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008528 if (TryI->use_empty())
8529 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008530 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008531 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008532 }
Evan Chengf35fd542009-01-15 17:01:23 +00008533 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008534
8535 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008536 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8537 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008538 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8539 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008540 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008541 // Just replace this cast with the result.
8542 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008543
Reid Spencer3da59db2006-11-27 01:05:10 +00008544 assert(Res->getType() == DestTy);
8545 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008546 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008547 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008548 // Just replace this cast with the result.
8549 return ReplaceInstUsesWith(CI, Res);
8550 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008551 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008552
8553 // If the high bits are already zero, just replace this cast with the
8554 // result.
8555 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8556 if (MaskedValueIsZero(Res, Mask))
8557 return ReplaceInstUsesWith(CI, Res);
8558
8559 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008560 Constant *C = ConstantInt::get(*Context,
8561 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008562 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008563 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008564 case Instruction::SExt: {
8565 // If the high bits are already filled with sign bit, just replace this
8566 // cast with the result.
8567 unsigned NumSignBits = ComputeNumSignBits(Res);
8568 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008569 return ReplaceInstUsesWith(CI, Res);
8570
Reid Spencer3da59db2006-11-27 01:05:10 +00008571 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008572 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008573 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008574 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008575 }
8576 }
8577
8578 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8579 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8580
8581 switch (SrcI->getOpcode()) {
8582 case Instruction::Add:
8583 case Instruction::Mul:
8584 case Instruction::And:
8585 case Instruction::Or:
8586 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008587 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008588 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8589 // Don't insert two casts unless at least one can be eliminated.
8590 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008591 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008592 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8593 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008594 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008595 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008596 }
8597 }
8598
8599 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8600 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8601 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008602 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008603 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008604 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008605 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008606 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008607 }
8608 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008609
Eli Friedman65445c52009-07-13 21:45:57 +00008610 case Instruction::Shl: {
8611 // Canonicalize trunc inside shl, if we can.
8612 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8613 if (CI && DestBitSize < SrcBitSize &&
8614 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008615 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8616 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008617 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008618 }
8619 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008620 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008621 }
8622 return 0;
8623}
8624
Chris Lattner8a9f5712007-04-11 06:57:46 +00008625Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008626 if (Instruction *Result = commonIntCastTransforms(CI))
8627 return Result;
8628
8629 Value *Src = CI.getOperand(0);
8630 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008631 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8632 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008633
8634 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008635 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008636 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008637 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008638 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008639 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008640 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008641
Chris Lattner4f9797d2009-03-24 18:15:30 +00008642 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8643 ConstantInt *ShAmtV = 0;
8644 Value *ShiftOp = 0;
8645 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008646 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008647 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8648
8649 // Get a mask for the bits shifting in.
8650 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8651 if (MaskedValueIsZero(ShiftOp, Mask)) {
8652 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008653 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008654
8655 // Okay, we can shrink this. Truncate the input, then return a new
8656 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008657 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008658 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008659 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008660 }
8661 }
Chris Lattner9956c052009-11-08 19:23:30 +00008662
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008663 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008664}
8665
Evan Chengb98a10e2008-03-24 00:21:34 +00008666/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8667/// in order to eliminate the icmp.
8668Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8669 bool DoXform) {
8670 // If we are just checking for a icmp eq of a single bit and zext'ing it
8671 // to an integer, then shift the bit to the appropriate place and then
8672 // cast to integer to avoid the comparison.
8673 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8674 const APInt &Op1CV = Op1C->getValue();
8675
8676 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8677 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8678 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8679 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8680 if (!DoXform) return ICI;
8681
8682 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008683 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008684 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008685 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008686 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008687 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008688
8689 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008690 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008691 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008692 }
8693
8694 return ReplaceInstUsesWith(CI, In);
8695 }
8696
8697
8698
8699 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8700 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8701 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8702 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8703 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8704 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8705 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8706 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8707 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8708 // This only works for EQ and NE
8709 ICI->isEquality()) {
8710 // If Op1C some other power of two, convert:
8711 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8712 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8713 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8714 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8715
8716 APInt KnownZeroMask(~KnownZero);
8717 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8718 if (!DoXform) return ICI;
8719
8720 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8721 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8722 // (X&4) == 2 --> false
8723 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008724 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008725 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008726 return ReplaceInstUsesWith(CI, Res);
8727 }
8728
8729 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8730 Value *In = ICI->getOperand(0);
8731 if (ShiftAmt) {
8732 // Perform a logical shr by shiftamt.
8733 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008734 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8735 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008736 }
8737
8738 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008739 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008740 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008741 }
8742
8743 if (CI.getType() == In->getType())
8744 return ReplaceInstUsesWith(CI, In);
8745 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008746 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008747 }
8748 }
8749 }
8750
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008751 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8752 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8753 // may lead to additional simplifications.
8754 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8755 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8756 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008757 Value *LHS = ICI->getOperand(0);
8758 Value *RHS = ICI->getOperand(1);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008759
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008760 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8761 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8762 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8763 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8764 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008765
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008766 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
8767 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
8768 APInt UnknownBit = ~KnownBits;
8769 if (UnknownBit.countPopulation() == 1) {
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008770 if (!DoXform) return ICI;
8771
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008772 Value *Result = Builder->CreateXor(LHS, RHS);
8773
8774 // Mask off any bits that are set and won't be shifted away.
8775 if (KnownOneLHS.uge(UnknownBit))
8776 Result = Builder->CreateAnd(Result,
8777 ConstantInt::get(ITy, UnknownBit));
8778
8779 // Shift the bit we're testing down to the lsb.
8780 Result = Builder->CreateLShr(
8781 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
8782
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008783 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008784 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
8785 Result->takeName(ICI);
8786 return ReplaceInstUsesWith(CI, Result);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008787 }
8788 }
8789 }
8790 }
8791
Evan Chengb98a10e2008-03-24 00:21:34 +00008792 return 0;
8793}
8794
Chris Lattner8a9f5712007-04-11 06:57:46 +00008795Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008796 // If one of the common conversion will work ..
8797 if (Instruction *Result = commonIntCastTransforms(CI))
8798 return Result;
8799
8800 Value *Src = CI.getOperand(0);
8801
Chris Lattnera84f47c2009-02-17 20:47:23 +00008802 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8803 // types and if the sizes are just right we can convert this into a logical
8804 // 'and' which will be much cheaper than the pair of casts.
8805 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8806 // Get the sizes of the types involved. We know that the intermediate type
8807 // will be smaller than A or C, but don't know the relation between A and C.
8808 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008809 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8810 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8811 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008812 // If we're actually extending zero bits, then if
8813 // SrcSize < DstSize: zext(a & mask)
8814 // SrcSize == DstSize: a & mask
8815 // SrcSize > DstSize: trunc(a) & mask
8816 if (SrcSize < DstSize) {
8817 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008818 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008819 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008820 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008821 }
8822
8823 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008824 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008825 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008826 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008827 }
8828 if (SrcSize > DstSize) {
8829 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008830 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008831 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008832 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008833 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008834 }
8835 }
8836
Evan Chengb98a10e2008-03-24 00:21:34 +00008837 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8838 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008839
Evan Chengb98a10e2008-03-24 00:21:34 +00008840 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8841 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8842 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8843 // of the (zext icmp) will be transformed.
8844 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8845 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8846 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8847 (transformZExtICmp(LHS, CI, false) ||
8848 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008849 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8850 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008851 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008852 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008853 }
8854
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008855 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008856 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8857 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8858 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8859 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008860 if (TI0->getType() == CI.getType())
8861 return
8862 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008863 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008864 }
8865
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008866 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8867 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8868 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8869 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8870 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8871 And->getOperand(1) == C)
8872 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8873 Value *TI0 = TI->getOperand(0);
8874 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008875 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008876 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008877 return BinaryOperator::CreateXor(NewAnd, ZC);
8878 }
8879 }
8880
Reid Spencer3da59db2006-11-27 01:05:10 +00008881 return 0;
8882}
8883
Chris Lattner8a9f5712007-04-11 06:57:46 +00008884Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008885 if (Instruction *I = commonIntCastTransforms(CI))
8886 return I;
8887
Chris Lattner8a9f5712007-04-11 06:57:46 +00008888 Value *Src = CI.getOperand(0);
8889
Dan Gohman1975d032008-10-30 20:40:10 +00008890 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008891 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008892 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008893 Constant::getAllOnesValue(CI.getType()),
8894 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008895
8896 // See if the value being truncated is already sign extended. If so, just
8897 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008898 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008899 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008900 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8901 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8902 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008903 unsigned NumSignBits = ComputeNumSignBits(Op);
8904
8905 if (OpBits == DestBits) {
8906 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8907 // bits, it is already ready.
8908 if (NumSignBits > DestBits-MidBits)
8909 return ReplaceInstUsesWith(CI, Op);
8910 } else if (OpBits < DestBits) {
8911 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8912 // bits, just sext from i32.
8913 if (NumSignBits > OpBits-MidBits)
8914 return new SExtInst(Op, CI.getType(), "tmp");
8915 } else {
8916 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8917 // bits, just truncate to i32.
8918 if (NumSignBits > OpBits-MidBits)
8919 return new TruncInst(Op, CI.getType(), "tmp");
8920 }
8921 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008922
8923 // If the input is a shl/ashr pair of a same constant, then this is a sign
8924 // extension from a smaller value. If we could trust arbitrary bitwidth
8925 // integers, we could turn this into a truncate to the smaller bit and then
8926 // use a sext for the whole extension. Since we don't, look deeper and check
8927 // for a truncate. If the source and dest are the same type, eliminate the
8928 // trunc and extend and just do shifts. For example, turn:
8929 // %a = trunc i32 %i to i8
8930 // %b = shl i8 %a, 6
8931 // %c = ashr i8 %b, 6
8932 // %d = sext i8 %c to i32
8933 // into:
8934 // %a = shl i32 %i, 30
8935 // %d = ashr i32 %a, 30
8936 Value *A = 0;
8937 ConstantInt *BA = 0, *CA = 0;
8938 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008939 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008940 BA == CA && isa<TruncInst>(A)) {
8941 Value *I = cast<TruncInst>(A)->getOperand(0);
8942 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008943 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8944 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008945 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008946 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008947 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008948 return BinaryOperator::CreateAShr(I, ShAmtV);
8949 }
8950 }
8951
Chris Lattnerba417832007-04-11 06:12:58 +00008952 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008953}
8954
Chris Lattnerb7530652008-01-27 05:29:54 +00008955/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8956/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008957static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008958 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008959 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008960 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008961 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8962 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008963 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008964 return 0;
8965}
8966
8967/// LookThroughFPExtensions - If this is an fp extension instruction, look
8968/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008969static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008970 if (Instruction *I = dyn_cast<Instruction>(V))
8971 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008972 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008973
8974 // If this value is a constant, return the constant in the smallest FP type
8975 // that can accurately represent it. This allows us to turn
8976 // (float)((double)X+2.0) into x+2.0f.
8977 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008978 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008979 return V; // No constant folding of this.
8980 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008981 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008982 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008983 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008984 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008985 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008986 return V;
8987 // Don't try to shrink to various long double types.
8988 }
8989
8990 return V;
8991}
8992
8993Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8994 if (Instruction *I = commonCastTransforms(CI))
8995 return I;
8996
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008997 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008998 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008999 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00009000 // many builtins (sqrt, etc).
9001 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
9002 if (OpI && OpI->hasOneUse()) {
9003 switch (OpI->getOpcode()) {
9004 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009005 case Instruction::FAdd:
9006 case Instruction::FSub:
9007 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00009008 case Instruction::FDiv:
9009 case Instruction::FRem:
9010 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00009011 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
9012 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00009013 if (LHSTrunc->getType() != SrcTy &&
9014 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00009015 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00009016 // If the source types were both smaller than the destination type of
9017 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00009018 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
9019 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009020 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
9021 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009022 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00009023 }
9024 }
9025 break;
9026 }
9027 }
9028 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009029}
9030
9031Instruction *InstCombiner::visitFPExt(CastInst &CI) {
9032 return commonCastTransforms(CI);
9033}
9034
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009035Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009036 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9037 if (OpI == 0)
9038 return commonCastTransforms(FI);
9039
9040 // fptoui(uitofp(X)) --> X
9041 // fptoui(sitofp(X)) --> X
9042 // This is safe if the intermediate type has enough bits in its mantissa to
9043 // accurately represent all values of X. For example, do not do this with
9044 // i64->float->i64. This is also safe for sitofp case, because any negative
9045 // 'X' value would cause an undefined result for the fptoui.
9046 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9047 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009048 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00009049 OpI->getType()->getFPMantissaWidth())
9050 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009051
9052 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009053}
9054
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009055Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009056 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9057 if (OpI == 0)
9058 return commonCastTransforms(FI);
9059
9060 // fptosi(sitofp(X)) --> X
9061 // fptosi(uitofp(X)) --> X
9062 // This is safe if the intermediate type has enough bits in its mantissa to
9063 // accurately represent all values of X. For example, do not do this with
9064 // i64->float->i64. This is also safe for sitofp case, because any negative
9065 // 'X' value would cause an undefined result for the fptoui.
9066 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9067 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009068 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00009069 OpI->getType()->getFPMantissaWidth())
9070 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009071
9072 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009073}
9074
9075Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9076 return commonCastTransforms(CI);
9077}
9078
9079Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9080 return commonCastTransforms(CI);
9081}
9082
Chris Lattnera0e69692009-03-24 18:35:40 +00009083Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9084 // If the destination integer type is smaller than the intptr_t type for
9085 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
9086 // trunc to be exposed to other transforms. Don't do this for extending
9087 // ptrtoint's, because we don't know if the target sign or zero extends its
9088 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009089 if (TD &&
9090 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009091 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9092 TD->getIntPtrType(CI.getContext()),
9093 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009094 return new TruncInst(P, CI.getType());
9095 }
9096
Chris Lattnerd3e28342007-04-27 17:44:50 +00009097 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009098}
9099
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009100Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00009101 // If the source integer type is larger than the intptr_t type for
9102 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
9103 // allows the trunc to be exposed to other transforms. Don't do this for
9104 // extending inttoptr's, because we don't know if the target sign or zero
9105 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009106 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00009107 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009108 Value *P = Builder->CreateTrunc(CI.getOperand(0),
9109 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009110 return new IntToPtrInst(P, CI.getType());
9111 }
9112
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009113 if (Instruction *I = commonCastTransforms(CI))
9114 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009115
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009116 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009117}
9118
Chris Lattnerd3e28342007-04-27 17:44:50 +00009119Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009120 // If the operands are integer typed then apply the integer transforms,
9121 // otherwise just apply the common ones.
9122 Value *Src = CI.getOperand(0);
9123 const Type *SrcTy = Src->getType();
9124 const Type *DestTy = CI.getType();
9125
Eli Friedman7e25d452009-07-13 20:53:00 +00009126 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009127 if (Instruction *I = commonPointerCastTransforms(CI))
9128 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00009129 } else {
9130 if (Instruction *Result = commonCastTransforms(CI))
9131 return Result;
9132 }
9133
9134
9135 // Get rid of casts from one type to the same type. These are useless and can
9136 // be replaced by the operand.
9137 if (DestTy == Src->getType())
9138 return ReplaceInstUsesWith(CI, Src);
9139
Reid Spencer3da59db2006-11-27 01:05:10 +00009140 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009141 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9142 const Type *DstElTy = DstPTy->getElementType();
9143 const Type *SrcElTy = SrcPTy->getElementType();
9144
Nate Begeman83ad90a2008-03-31 00:22:16 +00009145 // If the address spaces don't match, don't eliminate the bitcast, which is
9146 // required for changing types.
9147 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9148 return 0;
9149
Victor Hernandez83d63912009-09-18 22:35:49 +00009150 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00009151 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00009152 // There is no need to modify malloc calls because it is their bitcast that
9153 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00009154 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00009155 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9156 return V;
9157
Chris Lattnerd717c182007-05-05 22:32:24 +00009158 // If the source and destination are pointers, and this cast is equivalent
9159 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009160 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00009161 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00009162 unsigned NumZeros = 0;
9163 while (SrcElTy != DstElTy &&
9164 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9165 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9166 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9167 ++NumZeros;
9168 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009169
Chris Lattnerd3e28342007-04-27 17:44:50 +00009170 // If we found a path from the src to dest, create the getelementptr now.
9171 if (SrcElTy == DstElTy) {
9172 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00009173 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9174 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009175 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009176 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009177
Eli Friedman2451a642009-07-18 23:06:53 +00009178 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9179 if (DestVTy->getNumElements() == 1) {
9180 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009181 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009182 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00009183 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009184 }
9185 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9186 }
9187 }
9188
9189 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9190 if (SrcVTy->getNumElements() == 1) {
9191 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009192 Value *Elem =
9193 Builder->CreateExtractElement(Src,
9194 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009195 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9196 }
9197 }
9198 }
9199
Reid Spencer3da59db2006-11-27 01:05:10 +00009200 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9201 if (SVI->hasOneUse()) {
9202 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9203 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009204 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009205 cast<VectorType>(DestTy)->getNumElements() ==
9206 SVI->getType()->getNumElements() &&
9207 SVI->getType()->getNumElements() ==
9208 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009209 CastInst *Tmp;
9210 // If either of the operands is a cast from CI.getType(), then
9211 // evaluating the shuffle in the casted destination's type will allow
9212 // us to eliminate at least one cast.
9213 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9214 Tmp->getOperand(0)->getType() == DestTy) ||
9215 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9216 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009217 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9218 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00009219 // Return a new shuffle vector. Use the same element ID's, as we
9220 // know the vector types match #elts.
9221 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009222 }
9223 }
9224 }
9225 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009226 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009227}
9228
Chris Lattnere576b912004-04-09 23:46:01 +00009229/// GetSelectFoldableOperands - We want to turn code that looks like this:
9230/// %C = or %A, %B
9231/// %D = select %cond, %C, %A
9232/// into:
9233/// %C = select %cond, %B, 0
9234/// %D = or %A, %C
9235///
9236/// Assuming that the specified instruction is an operand to the select, return
9237/// a bitmask indicating which operands of this instruction are foldable if they
9238/// equal the other incoming value of the select.
9239///
9240static unsigned GetSelectFoldableOperands(Instruction *I) {
9241 switch (I->getOpcode()) {
9242 case Instruction::Add:
9243 case Instruction::Mul:
9244 case Instruction::And:
9245 case Instruction::Or:
9246 case Instruction::Xor:
9247 return 3; // Can fold through either operand.
9248 case Instruction::Sub: // Can only fold on the amount subtracted.
9249 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009250 case Instruction::LShr:
9251 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009252 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009253 default:
9254 return 0; // Cannot fold
9255 }
9256}
9257
9258/// GetSelectFoldableConstant - For the same transformation as the previous
9259/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009260static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009261 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009262 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009263 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009264 case Instruction::Add:
9265 case Instruction::Sub:
9266 case Instruction::Or:
9267 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009268 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009269 case Instruction::LShr:
9270 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009271 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009272 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009273 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009274 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009275 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009276 }
9277}
9278
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009279/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9280/// have the same opcode and only one use each. Try to simplify this.
9281Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9282 Instruction *FI) {
9283 if (TI->getNumOperands() == 1) {
9284 // If this is a non-volatile load or a cast from the same type,
9285 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009286 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009287 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9288 return 0;
9289 } else {
9290 return 0; // unknown unary op.
9291 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009292
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009293 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009294 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009295 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009296 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009297 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009298 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009299 }
9300
Reid Spencer832254e2007-02-02 02:16:23 +00009301 // Only handle binary operators here.
9302 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009303 return 0;
9304
9305 // Figure out if the operations have any operands in common.
9306 Value *MatchOp, *OtherOpT, *OtherOpF;
9307 bool MatchIsOpZero;
9308 if (TI->getOperand(0) == FI->getOperand(0)) {
9309 MatchOp = TI->getOperand(0);
9310 OtherOpT = TI->getOperand(1);
9311 OtherOpF = FI->getOperand(1);
9312 MatchIsOpZero = true;
9313 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9314 MatchOp = TI->getOperand(1);
9315 OtherOpT = TI->getOperand(0);
9316 OtherOpF = FI->getOperand(0);
9317 MatchIsOpZero = false;
9318 } else if (!TI->isCommutative()) {
9319 return 0;
9320 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9321 MatchOp = TI->getOperand(0);
9322 OtherOpT = TI->getOperand(1);
9323 OtherOpF = FI->getOperand(0);
9324 MatchIsOpZero = true;
9325 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9326 MatchOp = TI->getOperand(1);
9327 OtherOpT = TI->getOperand(0);
9328 OtherOpF = FI->getOperand(1);
9329 MatchIsOpZero = true;
9330 } else {
9331 return 0;
9332 }
9333
9334 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009335 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9336 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009337 InsertNewInstBefore(NewSI, SI);
9338
9339 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9340 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009341 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009342 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009343 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009344 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009345 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009346 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009347}
9348
Evan Chengde621922009-03-31 20:42:45 +00009349static bool isSelect01(Constant *C1, Constant *C2) {
9350 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9351 if (!C1I)
9352 return false;
9353 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9354 if (!C2I)
9355 return false;
9356 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9357}
9358
9359/// FoldSelectIntoOp - Try fold the select into one of the operands to
9360/// facilitate further optimization.
9361Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9362 Value *FalseVal) {
9363 // See the comment above GetSelectFoldableOperands for a description of the
9364 // transformation we are doing here.
9365 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9366 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9367 !isa<Constant>(FalseVal)) {
9368 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9369 unsigned OpToFold = 0;
9370 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9371 OpToFold = 1;
9372 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9373 OpToFold = 2;
9374 }
9375
9376 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009377 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009378 Value *OOp = TVI->getOperand(2-OpToFold);
9379 // Avoid creating select between 2 constants unless it's selecting
9380 // between 0 and 1.
9381 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9382 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9383 InsertNewInstBefore(NewSel, SI);
9384 NewSel->takeName(TVI);
9385 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9386 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009387 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009388 }
9389 }
9390 }
9391 }
9392 }
9393
9394 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9395 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9396 !isa<Constant>(TrueVal)) {
9397 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9398 unsigned OpToFold = 0;
9399 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9400 OpToFold = 1;
9401 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9402 OpToFold = 2;
9403 }
9404
9405 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009406 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009407 Value *OOp = FVI->getOperand(2-OpToFold);
9408 // Avoid creating select between 2 constants unless it's selecting
9409 // between 0 and 1.
9410 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9411 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9412 InsertNewInstBefore(NewSel, SI);
9413 NewSel->takeName(FVI);
9414 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9415 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009416 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009417 }
9418 }
9419 }
9420 }
9421 }
9422
9423 return 0;
9424}
9425
Dan Gohman81b28ce2008-09-16 18:46:06 +00009426/// visitSelectInstWithICmp - Visit a SelectInst that has an
9427/// ICmpInst as its first operand.
9428///
9429Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9430 ICmpInst *ICI) {
9431 bool Changed = false;
9432 ICmpInst::Predicate Pred = ICI->getPredicate();
9433 Value *CmpLHS = ICI->getOperand(0);
9434 Value *CmpRHS = ICI->getOperand(1);
9435 Value *TrueVal = SI.getTrueValue();
9436 Value *FalseVal = SI.getFalseValue();
9437
9438 // Check cases where the comparison is with a constant that
9439 // can be adjusted to fit the min/max idiom. We may edit ICI in
9440 // place here, so make sure the select is the only user.
9441 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009442 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009443 switch (Pred) {
9444 default: break;
9445 case ICmpInst::ICMP_ULT:
9446 case ICmpInst::ICMP_SLT: {
9447 // X < MIN ? T : F --> F
9448 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9449 return ReplaceInstUsesWith(SI, FalseVal);
9450 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009451 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009452 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9453 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9454 Pred = ICmpInst::getSwappedPredicate(Pred);
9455 CmpRHS = AdjustedRHS;
9456 std::swap(FalseVal, TrueVal);
9457 ICI->setPredicate(Pred);
9458 ICI->setOperand(1, CmpRHS);
9459 SI.setOperand(1, TrueVal);
9460 SI.setOperand(2, FalseVal);
9461 Changed = true;
9462 }
9463 break;
9464 }
9465 case ICmpInst::ICMP_UGT:
9466 case ICmpInst::ICMP_SGT: {
9467 // X > MAX ? T : F --> F
9468 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9469 return ReplaceInstUsesWith(SI, FalseVal);
9470 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009471 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009472 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9473 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9474 Pred = ICmpInst::getSwappedPredicate(Pred);
9475 CmpRHS = AdjustedRHS;
9476 std::swap(FalseVal, TrueVal);
9477 ICI->setPredicate(Pred);
9478 ICI->setOperand(1, CmpRHS);
9479 SI.setOperand(1, TrueVal);
9480 SI.setOperand(2, FalseVal);
9481 Changed = true;
9482 }
9483 break;
9484 }
9485 }
9486
Dan Gohman1975d032008-10-30 20:40:10 +00009487 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9488 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009489 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009490 if (match(TrueVal, m_ConstantInt<-1>()) &&
9491 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009492 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009493 else if (match(TrueVal, m_ConstantInt<0>()) &&
9494 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009495 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9496
Dan Gohman1975d032008-10-30 20:40:10 +00009497 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9498 // If we are just checking for a icmp eq of a single bit and zext'ing it
9499 // to an integer, then shift the bit to the appropriate place and then
9500 // cast to integer to avoid the comparison.
9501 const APInt &Op1CV = CI->getValue();
9502
9503 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9504 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9505 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009506 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009507 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009508 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009509 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009510 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009511 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009512 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009513 if (In->getType() != SI.getType())
9514 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009515 true/*SExt*/, "tmp", ICI);
9516
9517 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009518 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009519 In->getName()+".not"), *ICI);
9520
9521 return ReplaceInstUsesWith(SI, In);
9522 }
9523 }
9524 }
9525
Dan Gohman81b28ce2008-09-16 18:46:06 +00009526 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9527 // Transform (X == Y) ? X : Y -> Y
9528 if (Pred == ICmpInst::ICMP_EQ)
9529 return ReplaceInstUsesWith(SI, FalseVal);
9530 // Transform (X != Y) ? X : Y -> X
9531 if (Pred == ICmpInst::ICMP_NE)
9532 return ReplaceInstUsesWith(SI, TrueVal);
9533 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9534
9535 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9536 // Transform (X == Y) ? Y : X -> X
9537 if (Pred == ICmpInst::ICMP_EQ)
9538 return ReplaceInstUsesWith(SI, FalseVal);
9539 // Transform (X != Y) ? Y : X -> Y
9540 if (Pred == ICmpInst::ICMP_NE)
9541 return ReplaceInstUsesWith(SI, TrueVal);
9542 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9543 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009544 return Changed ? &SI : 0;
9545}
9546
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009547
Chris Lattner7f239582009-10-22 00:17:26 +00009548/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9549/// PHI node (but the two may be in different blocks). See if the true/false
9550/// values (V) are live in all of the predecessor blocks of the PHI. For
9551/// example, cases like this cannot be mapped:
9552///
9553/// X = phi [ C1, BB1], [C2, BB2]
9554/// Y = add
9555/// Z = select X, Y, 0
9556///
9557/// because Y is not live in BB1/BB2.
9558///
9559static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9560 const SelectInst &SI) {
9561 // If the value is a non-instruction value like a constant or argument, it
9562 // can always be mapped.
9563 const Instruction *I = dyn_cast<Instruction>(V);
9564 if (I == 0) return true;
9565
9566 // If V is a PHI node defined in the same block as the condition PHI, we can
9567 // map the arguments.
9568 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9569
9570 if (const PHINode *VP = dyn_cast<PHINode>(I))
9571 if (VP->getParent() == CondPHI->getParent())
9572 return true;
9573
9574 // Otherwise, if the PHI and select are defined in the same block and if V is
9575 // defined in a different block, then we can transform it.
9576 if (SI.getParent() == CondPHI->getParent() &&
9577 I->getParent() != CondPHI->getParent())
9578 return true;
9579
9580 // Otherwise we have a 'hard' case and we can't tell without doing more
9581 // detailed dominator based analysis, punt.
9582 return false;
9583}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009584
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009585/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
9586/// SPF2(SPF1(A, B), C)
9587Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
9588 SelectPatternFlavor SPF1,
9589 Value *A, Value *B,
9590 Instruction &Outer,
9591 SelectPatternFlavor SPF2, Value *C) {
9592 if (C == A || C == B) {
9593 // MAX(MAX(A, B), B) -> MAX(A, B)
9594 // MIN(MIN(a, b), a) -> MIN(a, b)
9595 if (SPF1 == SPF2)
9596 return ReplaceInstUsesWith(Outer, Inner);
9597
9598 // MAX(MIN(a, b), a) -> a
9599 // MIN(MAX(a, b), a) -> a
Daniel Dunbareddfaaf2009-12-21 23:27:57 +00009600 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
9601 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
9602 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
9603 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009604 return ReplaceInstUsesWith(Outer, C);
9605 }
9606
9607 // TODO: MIN(MIN(A, 23), 97)
9608 return 0;
9609}
9610
9611
9612
9613
Chris Lattner3d69f462004-03-12 05:52:32 +00009614Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009615 Value *CondVal = SI.getCondition();
9616 Value *TrueVal = SI.getTrueValue();
9617 Value *FalseVal = SI.getFalseValue();
9618
9619 // select true, X, Y -> X
9620 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009621 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009622 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009623
9624 // select C, X, X -> X
9625 if (TrueVal == FalseVal)
9626 return ReplaceInstUsesWith(SI, TrueVal);
9627
Chris Lattnere87597f2004-10-16 18:11:37 +00009628 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9629 return ReplaceInstUsesWith(SI, FalseVal);
9630 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9631 return ReplaceInstUsesWith(SI, TrueVal);
9632 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9633 if (isa<Constant>(TrueVal))
9634 return ReplaceInstUsesWith(SI, TrueVal);
9635 else
9636 return ReplaceInstUsesWith(SI, FalseVal);
9637 }
9638
Owen Anderson1d0be152009-08-13 21:58:54 +00009639 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009640 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009641 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009642 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009643 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009644 } else {
9645 // Change: A = select B, false, C --> A = and !B, C
9646 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009647 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009648 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009649 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009650 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009651 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009652 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009653 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009654 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009655 } else {
9656 // Change: A = select B, C, true --> A = or !B, C
9657 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009658 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009659 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009660 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009661 }
9662 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009663
9664 // select a, b, a -> a&b
9665 // select a, a, b -> a|b
9666 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009667 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009668 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009669 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009670 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009671
Chris Lattner2eefe512004-04-09 19:05:30 +00009672 // Selecting between two integer constants?
9673 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9674 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009675 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009676 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009677 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009678 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009679 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009680 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009681 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009682 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009683 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009684 }
Chris Lattner457dd822004-06-09 07:59:58 +00009685
Reid Spencere4d87aa2006-12-23 06:05:41 +00009686 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009687 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009688 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009689 // non-constant value, eliminate this whole mess. This corresponds to
9690 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009691 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009692 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009693 cast<Constant>(IC->getOperand(1))->isNullValue())
9694 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9695 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009696 isa<ConstantInt>(ICA->getOperand(1)) &&
9697 (ICA->getOperand(1) == TrueValC ||
9698 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009699 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9700 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009701 // know whether we have a icmp_ne or icmp_eq and whether the
9702 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009703 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009704 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009705 Value *V = ICA;
9706 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009707 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009708 Instruction::Xor, V, ICA->getOperand(1)), SI);
9709 return ReplaceInstUsesWith(SI, V);
9710 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009711 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009712 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009713
9714 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009715 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9716 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009717 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009718 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9719 // This is not safe in general for floating point:
9720 // consider X== -0, Y== +0.
9721 // It becomes safe if either operand is a nonzero constant.
9722 ConstantFP *CFPt, *CFPf;
9723 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9724 !CFPt->getValueAPF().isZero()) ||
9725 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9726 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009727 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009728 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009729 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009730 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009731 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009732 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009733
Reid Spencere4d87aa2006-12-23 06:05:41 +00009734 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009735 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009736 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9737 // This is not safe in general for floating point:
9738 // consider X== -0, Y== +0.
9739 // It becomes safe if either operand is a nonzero constant.
9740 ConstantFP *CFPt, *CFPf;
9741 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9742 !CFPt->getValueAPF().isZero()) ||
9743 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9744 !CFPf->getValueAPF().isZero()))
9745 return ReplaceInstUsesWith(SI, FalseVal);
9746 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009747 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009748 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9749 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009750 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009751 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009752 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009753 }
9754
9755 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009756 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9757 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9758 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009759
Chris Lattner87875da2005-01-13 22:52:24 +00009760 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9761 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9762 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009763 Instruction *AddOp = 0, *SubOp = 0;
9764
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009765 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9766 if (TI->getOpcode() == FI->getOpcode())
9767 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9768 return IV;
9769
9770 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9771 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009772 if ((TI->getOpcode() == Instruction::Sub &&
9773 FI->getOpcode() == Instruction::Add) ||
9774 (TI->getOpcode() == Instruction::FSub &&
9775 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009776 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009777 } else if ((FI->getOpcode() == Instruction::Sub &&
9778 TI->getOpcode() == Instruction::Add) ||
9779 (FI->getOpcode() == Instruction::FSub &&
9780 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009781 AddOp = TI; SubOp = FI;
9782 }
9783
9784 if (AddOp) {
9785 Value *OtherAddOp = 0;
9786 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9787 OtherAddOp = AddOp->getOperand(1);
9788 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9789 OtherAddOp = AddOp->getOperand(0);
9790 }
9791
9792 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009793 // So at this point we know we have (Y -> OtherAddOp):
9794 // select C, (add X, Y), (sub X, Z)
9795 Value *NegVal; // Compute -Z
9796 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009797 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009798 } else {
9799 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009800 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009801 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009802 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009803
9804 Value *NewTrueOp = OtherAddOp;
9805 Value *NewFalseOp = NegVal;
9806 if (AddOp != TI)
9807 std::swap(NewTrueOp, NewFalseOp);
9808 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009809 SelectInst::Create(CondVal, NewTrueOp,
9810 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009811
9812 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009813 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009814 }
9815 }
9816 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009817
Chris Lattnere576b912004-04-09 23:46:01 +00009818 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009819 if (SI.getType()->isInteger()) {
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009820 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Chengde621922009-03-31 20:42:45 +00009821 return FoldI;
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009822
9823 // MAX(MAX(a, b), a) -> MAX(a, b)
9824 // MIN(MIN(a, b), a) -> MIN(a, b)
9825 // MAX(MIN(a, b), a) -> a
9826 // MIN(MAX(a, b), a) -> a
9827 Value *LHS, *RHS, *LHS2, *RHS2;
9828 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
9829 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
9830 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
9831 SI, SPF, RHS))
9832 return R;
9833 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
9834 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
9835 SI, SPF, LHS))
9836 return R;
9837 }
9838
9839 // TODO.
9840 // ABS(-X) -> ABS(X)
9841 // ABS(ABS(X)) -> ABS(X)
Chris Lattnere576b912004-04-09 23:46:01 +00009842 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009843
Chris Lattner7f239582009-10-22 00:17:26 +00009844 // See if we can fold the select into a phi node if the condition is a select.
9845 if (isa<PHINode>(SI.getCondition()))
9846 // The true/false values have to be live in the PHI predecessor's blocks.
9847 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9848 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9849 if (Instruction *NV = FoldOpIntoPhi(SI))
9850 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00009851
Chris Lattnera1df33c2005-04-24 07:30:14 +00009852 if (BinaryOperator::isNot(CondVal)) {
9853 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9854 SI.setOperand(1, FalseVal);
9855 SI.setOperand(2, TrueVal);
9856 return &SI;
9857 }
9858
Chris Lattner3d69f462004-03-12 05:52:32 +00009859 return 0;
9860}
9861
Dan Gohmaneee962e2008-04-10 18:43:06 +00009862/// EnforceKnownAlignment - If the specified pointer points to an object that
9863/// we control, modify the object's alignment to PrefAlign. This isn't
9864/// often possible though. If alignment is important, a more reliable approach
9865/// is to simply align all global variables and allocation instructions to
9866/// their preferred alignment from the beginning.
9867///
9868static unsigned EnforceKnownAlignment(Value *V,
9869 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009870
Dan Gohmaneee962e2008-04-10 18:43:06 +00009871 User *U = dyn_cast<User>(V);
9872 if (!U) return Align;
9873
Dan Gohmanca178902009-07-17 20:47:02 +00009874 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009875 default: break;
9876 case Instruction::BitCast:
9877 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9878 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009879 // If all indexes are zero, it is just the alignment of the base pointer.
9880 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009881 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009882 if (!isa<Constant>(*i) ||
9883 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009884 AllZeroOperands = false;
9885 break;
9886 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009887
9888 if (AllZeroOperands) {
9889 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009890 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009891 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009892 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009893 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009894 }
9895
9896 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9897 // If there is a large requested alignment and we can, bump up the alignment
9898 // of the global.
9899 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009900 if (GV->getAlignment() >= PrefAlign)
9901 Align = GV->getAlignment();
9902 else {
9903 GV->setAlignment(PrefAlign);
9904 Align = PrefAlign;
9905 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009906 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009907 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9908 // If there is a requested alignment and if this is an alloca, round up.
9909 if (AI->getAlignment() >= PrefAlign)
9910 Align = AI->getAlignment();
9911 else {
9912 AI->setAlignment(PrefAlign);
9913 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009914 }
9915 }
9916
9917 return Align;
9918}
9919
9920/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9921/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9922/// and it is more than the alignment of the ultimate object, see if we can
9923/// increase the alignment of the ultimate object, making this check succeed.
9924unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9925 unsigned PrefAlign) {
9926 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9927 sizeof(PrefAlign) * CHAR_BIT;
9928 APInt Mask = APInt::getAllOnesValue(BitWidth);
9929 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9930 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9931 unsigned TrailZ = KnownZero.countTrailingOnes();
9932 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9933
9934 if (PrefAlign > Align)
9935 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9936
9937 // We don't need to make any adjustment.
9938 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009939}
9940
Chris Lattnerf497b022008-01-13 23:50:23 +00009941Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009942 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009943 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009944 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009945 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009946
9947 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009948 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009949 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009950 return MI;
9951 }
9952
9953 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9954 // load/store.
9955 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9956 if (MemOpLength == 0) return 0;
9957
Chris Lattner37ac6082008-01-14 00:28:35 +00009958 // Source and destination pointer types are always "i8*" for intrinsic. See
9959 // if the size is something we can handle with a single primitive load/store.
9960 // A single load+store correctly handles overlapping memory in the memmove
9961 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009962 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009963 if (Size == 0) return MI; // Delete this mem transfer.
9964
9965 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009966 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009967
Chris Lattner37ac6082008-01-14 00:28:35 +00009968 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009969 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009970 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009971
9972 // Memcpy forces the use of i8* for the source and destination. That means
9973 // that if you're using memcpy to move one double around, you'll get a cast
9974 // from double* to i8*. We'd much rather use a double load+store rather than
9975 // an i64 load+store, here because this improves the odds that the source or
9976 // dest address will be promotable. See if we can find a better type than the
9977 // integer datatype.
9978 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9979 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009980 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009981 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9982 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009983 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009984 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9985 if (STy->getNumElements() == 1)
9986 SrcETy = STy->getElementType(0);
9987 else
9988 break;
9989 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9990 if (ATy->getNumElements() == 1)
9991 SrcETy = ATy->getElementType();
9992 else
9993 break;
9994 } else
9995 break;
9996 }
9997
Dan Gohman8f8e2692008-05-23 01:52:21 +00009998 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009999 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +000010000 }
10001 }
10002
10003
Chris Lattnerf497b022008-01-13 23:50:23 +000010004 // If the memcpy/memmove provides better alignment info than we can
10005 // infer, use it.
10006 SrcAlign = std::max(SrcAlign, CopyAlign);
10007 DstAlign = std::max(DstAlign, CopyAlign);
10008
Chris Lattner08142f22009-08-30 19:47:22 +000010009 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
10010 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +000010011 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
10012 InsertNewInstBefore(L, *MI);
10013 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
10014
10015 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010016 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +000010017 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +000010018}
Chris Lattner3d69f462004-03-12 05:52:32 +000010019
Chris Lattner69ea9d22008-04-30 06:39:11 +000010020Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
10021 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010022 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010023 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +000010024 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010025 return MI;
10026 }
10027
10028 // Extract the length and alignment and fill if they are constant.
10029 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
10030 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +000010031 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +000010032 return 0;
10033 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010034 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +000010035
10036 // If the length is zero, this is a no-op
10037 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
10038
10039 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
10040 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010041 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +000010042
10043 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +000010044 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010045
10046 // Alignment 0 is identity for alignment 1 for memset, but not store.
10047 if (Alignment == 0) Alignment = 1;
10048
10049 // Extract the fill value and store.
10050 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +000010051 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +000010052 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +000010053
10054 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010055 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010056 return MI;
10057 }
10058
10059 return 0;
10060}
10061
10062
Chris Lattner8b0ea312006-01-13 20:11:04 +000010063/// visitCallInst - CallInst simplification. This mostly only handles folding
10064/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
10065/// the heavy lifting.
10066///
Chris Lattner9fe38862003-06-19 17:00:31 +000010067Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +000010068 if (isFreeCall(&CI))
10069 return visitFree(CI);
10070
Chris Lattneraab6ec42009-05-13 17:39:14 +000010071 // If the caller function is nounwind, mark the call as nounwind, even if the
10072 // callee isn't.
10073 if (CI.getParent()->getParent()->doesNotThrow() &&
10074 !CI.doesNotThrow()) {
10075 CI.setDoesNotThrow();
10076 return &CI;
10077 }
10078
Chris Lattner8b0ea312006-01-13 20:11:04 +000010079 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
10080 if (!II) return visitCallSite(&CI);
10081
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010082 // Intrinsics cannot occur in an invoke, so handle them here instead of in
10083 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +000010084 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010085 bool Changed = false;
10086
10087 // memmove/cpy/set of zero bytes is a noop.
10088 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
10089 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
10090
Chris Lattner35b9e482004-10-12 04:52:52 +000010091 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +000010092 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010093 // Replace the instruction with just byte operations. We would
10094 // transform other cases to loads/stores, but we don't know if
10095 // alignment is sufficient.
10096 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010097 }
10098
Chris Lattner35b9e482004-10-12 04:52:52 +000010099 // If we have a memmove and the source operation is a constant global,
10100 // then the source and dest pointers can't alias, so we can change this
10101 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +000010102 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010103 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
10104 if (GVSrc->isConstant()) {
10105 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +000010106 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10107 const Type *Tys[1];
10108 Tys[0] = CI.getOperand(3)->getType();
10109 CI.setOperand(0,
10110 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +000010111 Changed = true;
10112 }
Eli Friedman0c826d92009-12-17 21:07:31 +000010113 }
Chris Lattnera935db82008-05-28 05:30:41 +000010114
Eli Friedman0c826d92009-12-17 21:07:31 +000010115 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +000010116 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +000010117 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +000010118 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +000010119 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010120
Chris Lattner95a959d2006-03-06 20:18:44 +000010121 // If we can determine a pointer alignment that is bigger than currently
10122 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +000010123 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +000010124 if (Instruction *I = SimplifyMemTransfer(MI))
10125 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +000010126 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10127 if (Instruction *I = SimplifyMemSet(MSI))
10128 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +000010129 }
10130
Chris Lattner8b0ea312006-01-13 20:11:04 +000010131 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010132 }
10133
10134 switch (II->getIntrinsicID()) {
10135 default: break;
10136 case Intrinsic::bswap:
10137 // bswap(bswap(x)) -> x
10138 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10139 if (Operand->getIntrinsicID() == Intrinsic::bswap)
10140 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +000010141
10142 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
10143 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
10144 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
10145 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
10146 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
10147 TI->getType()->getPrimitiveSizeInBits();
10148 Value *CV = ConstantInt::get(Operand->getType(), C);
10149 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
10150 return new TruncInst(V, TI->getType());
10151 }
10152 }
10153
Chris Lattner0521e3c2008-06-18 04:33:20 +000010154 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +000010155 case Intrinsic::powi:
10156 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
10157 // powi(x, 0) -> 1.0
10158 if (Power->isZero())
10159 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
10160 // powi(x, 1) -> x
10161 if (Power->isOne())
10162 return ReplaceInstUsesWith(CI, II->getOperand(1));
10163 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +000010164 if (Power->isAllOnesValue())
10165 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
10166 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +000010167 }
10168 break;
10169
Chris Lattner2bbac752009-11-26 21:42:47 +000010170 case Intrinsic::uadd_with_overflow: {
10171 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10172 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10173 uint32_t BitWidth = IT->getBitWidth();
10174 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +000010175 APInt LHSKnownZero(BitWidth, 0);
10176 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010177 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10178 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10179 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10180
10181 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +000010182 APInt RHSKnownZero(BitWidth, 0);
10183 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010184 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10185 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10186 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10187 if (LHSKnownNegative && RHSKnownNegative) {
10188 // The sign bit is set in both cases: this MUST overflow.
10189 // Create a simple add instruction, and insert it into the struct.
10190 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10191 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010192 Constant *V[] = {
10193 UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10194 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010195 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10196 return InsertValueInst::Create(Struct, Add, 0);
10197 }
10198
10199 if (LHSKnownPositive && RHSKnownPositive) {
10200 // The sign bit is clear in both cases: this CANNOT overflow.
10201 // Create a simple add instruction, and insert it into the struct.
10202 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10203 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010204 Constant *V[] = {
10205 UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10206 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010207 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10208 return InsertValueInst::Create(Struct, Add, 0);
10209 }
10210 }
10211 }
10212 // FALL THROUGH uadd into sadd
10213 case Intrinsic::sadd_with_overflow:
10214 // Canonicalize constants into the RHS.
10215 if (isa<Constant>(II->getOperand(1)) &&
10216 !isa<Constant>(II->getOperand(2))) {
10217 Value *LHS = II->getOperand(1);
10218 II->setOperand(1, II->getOperand(2));
10219 II->setOperand(2, LHS);
10220 return II;
10221 }
10222
10223 // X + undef -> undef
10224 if (isa<UndefValue>(II->getOperand(2)))
10225 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10226
10227 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10228 // X + 0 -> {X, false}
10229 if (RHS->isZero()) {
10230 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010231 UndefValue::get(II->getOperand(0)->getType()),
10232 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010233 };
10234 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10235 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10236 }
10237 }
10238 break;
10239 case Intrinsic::usub_with_overflow:
10240 case Intrinsic::ssub_with_overflow:
10241 // undef - X -> undef
10242 // X - undef -> undef
10243 if (isa<UndefValue>(II->getOperand(1)) ||
10244 isa<UndefValue>(II->getOperand(2)))
10245 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10246
10247 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10248 // X - 0 -> {X, false}
10249 if (RHS->isZero()) {
10250 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010251 UndefValue::get(II->getOperand(1)->getType()),
10252 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010253 };
10254 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10255 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10256 }
10257 }
10258 break;
10259 case Intrinsic::umul_with_overflow:
10260 case Intrinsic::smul_with_overflow:
10261 // Canonicalize constants into the RHS.
10262 if (isa<Constant>(II->getOperand(1)) &&
10263 !isa<Constant>(II->getOperand(2))) {
10264 Value *LHS = II->getOperand(1);
10265 II->setOperand(1, II->getOperand(2));
10266 II->setOperand(2, LHS);
10267 return II;
10268 }
10269
10270 // X * undef -> undef
10271 if (isa<UndefValue>(II->getOperand(2)))
10272 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10273
10274 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10275 // X*0 -> {0, false}
10276 if (RHSI->isZero())
10277 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10278
10279 // X * 1 -> {X, false}
10280 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +000010281 Constant *V[] = {
10282 UndefValue::get(II->getOperand(1)->getType()),
10283 ConstantInt::getFalse(*Context)
10284 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010285 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +000010286 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010287 }
10288 }
10289 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010290 case Intrinsic::ppc_altivec_lvx:
10291 case Intrinsic::ppc_altivec_lvxl:
10292 case Intrinsic::x86_sse_loadu_ps:
10293 case Intrinsic::x86_sse2_loadu_pd:
10294 case Intrinsic::x86_sse2_loadu_dq:
10295 // Turn PPC lvx -> load if the pointer is known aligned.
10296 // Turn X86 loadups -> load if the pointer is known aligned.
10297 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +000010298 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10299 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +000010300 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +000010301 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010302 break;
10303 case Intrinsic::ppc_altivec_stvx:
10304 case Intrinsic::ppc_altivec_stvxl:
10305 // Turn stvx -> store if the pointer is known aligned.
10306 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10307 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010308 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010309 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010310 return new StoreInst(II->getOperand(1), Ptr);
10311 }
10312 break;
10313 case Intrinsic::x86_sse_storeu_ps:
10314 case Intrinsic::x86_sse2_storeu_pd:
10315 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +000010316 // Turn X86 storeu -> store if the pointer is known aligned.
10317 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10318 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010319 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010320 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010321 return new StoreInst(II->getOperand(2), Ptr);
10322 }
10323 break;
10324
10325 case Intrinsic::x86_sse_cvttss2si: {
10326 // These intrinsics only demands the 0th element of its input vector. If
10327 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +000010328 unsigned VWidth =
10329 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10330 APInt DemandedElts(VWidth, 1);
10331 APInt UndefElts(VWidth, 0);
10332 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +000010333 UndefElts)) {
10334 II->setOperand(1, V);
10335 return II;
10336 }
10337 break;
10338 }
10339
10340 case Intrinsic::ppc_altivec_vperm:
10341 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10342 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10343 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +000010344
Chris Lattner0521e3c2008-06-18 04:33:20 +000010345 // Check that all of the elements are integer constants or undefs.
10346 bool AllEltsOk = true;
10347 for (unsigned i = 0; i != 16; ++i) {
10348 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10349 !isa<UndefValue>(Mask->getOperand(i))) {
10350 AllEltsOk = false;
10351 break;
10352 }
10353 }
10354
10355 if (AllEltsOk) {
10356 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +000010357 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10358 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010359 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010360
Chris Lattner0521e3c2008-06-18 04:33:20 +000010361 // Only extract each element once.
10362 Value *ExtractedElts[32];
10363 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10364
Chris Lattnere2ed0572006-04-06 19:19:17 +000010365 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010366 if (isa<UndefValue>(Mask->getOperand(i)))
10367 continue;
10368 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10369 Idx &= 31; // Match the hardware behavior.
10370
10371 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010372 ExtractedElts[Idx] =
10373 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10374 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10375 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010376 }
Chris Lattnere2ed0572006-04-06 19:19:17 +000010377
Chris Lattner0521e3c2008-06-18 04:33:20 +000010378 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010379 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10380 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10381 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010382 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010383 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010384 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010385 }
10386 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010387
Chris Lattner0521e3c2008-06-18 04:33:20 +000010388 case Intrinsic::stackrestore: {
10389 // If the save is right next to the restore, remove the restore. This can
10390 // happen when variable allocas are DCE'd.
10391 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10392 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10393 BasicBlock::iterator BI = SS;
10394 if (&*++BI == II)
10395 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010396 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010397 }
10398
10399 // Scan down this block to see if there is another stack restore in the
10400 // same block without an intervening call/alloca.
10401 BasicBlock::iterator BI = II;
10402 TerminatorInst *TI = II->getParent()->getTerminator();
10403 bool CannotRemove = false;
10404 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +000010405 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010406 CannotRemove = true;
10407 break;
10408 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010409 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10410 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10411 // If there is a stackrestore below this one, remove this one.
10412 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10413 return EraseInstFromFunction(CI);
10414 // Otherwise, ignore the intrinsic.
10415 } else {
10416 // If we found a non-intrinsic call, we can't remove the stack
10417 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010418 CannotRemove = true;
10419 break;
10420 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010421 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010422 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010423
10424 // If the stack restore is in a return/unwind block and if there are no
10425 // allocas or calls between the restore and the return, nuke the restore.
10426 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10427 return EraseInstFromFunction(CI);
10428 break;
10429 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010430 }
10431
Chris Lattner8b0ea312006-01-13 20:11:04 +000010432 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010433}
10434
10435// InvokeInst simplification
10436//
10437Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010438 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010439}
10440
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010441/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10442/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010443static bool isSafeToEliminateVarargsCast(const CallSite CS,
10444 const CastInst * const CI,
10445 const TargetData * const TD,
10446 const int ix) {
10447 if (!CI->isLosslessCast())
10448 return false;
10449
10450 // The size of ByVal arguments is derived from the type, so we
10451 // can't change to a type with a different size. If the size were
10452 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010453 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010454 return true;
10455
10456 const Type* SrcTy =
10457 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10458 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10459 if (!SrcTy->isSized() || !DstTy->isSized())
10460 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010461 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010462 return false;
10463 return true;
10464}
10465
Chris Lattnera44d8a22003-10-07 22:32:43 +000010466// visitCallSite - Improvements for call and invoke instructions.
10467//
10468Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010469 bool Changed = false;
10470
10471 // If the callee is a constexpr cast of a function, attempt to move the cast
10472 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010473 if (transformConstExprCastCall(CS)) return 0;
10474
Chris Lattner6c266db2003-10-07 22:54:13 +000010475 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010476
Chris Lattner08b22ec2005-05-13 07:09:09 +000010477 if (Function *CalleeF = dyn_cast<Function>(Callee))
10478 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10479 Instruction *OldCall = CS.getInstruction();
10480 // If the call and callee calling conventions don't match, this call must
10481 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010482 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010483 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010484 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010485 // If OldCall dues not return void then replaceAllUsesWith undef.
10486 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010487 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010488 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010489 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10490 return EraseInstFromFunction(*OldCall);
10491 return 0;
10492 }
10493
Chris Lattner17be6352004-10-18 02:59:09 +000010494 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10495 // This instruction is not reachable, just remove it. We insert a store to
10496 // undef so that we know that this code is not reachable, despite the fact
10497 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010498 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010499 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010500 CS.getInstruction());
10501
Devang Patel228ebd02009-10-13 22:56:32 +000010502 // If CS dues not return void then replaceAllUsesWith undef.
10503 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010504 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010505 CS.getInstruction()->
10506 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010507
10508 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10509 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010510 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010511 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010512 }
Chris Lattner17be6352004-10-18 02:59:09 +000010513 return EraseInstFromFunction(*CS.getInstruction());
10514 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010515
Duncan Sandscdb6d922007-09-17 10:26:40 +000010516 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10517 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10518 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10519 return transformCallThroughTrampoline(CS);
10520
Chris Lattner6c266db2003-10-07 22:54:13 +000010521 const PointerType *PTy = cast<PointerType>(Callee->getType());
10522 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10523 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010524 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010525 // See if we can optimize any arguments passed through the varargs area of
10526 // the call.
10527 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010528 E = CS.arg_end(); I != E; ++I, ++ix) {
10529 CastInst *CI = dyn_cast<CastInst>(*I);
10530 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10531 *I = CI->getOperand(0);
10532 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010533 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010534 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010535 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010536
Duncan Sandsf0c33542007-12-19 21:13:37 +000010537 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010538 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010539 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010540 Changed = true;
10541 }
10542
Chris Lattner6c266db2003-10-07 22:54:13 +000010543 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010544}
10545
Chris Lattner9fe38862003-06-19 17:00:31 +000010546// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10547// attempt to move the cast to the arguments of the call/invoke.
10548//
10549bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10550 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10551 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010552 if (CE->getOpcode() != Instruction::BitCast ||
10553 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010554 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010555 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010556 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010557 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010558
10559 // Okay, this is a cast from a function to a different type. Unless doing so
10560 // would cause a type conversion of one of our arguments, change this call to
10561 // be a direct call with arguments casted to the appropriate types.
10562 //
10563 const FunctionType *FT = Callee->getFunctionType();
10564 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010565 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010566
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010567 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010568 return false; // TODO: Handle multiple return values.
10569
Chris Lattnerf78616b2004-01-14 06:06:08 +000010570 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010571 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010572 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010573 // Conversion is ok if changing from one pointer type to another or from
10574 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010575 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010576 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010577 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010578 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010579 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010580
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010581 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010582 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010583 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010584 return false; // Cannot transform this return value.
10585
Chris Lattner58d74912008-03-12 17:45:29 +000010586 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010587 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010588 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010589 return false; // Attribute not compatible with transformed value.
10590 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010591
Chris Lattnerf78616b2004-01-14 06:06:08 +000010592 // If the callsite is an invoke instruction, and the return value is used by
10593 // a PHI node in a successor, we cannot change the return type of the call
10594 // because there is no place to put the cast instruction (without breaking
10595 // the critical edge). Bail out in this case.
10596 if (!Caller->use_empty())
10597 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10598 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10599 UI != E; ++UI)
10600 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10601 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010602 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010603 return false;
10604 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010605
10606 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10607 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010608
Chris Lattner9fe38862003-06-19 17:00:31 +000010609 CallSite::arg_iterator AI = CS.arg_begin();
10610 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10611 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010612 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010613
10614 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010615 return false; // Cannot transform this parameter value.
10616
Devang Patel19c87462008-09-26 22:53:05 +000010617 if (CallerPAL.getParamAttributes(i + 1)
10618 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010619 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010620
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010621 // Converting from one pointer type to another or between a pointer and an
10622 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010623 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010624 (TD && ((isa<PointerType>(ParamTy) ||
10625 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10626 (isa<PointerType>(ActTy) ||
10627 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010628 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010629 }
10630
10631 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010632 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010633 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010634
Chris Lattner58d74912008-03-12 17:45:29 +000010635 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10636 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010637 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010638 // won't be dropping them. Check that these extra arguments have attributes
10639 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010640 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10641 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010642 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010643 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010644 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010645 return false;
10646 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010647
Chris Lattner9fe38862003-06-19 17:00:31 +000010648 // Okay, we decided that this is a safe thing to do: go ahead and start
10649 // inserting cast instructions as necessary...
10650 std::vector<Value*> Args;
10651 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010652 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010653 attrVec.reserve(NumCommonArgs);
10654
10655 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010656 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010657
10658 // If the return value is not being used, the type may not be compatible
10659 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010660 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010661
10662 // Add the new return attributes.
10663 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010664 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010665
10666 AI = CS.arg_begin();
10667 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10668 const Type *ParamTy = FT->getParamType(i);
10669 if ((*AI)->getType() == ParamTy) {
10670 Args.push_back(*AI);
10671 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010672 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010673 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010674 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010675 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010676
10677 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010678 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010679 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010680 }
10681
10682 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010683 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010684 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010685 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010686
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010687 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010688 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010689 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010690 errs() << "WARNING: While resolving call to function '"
10691 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010692 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010693 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010694 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10695 const Type *PTy = getPromotedType((*AI)->getType());
10696 if (PTy != (*AI)->getType()) {
10697 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010698 Instruction::CastOps opcode =
10699 CastInst::getCastOpcode(*AI, false, PTy, false);
10700 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010701 } else {
10702 Args.push_back(*AI);
10703 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010704
Duncan Sandse1e520f2008-01-13 08:02:44 +000010705 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010706 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010707 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010708 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010709 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010710 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010711
Devang Patel19c87462008-09-26 22:53:05 +000010712 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10713 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10714
Devang Patel9674d152009-10-14 17:29:00 +000010715 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010716 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010717
Eric Christophera66297a2009-07-25 02:45:27 +000010718 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10719 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010720
Chris Lattner9fe38862003-06-19 17:00:31 +000010721 Instruction *NC;
10722 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010723 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010724 Args.begin(), Args.end(),
10725 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010726 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010727 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010728 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010729 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10730 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010731 CallInst *CI = cast<CallInst>(Caller);
10732 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010733 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010734 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010735 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010736 }
10737
Chris Lattner6934a042007-02-11 01:23:03 +000010738 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010739 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010740 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010741 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010742 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010743 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010744 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010745
10746 // If this is an invoke instruction, we should insert it after the first
10747 // non-phi, instruction in the normal successor block.
10748 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010749 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010750 InsertNewInstBefore(NC, *I);
10751 } else {
10752 // Otherwise, it's a call, just insert cast right after the call instr
10753 InsertNewInstBefore(NC, *Caller);
10754 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010755 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010756 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010757 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010758 }
10759 }
10760
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010761
Chris Lattner931f8f32009-08-31 05:17:58 +000010762 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010763 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010764
10765 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010766 return true;
10767}
10768
Duncan Sandscdb6d922007-09-17 10:26:40 +000010769// transformCallThroughTrampoline - Turn a call to a function created by the
10770// init_trampoline intrinsic into a direct call to the underlying function.
10771//
10772Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10773 Value *Callee = CS.getCalledValue();
10774 const PointerType *PTy = cast<PointerType>(Callee->getType());
10775 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010776 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010777
10778 // If the call already has the 'nest' attribute somewhere then give up -
10779 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010780 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010781 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010782
10783 IntrinsicInst *Tramp =
10784 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10785
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010786 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010787 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10788 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10789
Devang Patel05988662008-09-25 21:00:45 +000010790 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010791 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010792 unsigned NestIdx = 1;
10793 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010794 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010795
10796 // Look for a parameter marked with the 'nest' attribute.
10797 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10798 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010799 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010800 // Record the parameter type and any other attributes.
10801 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010802 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010803 break;
10804 }
10805
10806 if (NestTy) {
10807 Instruction *Caller = CS.getInstruction();
10808 std::vector<Value*> NewArgs;
10809 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10810
Devang Patel05988662008-09-25 21:00:45 +000010811 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010812 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010813
Duncan Sandscdb6d922007-09-17 10:26:40 +000010814 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010815 // mean appending it. Likewise for attributes.
10816
Devang Patel19c87462008-09-26 22:53:05 +000010817 // Add any result attributes.
10818 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010819 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010820
Duncan Sandscdb6d922007-09-17 10:26:40 +000010821 {
10822 unsigned Idx = 1;
10823 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10824 do {
10825 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010826 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010827 Value *NestVal = Tramp->getOperand(3);
10828 if (NestVal->getType() != NestTy)
10829 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10830 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010831 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010832 }
10833
10834 if (I == E)
10835 break;
10836
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010837 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010838 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010839 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010840 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010841 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010842
10843 ++Idx, ++I;
10844 } while (1);
10845 }
10846
Devang Patel19c87462008-09-26 22:53:05 +000010847 // Add any function attributes.
10848 if (Attributes Attr = Attrs.getFnAttributes())
10849 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10850
Duncan Sandscdb6d922007-09-17 10:26:40 +000010851 // The trampoline may have been bitcast to a bogus type (FTy).
10852 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010853 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010854
Duncan Sandscdb6d922007-09-17 10:26:40 +000010855 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010856 NewTypes.reserve(FTy->getNumParams()+1);
10857
Duncan Sandscdb6d922007-09-17 10:26:40 +000010858 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010859 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010860 {
10861 unsigned Idx = 1;
10862 FunctionType::param_iterator I = FTy->param_begin(),
10863 E = FTy->param_end();
10864
10865 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010866 if (Idx == NestIdx)
10867 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010868 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010869
10870 if (I == E)
10871 break;
10872
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010873 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010874 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010875
10876 ++Idx, ++I;
10877 } while (1);
10878 }
10879
10880 // Replace the trampoline call with a direct call. Let the generic
10881 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010882 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010883 FTy->isVarArg());
10884 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010885 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010886 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010887 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010888 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10889 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010890
10891 Instruction *NewCaller;
10892 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010893 NewCaller = InvokeInst::Create(NewCallee,
10894 II->getNormalDest(), II->getUnwindDest(),
10895 NewArgs.begin(), NewArgs.end(),
10896 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010897 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010898 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010899 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010900 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10901 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010902 if (cast<CallInst>(Caller)->isTailCall())
10903 cast<CallInst>(NewCaller)->setTailCall();
10904 cast<CallInst>(NewCaller)->
10905 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010906 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010907 }
Devang Patel9674d152009-10-14 17:29:00 +000010908 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010909 Caller->replaceAllUsesWith(NewCaller);
10910 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010911 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010912 return 0;
10913 }
10914 }
10915
10916 // Replace the trampoline call with a direct call. Since there is no 'nest'
10917 // parameter, there is no need to adjust the argument list. Let the generic
10918 // code sort out any function type mismatches.
10919 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010920 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010921 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010922 CS.setCalledFunction(NewCallee);
10923 return CS.getInstruction();
10924}
10925
Dan Gohman9ad29202009-09-16 16:50:24 +000010926/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10927/// 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 +000010928/// and a single binop.
10929Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10930 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010931 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010932 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010933 Value *LHSVal = FirstInst->getOperand(0);
10934 Value *RHSVal = FirstInst->getOperand(1);
10935
10936 const Type *LHSType = LHSVal->getType();
10937 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010938
Dan Gohman9ad29202009-09-16 16:50:24 +000010939 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010940 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010941 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010942 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010943 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010944 // types or GEP's with different index types.
10945 I->getOperand(0)->getType() != LHSType ||
10946 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010947 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010948
10949 // If they are CmpInst instructions, check their predicates
10950 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10951 if (cast<CmpInst>(I)->getPredicate() !=
10952 cast<CmpInst>(FirstInst)->getPredicate())
10953 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010954
10955 // Keep track of which operand needs a phi node.
10956 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10957 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010958 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010959
10960 // If both LHS and RHS would need a PHI, don't do this transformation,
10961 // because it would increase the number of PHIs entering the block,
10962 // which leads to higher register pressure. This is especially
10963 // bad when the PHIs are in the header of a loop.
10964 if (!LHSVal && !RHSVal)
10965 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010966
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010967 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010968
Chris Lattner7da52b22006-11-01 04:51:18 +000010969 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010970 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010971 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010972 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010973 NewLHS = PHINode::Create(LHSType,
10974 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010975 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10976 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010977 InsertNewInstBefore(NewLHS, PN);
10978 LHSVal = NewLHS;
10979 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010980
10981 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010982 NewRHS = PHINode::Create(RHSType,
10983 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010984 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10985 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010986 InsertNewInstBefore(NewRHS, PN);
10987 RHSVal = NewRHS;
10988 }
10989
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010990 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010991 if (NewLHS || NewRHS) {
10992 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10993 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10994 if (NewLHS) {
10995 Value *NewInLHS = InInst->getOperand(0);
10996 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10997 }
10998 if (NewRHS) {
10999 Value *NewInRHS = InInst->getOperand(1);
11000 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
11001 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011002 }
11003 }
11004
Chris Lattner7da52b22006-11-01 04:51:18 +000011005 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011006 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011007 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000011008 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000011009 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000011010}
11011
Chris Lattner05f18922008-12-01 02:34:36 +000011012Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
11013 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
11014
11015 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
11016 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000011017 // This is true if all GEP bases are allocas and if all indices into them are
11018 // constants.
11019 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011020
11021 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000011022 // more than one phi, which leads to higher register pressure. This is
11023 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011024 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000011025
Dan Gohman9ad29202009-09-16 16:50:24 +000011026 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000011027 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11028 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
11029 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
11030 GEP->getNumOperands() != FirstInst->getNumOperands())
11031 return 0;
11032
Chris Lattner36d3e322009-02-21 00:46:50 +000011033 // Keep track of whether or not all GEPs are of alloca pointers.
11034 if (AllBasePointersAreAllocas &&
11035 (!isa<AllocaInst>(GEP->getOperand(0)) ||
11036 !GEP->hasAllConstantIndices()))
11037 AllBasePointersAreAllocas = false;
11038
Chris Lattner05f18922008-12-01 02:34:36 +000011039 // Compare the operand lists.
11040 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
11041 if (FirstInst->getOperand(op) == GEP->getOperand(op))
11042 continue;
11043
11044 // Don't merge two GEPs when two operands differ (introducing phi nodes)
11045 // if one of the PHIs has a constant for the index. The index may be
11046 // substantially cheaper to compute for the constants, so making it a
11047 // variable index could pessimize the path. This also handles the case
11048 // for struct indices, which must always be constant.
11049 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
11050 isa<ConstantInt>(GEP->getOperand(op)))
11051 return 0;
11052
11053 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
11054 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011055
11056 // If we already needed a PHI for an earlier operand, and another operand
11057 // also requires a PHI, we'd be introducing more PHIs than we're
11058 // eliminating, which increases register pressure on entry to the PHI's
11059 // block.
11060 if (NeededPhi)
11061 return 0;
11062
Chris Lattner05f18922008-12-01 02:34:36 +000011063 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011064 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000011065 }
11066 }
11067
Chris Lattner36d3e322009-02-21 00:46:50 +000011068 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000011069 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000011070 // offset calculation, but all the predecessors will have to materialize the
11071 // stack address into a register anyway. We'd actually rather *clone* the
11072 // load up into the predecessors so that we have a load of a gep of an alloca,
11073 // which can usually all be folded into the load.
11074 if (AllBasePointersAreAllocas)
11075 return 0;
11076
Chris Lattner05f18922008-12-01 02:34:36 +000011077 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
11078 // that is variable.
11079 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
11080
11081 bool HasAnyPHIs = false;
11082 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
11083 if (FixedOperands[i]) continue; // operand doesn't need a phi.
11084 Value *FirstOp = FirstInst->getOperand(i);
11085 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
11086 FirstOp->getName()+".pn");
11087 InsertNewInstBefore(NewPN, PN);
11088
11089 NewPN->reserveOperandSpace(e);
11090 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
11091 OperandPhis[i] = NewPN;
11092 FixedOperands[i] = NewPN;
11093 HasAnyPHIs = true;
11094 }
11095
11096
11097 // Add all operands to the new PHIs.
11098 if (HasAnyPHIs) {
11099 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11100 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
11101 BasicBlock *InBB = PN.getIncomingBlock(i);
11102
11103 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
11104 if (PHINode *OpPhi = OperandPhis[op])
11105 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
11106 }
11107 }
11108
11109 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011110 return cast<GEPOperator>(FirstInst)->isInBounds() ?
11111 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
11112 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011113 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
11114 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000011115}
11116
11117
Chris Lattner21550882009-02-23 05:56:17 +000011118/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
11119/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000011120/// obvious the value of the load is not changed from the point of the load to
11121/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011122///
11123/// Finally, it is safe, but not profitable, to sink a load targetting a
11124/// non-address-taken alloca. Doing so will cause us to not promote the alloca
11125/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000011126static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000011127 BasicBlock::iterator BBI = L, E = L->getParent()->end();
11128
11129 for (++BBI; BBI != E; ++BBI)
11130 if (BBI->mayWriteToMemory())
11131 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011132
11133 // Check for non-address taken alloca. If not address-taken already, it isn't
11134 // profitable to do this xform.
11135 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11136 bool isAddressTaken = false;
11137 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11138 UI != E; ++UI) {
11139 if (isa<LoadInst>(UI)) continue;
11140 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11141 // If storing TO the alloca, then the address isn't taken.
11142 if (SI->getOperand(1) == AI) continue;
11143 }
11144 isAddressTaken = true;
11145 break;
11146 }
11147
Chris Lattner36d3e322009-02-21 00:46:50 +000011148 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011149 return false;
11150 }
11151
Chris Lattner36d3e322009-02-21 00:46:50 +000011152 // If this load is a load from a GEP with a constant offset from an alloca,
11153 // then we don't want to sink it. In its present form, it will be
11154 // load [constant stack offset]. Sinking it will cause us to have to
11155 // materialize the stack addresses in each predecessor in a register only to
11156 // do a shared load from register in the successor.
11157 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11158 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11159 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11160 return false;
11161
Chris Lattner76c73142006-11-01 07:13:54 +000011162 return true;
11163}
11164
Chris Lattner751a3622009-11-01 20:04:24 +000011165Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11166 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11167
11168 // When processing loads, we need to propagate two bits of information to the
11169 // sunk load: whether it is volatile, and what its alignment is. We currently
11170 // don't sink loads when some have their alignment specified and some don't.
11171 // visitLoadInst will propagate an alignment onto the load when TD is around,
11172 // and if TD isn't around, we can't handle the mixed case.
11173 bool isVolatile = FirstLI->isVolatile();
11174 unsigned LoadAlignment = FirstLI->getAlignment();
11175
11176 // We can't sink the load if the loaded value could be modified between the
11177 // load and the PHI.
11178 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11179 !isSafeAndProfitableToSinkLoad(FirstLI))
11180 return 0;
11181
11182 // If the PHI is of volatile loads and the load block has multiple
11183 // successors, sinking it would remove a load of the volatile value from
11184 // the path through the other successor.
11185 if (isVolatile &&
11186 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11187 return 0;
11188
11189 // Check to see if all arguments are the same operation.
11190 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11191 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11192 if (!LI || !LI->hasOneUse())
11193 return 0;
11194
11195 // We can't sink the load if the loaded value could be modified between
11196 // the load and the PHI.
11197 if (LI->isVolatile() != isVolatile ||
11198 LI->getParent() != PN.getIncomingBlock(i) ||
11199 !isSafeAndProfitableToSinkLoad(LI))
11200 return 0;
11201
11202 // If some of the loads have an alignment specified but not all of them,
11203 // we can't do the transformation.
11204 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11205 return 0;
11206
Chris Lattnera664bb72009-11-01 20:07:07 +000011207 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000011208
11209 // If the PHI is of volatile loads and the load block has multiple
11210 // successors, sinking it would remove a load of the volatile value from
11211 // the path through the other successor.
11212 if (isVolatile &&
11213 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11214 return 0;
11215 }
11216
11217 // Okay, they are all the same operation. Create a new PHI node of the
11218 // correct type, and PHI together all of the LHS's of the instructions.
11219 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11220 PN.getName()+".in");
11221 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11222
11223 Value *InVal = FirstLI->getOperand(0);
11224 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11225
11226 // Add all operands to the new PHI.
11227 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11228 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11229 if (NewInVal != InVal)
11230 InVal = 0;
11231 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11232 }
11233
11234 Value *PhiVal;
11235 if (InVal) {
11236 // The new PHI unions all of the same values together. This is really
11237 // common, so we handle it intelligently here for compile-time speed.
11238 PhiVal = InVal;
11239 delete NewPN;
11240 } else {
11241 InsertNewInstBefore(NewPN, PN);
11242 PhiVal = NewPN;
11243 }
11244
11245 // If this was a volatile load that we are merging, make sure to loop through
11246 // and mark all the input loads as non-volatile. If we don't do this, we will
11247 // insert a new volatile load and the old ones will not be deletable.
11248 if (isVolatile)
11249 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11250 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11251
11252 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11253}
11254
Chris Lattner9fe38862003-06-19 17:00:31 +000011255
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011256
11257/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11258/// operator and they all are only used by the PHI, PHI together their
11259/// inputs, and do the operation once, to the result of the PHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011260Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11261 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11262
Chris Lattner751a3622009-11-01 20:04:24 +000011263 if (isa<GetElementPtrInst>(FirstInst))
11264 return FoldPHIArgGEPIntoPHI(PN);
11265 if (isa<LoadInst>(FirstInst))
11266 return FoldPHIArgLoadIntoPHI(PN);
11267
Chris Lattnerbac32862004-11-14 19:13:23 +000011268 // Scan the instruction, looking for input operations that can be folded away.
11269 // If all input operands to the phi are the same instruction (e.g. a cast from
11270 // the same type or "+42") we can pull the operation through the PHI, reducing
11271 // code size and simplifying code.
11272 Constant *ConstantOp = 0;
11273 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000011274
Chris Lattnerbac32862004-11-14 19:13:23 +000011275 if (isa<CastInst>(FirstInst)) {
11276 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000011277
11278 // Be careful about transforming integer PHIs. We don't want to pessimize
11279 // the code by turning an i32 into an i1293.
11280 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011281 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattnerbf382b52009-11-08 21:20:06 +000011282 return 0;
11283 }
Reid Spencer832254e2007-02-02 02:16:23 +000011284 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000011285 // Can fold binop, compare or shift here if the RHS is a constant,
11286 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011287 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000011288 if (ConstantOp == 0)
11289 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000011290 } else {
11291 return 0; // Cannot fold this operation.
11292 }
11293
11294 // Check to see if all arguments are the same operation.
11295 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000011296 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11297 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000011298 return 0;
11299 if (CastSrcTy) {
11300 if (I->getOperand(0)->getType() != CastSrcTy)
11301 return 0; // Cast operation must match.
11302 } else if (I->getOperand(1) != ConstantOp) {
11303 return 0;
11304 }
11305 }
11306
11307 // Okay, they are all the same operation. Create a new PHI node of the
11308 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000011309 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11310 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000011311 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000011312
11313 Value *InVal = FirstInst->getOperand(0);
11314 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000011315
11316 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000011317 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11318 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11319 if (NewInVal != InVal)
11320 InVal = 0;
11321 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11322 }
11323
11324 Value *PhiVal;
11325 if (InVal) {
11326 // The new PHI unions all of the same values together. This is really
11327 // common, so we handle it intelligently here for compile-time speed.
11328 PhiVal = InVal;
11329 delete NewPN;
11330 } else {
11331 InsertNewInstBefore(NewPN, PN);
11332 PhiVal = NewPN;
11333 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011334
Chris Lattnerbac32862004-11-14 19:13:23 +000011335 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000011336 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011337 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000011338
Chris Lattner54545ac2008-04-29 17:13:43 +000011339 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011340 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000011341
Chris Lattner751a3622009-11-01 20:04:24 +000011342 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11343 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11344 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000011345}
Chris Lattnera1be5662002-05-02 17:06:02 +000011346
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011347/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11348/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011349static bool DeadPHICycle(PHINode *PN,
11350 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011351 if (PN->use_empty()) return true;
11352 if (!PN->hasOneUse()) return false;
11353
11354 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011355 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011356 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000011357
11358 // Don't scan crazily complex things.
11359 if (PotentiallyDeadPHIs.size() == 16)
11360 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011361
11362 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11363 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000011364
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011365 return false;
11366}
11367
Chris Lattnercf5008a2007-11-06 21:52:06 +000011368/// PHIsEqualValue - Return true if this phi node is always equal to
11369/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11370/// z = some value; x = phi (y, z); y = phi (x, z)
11371static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11372 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11373 // See if we already saw this PHI node.
11374 if (!ValueEqualPHIs.insert(PN))
11375 return true;
11376
11377 // Don't scan crazily complex things.
11378 if (ValueEqualPHIs.size() == 16)
11379 return false;
11380
11381 // Scan the operands to see if they are either phi nodes or are equal to
11382 // the value.
11383 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11384 Value *Op = PN->getIncomingValue(i);
11385 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11386 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11387 return false;
11388 } else if (Op != NonPhiInVal)
11389 return false;
11390 }
11391
11392 return true;
11393}
11394
11395
Chris Lattner9956c052009-11-08 19:23:30 +000011396namespace {
11397struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011398 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000011399 unsigned Shift; // The amount shifted.
11400 Instruction *Inst; // The trunc instruction.
11401
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011402 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11403 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000011404
11405 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011406 if (PHIId < RHS.PHIId) return true;
11407 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000011408 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011409 if (Shift > RHS.Shift) return false;
11410 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000011411 RHS.Inst->getType()->getPrimitiveSizeInBits();
11412 }
11413};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011414
11415struct LoweredPHIRecord {
11416 PHINode *PN; // The PHI that was lowered.
11417 unsigned Shift; // The amount shifted.
11418 unsigned Width; // The width extracted.
11419
11420 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11421 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11422
11423 // Ctor form used by DenseMap.
11424 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11425 : PN(pn), Shift(Sh), Width(0) {}
11426};
11427}
11428
11429namespace llvm {
11430 template<>
11431 struct DenseMapInfo<LoweredPHIRecord> {
11432 static inline LoweredPHIRecord getEmptyKey() {
11433 return LoweredPHIRecord(0, 0);
11434 }
11435 static inline LoweredPHIRecord getTombstoneKey() {
11436 return LoweredPHIRecord(0, 1);
11437 }
11438 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11439 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11440 (Val.Width>>3);
11441 }
11442 static bool isEqual(const LoweredPHIRecord &LHS,
11443 const LoweredPHIRecord &RHS) {
11444 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11445 LHS.Width == RHS.Width;
11446 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011447 };
Chris Lattner4bbf4ee2009-12-15 07:26:43 +000011448 template <>
11449 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner9956c052009-11-08 19:23:30 +000011450}
11451
11452
11453/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11454/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11455/// so, we split the PHI into the various pieces being extracted. This sort of
11456/// thing is introduced when SROA promotes an aggregate to large integer values.
11457///
11458/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11459/// inttoptr. We should produce new PHIs in the right type.
11460///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011461Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11462 // PHIUsers - Keep track of all of the truncated values extracted from a set
11463 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000011464 SmallVector<PHIUsageRecord, 16> PHIUsers;
11465
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011466 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11467 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11468 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11469 // check the uses of (to ensure they are all extracts).
11470 SmallVector<PHINode*, 8> PHIsToSlice;
11471 SmallPtrSet<PHINode*, 8> PHIsInspected;
11472
11473 PHIsToSlice.push_back(&FirstPhi);
11474 PHIsInspected.insert(&FirstPhi);
11475
11476 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11477 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011478
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011479 // Scan the input list of the PHI. If any input is an invoke, and if the
11480 // input is defined in the predecessor, then we won't be split the critical
11481 // edge which is required to insert a truncate. Because of this, we have to
11482 // bail out.
11483 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11484 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11485 if (II == 0) continue;
11486 if (II->getParent() != PN->getIncomingBlock(i))
11487 continue;
11488
11489 // If we have a phi, and if it's directly in the predecessor, then we have
11490 // a critical edge where we need to put the truncate. Since we can't
11491 // split the edge in instcombine, we have to bail out.
11492 return 0;
11493 }
11494
11495
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011496 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11497 UI != E; ++UI) {
11498 Instruction *User = cast<Instruction>(*UI);
11499
11500 // If the user is a PHI, inspect its uses recursively.
11501 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11502 if (PHIsInspected.insert(UserPN))
11503 PHIsToSlice.push_back(UserPN);
11504 continue;
11505 }
11506
11507 // Truncates are always ok.
11508 if (isa<TruncInst>(User)) {
11509 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11510 continue;
11511 }
11512
11513 // Otherwise it must be a lshr which can only be used by one trunc.
11514 if (User->getOpcode() != Instruction::LShr ||
11515 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11516 !isa<ConstantInt>(User->getOperand(1)))
11517 return 0;
11518
11519 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11520 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000011521 }
Chris Lattner9956c052009-11-08 19:23:30 +000011522 }
11523
11524 // If we have no users, they must be all self uses, just nuke the PHI.
11525 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011526 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000011527
11528 // If this phi node is transformable, create new PHIs for all the pieces
11529 // extracted out of it. First, sort the users by their offset and size.
11530 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11531
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011532 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11533 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11534 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11535 );
Chris Lattner9956c052009-11-08 19:23:30 +000011536
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011537 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11538 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000011539 DenseMap<BasicBlock*, Value*> PredValues;
11540
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011541 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11542 // introduce redundant PHIs.
11543 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11544
11545 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11546 unsigned PHIId = PHIUsers[UserI].PHIId;
11547 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011548 unsigned Offset = PHIUsers[UserI].Shift;
11549 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000011550
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011551 PHINode *EltPHI;
11552
11553 // If we've already lowered a user like this, reuse the previously lowered
11554 // value.
11555 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000011556
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011557 // Otherwise, Create the new PHI node for this user.
11558 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11559 assert(EltPHI->getType() != PN->getType() &&
11560 "Truncate didn't shrink phi?");
11561
11562 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11563 BasicBlock *Pred = PN->getIncomingBlock(i);
11564 Value *&PredVal = PredValues[Pred];
11565
11566 // If we already have a value for this predecessor, reuse it.
11567 if (PredVal) {
11568 EltPHI->addIncoming(PredVal, Pred);
11569 continue;
11570 }
Chris Lattner9956c052009-11-08 19:23:30 +000011571
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011572 // Handle the PHI self-reuse case.
11573 Value *InVal = PN->getIncomingValue(i);
11574 if (InVal == PN) {
11575 PredVal = EltPHI;
11576 EltPHI->addIncoming(PredVal, Pred);
11577 continue;
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011578 }
11579
11580 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011581 // If the incoming value was a PHI, and if it was one of the PHIs we
11582 // already rewrote it, just use the lowered value.
11583 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11584 PredVal = Res;
11585 EltPHI->addIncoming(PredVal, Pred);
11586 continue;
11587 }
11588 }
11589
11590 // Otherwise, do an extract in the predecessor.
11591 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11592 Value *Res = InVal;
11593 if (Offset)
11594 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11595 Offset), "extract");
11596 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11597 PredVal = Res;
11598 EltPHI->addIncoming(Res, Pred);
11599
11600 // If the incoming value was a PHI, and if it was one of the PHIs we are
11601 // rewriting, we will ultimately delete the code we inserted. This
11602 // means we need to revisit that PHI to make sure we extract out the
11603 // needed piece.
11604 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11605 if (PHIsInspected.count(OldInVal)) {
11606 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11607 OldInVal)-PHIsToSlice.begin();
11608 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11609 cast<Instruction>(Res)));
11610 ++UserE;
11611 }
Chris Lattner9956c052009-11-08 19:23:30 +000011612 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011613 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000011614
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011615 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11616 << *EltPHI << '\n');
11617 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000011618 }
Chris Lattner9956c052009-11-08 19:23:30 +000011619
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011620 // Replace the use of this piece with the PHI node.
11621 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000011622 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011623
11624 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11625 // with undefs.
11626 Value *Undef = UndefValue::get(FirstPhi.getType());
11627 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11628 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11629 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000011630}
11631
Chris Lattner473945d2002-05-06 18:06:38 +000011632// PHINode simplification
11633//
Chris Lattner7e708292002-06-25 16:13:24 +000011634Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011635 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011636 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011637
Owen Anderson7e057142006-07-10 22:03:18 +000011638 if (Value *V = PN.hasConstantValue())
11639 return ReplaceInstUsesWith(PN, V);
11640
Owen Anderson7e057142006-07-10 22:03:18 +000011641 // If all PHI operands are the same operation, pull them through the PHI,
11642 // reducing code size.
11643 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011644 isa<Instruction>(PN.getIncomingValue(1)) &&
11645 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11646 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11647 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11648 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011649 PN.getIncomingValue(0)->hasOneUse())
11650 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11651 return Result;
11652
11653 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11654 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11655 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011656 if (PN.hasOneUse()) {
11657 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11658 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011659 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011660 PotentiallyDeadPHIs.insert(&PN);
11661 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011662 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000011663 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011664
11665 // If this phi has a single use, and if that use just computes a value for
11666 // the next iteration of a loop, delete the phi. This occurs with unused
11667 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11668 // common case here is good because the only other things that catch this
11669 // are induction variable analysis (sometimes) and ADCE, which is only run
11670 // late.
11671 if (PHIUser->hasOneUse() &&
11672 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11673 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011674 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011675 }
11676 }
Owen Anderson7e057142006-07-10 22:03:18 +000011677
Chris Lattnercf5008a2007-11-06 21:52:06 +000011678 // We sometimes end up with phi cycles that non-obviously end up being the
11679 // same value, for example:
11680 // z = some value; x = phi (y, z); y = phi (x, z)
11681 // where the phi nodes don't necessarily need to be in the same block. Do a
11682 // quick check to see if the PHI node only contains a single non-phi value, if
11683 // so, scan to see if the phi cycle is actually equal to that value.
11684 {
11685 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11686 // Scan for the first non-phi operand.
11687 while (InValNo != NumOperandVals &&
11688 isa<PHINode>(PN.getIncomingValue(InValNo)))
11689 ++InValNo;
11690
11691 if (InValNo != NumOperandVals) {
11692 Value *NonPhiInVal = PN.getOperand(InValNo);
11693
11694 // Scan the rest of the operands to see if there are any conflicts, if so
11695 // there is no need to recursively scan other phis.
11696 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11697 Value *OpVal = PN.getIncomingValue(InValNo);
11698 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11699 break;
11700 }
11701
11702 // If we scanned over all operands, then we have one unique value plus
11703 // phi values. Scan PHI nodes to see if they all merge in each other or
11704 // the value.
11705 if (InValNo == NumOperandVals) {
11706 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11707 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11708 return ReplaceInstUsesWith(PN, NonPhiInVal);
11709 }
11710 }
11711 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011712
Dan Gohman5b097012009-10-31 14:22:52 +000011713 // If there are multiple PHIs, sort their operands so that they all list
11714 // the blocks in the same order. This will help identical PHIs be eliminated
11715 // by other passes. Other passes shouldn't depend on this for correctness
11716 // however.
11717 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11718 if (&PN != FirstPN)
11719 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011720 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000011721 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11722 if (BBA != BBB) {
11723 Value *VA = PN.getIncomingValue(i);
11724 unsigned j = PN.getBasicBlockIndex(BBB);
11725 Value *VB = PN.getIncomingValue(j);
11726 PN.setIncomingBlock(i, BBB);
11727 PN.setIncomingValue(i, VB);
11728 PN.setIncomingBlock(j, BBA);
11729 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000011730 // NOTE: Instcombine normally would want us to "return &PN" if we
11731 // modified any of the operands of an instruction. However, since we
11732 // aren't adding or removing uses (just rearranging them) we don't do
11733 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000011734 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011735 }
11736
Chris Lattner9956c052009-11-08 19:23:30 +000011737 // If this is an integer PHI and we know that it has an illegal type, see if
11738 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11739 // PHI into the various pieces being extracted. This sort of thing is
11740 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000011741 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000011742 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11743 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11744 return Res;
11745
Chris Lattner60921c92003-12-19 05:58:40 +000011746 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011747}
11748
Chris Lattner7e708292002-06-25 16:13:24 +000011749Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +000011750 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11751
11752 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11753 return ReplaceInstUsesWith(GEP, V);
11754
Chris Lattner620ce142004-05-07 22:09:22 +000011755 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011756
Chris Lattnere87597f2004-10-16 18:11:37 +000011757 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011758 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011759
Chris Lattner28977af2004-04-05 01:30:19 +000011760 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011761 if (TD) {
11762 bool MadeChange = false;
11763 unsigned PtrSize = TD->getPointerSizeInBits();
11764
11765 gep_type_iterator GTI = gep_type_begin(GEP);
11766 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11767 I != E; ++I, ++GTI) {
11768 if (!isa<SequentialType>(*GTI)) continue;
11769
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011770 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011771 // to what we need. If narrower, sign-extend it to what we need. This
11772 // explicit cast can make subsequent optimizations more obvious.
11773 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000011774 if (OpBits == PtrSize)
11775 continue;
11776
Chris Lattner2345d1d2009-08-30 20:01:10 +000011777 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011778 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011779 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011780 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011781 }
Chris Lattner28977af2004-04-05 01:30:19 +000011782
Chris Lattner90ac28c2002-08-02 19:29:35 +000011783 // Combine Indices - If the source pointer to this getelementptr instruction
11784 // is a getelementptr instruction, combine the indices of the two
11785 // getelementptr instructions into a single instruction.
11786 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011787 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011788 // Note that if our source is a gep chain itself that we wait for that
11789 // chain to be resolved before we perform this transformation. This
11790 // avoids us creating a TON of code in some cases.
11791 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011792 if (GetElementPtrInst *SrcGEP =
11793 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11794 if (SrcGEP->getNumOperands() == 2)
11795 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011796
Chris Lattner72588fc2007-02-15 22:48:32 +000011797 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011798
11799 // Find out whether the last index in the source GEP is a sequential idx.
11800 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011801 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11802 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011803 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011804
Chris Lattner90ac28c2002-08-02 19:29:35 +000011805 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011806 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011807 // Replace: gep (gep %P, long B), long A, ...
11808 // With: T = long A+B; gep %P, T, ...
11809 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011810 Value *Sum;
11811 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11812 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011813 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011814 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011815 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011816 Sum = SO1;
11817 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011818 // If they aren't the same type, then the input hasn't been processed
11819 // by the loop above yet (which canonicalizes sequential index types to
11820 // intptr_t). Just avoid transforming this until the input has been
11821 // normalized.
11822 if (SO1->getType() != GO1->getType())
11823 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011824 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000011825 }
Chris Lattner620ce142004-05-07 22:09:22 +000011826
Chris Lattnerab984842009-08-30 05:30:55 +000011827 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011828 if (Src->getNumOperands() == 2) {
11829 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011830 GEP.setOperand(1, Sum);
11831 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011832 }
Chris Lattnerab984842009-08-30 05:30:55 +000011833 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011834 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011835 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011836 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011837 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011838 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011839 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011840 Indices.append(Src->op_begin()+1, Src->op_end());
11841 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011842 }
11843
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011844 if (!Indices.empty())
11845 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11846 Src->isInBounds()) ?
11847 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11848 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011849 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011850 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011851 }
11852
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011853 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11854 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011855 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011856
Chris Lattner2de23192009-08-30 20:38:21 +000011857 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11858 // want to change the gep until the bitcasts are eliminated.
11859 if (getBitCastOperand(X)) {
11860 Worklist.AddValue(PtrOp);
11861 return 0;
11862 }
11863
Chris Lattnerc514c1f2009-11-27 00:29:05 +000011864 bool HasZeroPointerIndex = false;
11865 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
11866 HasZeroPointerIndex = C->isZero();
11867
Chris Lattner963f4ba2009-08-30 20:36:46 +000011868 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11869 // into : GEP [10 x i8]* X, i32 0, ...
11870 //
11871 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11872 // into : GEP i8* X, ...
11873 //
11874 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011875 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011876 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11877 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011878 if (const ArrayType *CATy =
11879 dyn_cast<ArrayType>(CPTy->getElementType())) {
11880 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11881 if (CATy->getElementType() == XTy->getElementType()) {
11882 // -> GEP i8* X, ...
11883 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011884 return cast<GEPOperator>(&GEP)->isInBounds() ?
11885 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11886 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011887 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11888 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011889 }
11890
11891 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011892 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011893 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011894 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011895 // At this point, we know that the cast source type is a pointer
11896 // to an array of the same type as the destination pointer
11897 // array. Because the array type is never stepped over (there
11898 // is a leading zero) we can fold the cast into this GEP.
11899 GEP.setOperand(0, X);
11900 return &GEP;
11901 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011902 }
11903 }
Chris Lattnereed48272005-09-13 00:40:14 +000011904 } else if (GEP.getNumOperands() == 2) {
11905 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011906 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11907 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011908 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11909 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011910 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011911 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11912 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011913 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011914 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011915 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011916 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11917 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011918 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011919 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011920 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011921 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011922
11923 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011924 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011925 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011926 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011927
Owen Anderson1d0be152009-08-13 21:58:54 +000011928 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011929 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011930 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011931
11932 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11933 // allow either a mul, shift, or constant here.
11934 Value *NewIdx = 0;
11935 ConstantInt *Scale = 0;
11936 if (ArrayEltSize == 1) {
11937 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011938 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011939 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011940 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011941 Scale = CI;
11942 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11943 if (Inst->getOpcode() == Instruction::Shl &&
11944 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011945 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11946 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011947 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011948 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011949 NewIdx = Inst->getOperand(0);
11950 } else if (Inst->getOpcode() == Instruction::Mul &&
11951 isa<ConstantInt>(Inst->getOperand(1))) {
11952 Scale = cast<ConstantInt>(Inst->getOperand(1));
11953 NewIdx = Inst->getOperand(0);
11954 }
11955 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011956
Chris Lattner7835cdd2005-09-13 18:36:04 +000011957 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011958 // out, perform the transformation. Note, we don't know whether Scale is
11959 // signed or not. We'll use unsigned version of division/modulo
11960 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011961 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011962 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011963 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011964 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011965 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011966 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11967 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011968 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011969 }
11970
11971 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011972 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011973 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011974 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011975 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11976 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11977 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011978 // The NewGEP must be pointer typed, so must the old one -> BitCast
11979 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011980 }
11981 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011982 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011983 }
Chris Lattner58407792009-01-09 04:53:57 +000011984
Chris Lattner46cd5a12009-01-09 05:44:56 +000011985 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011986 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011987 /// Y = gep X, <...constant indices...>
11988 /// into a gep of the original struct. This is important for SROA and alias
11989 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011990 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011991 if (TD &&
11992 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011993 // Determine how much the GEP moves the pointer. We are guaranteed to get
11994 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000011995 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011996 int64_t Offset = OffsetV->getSExtValue();
11997
11998 // If this GEP instruction doesn't move the pointer, just replace the GEP
11999 // with a bitcast of the real input to the dest type.
12000 if (Offset == 0) {
12001 // If the bitcast is of an allocation, and the allocation will be
12002 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000012003 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000012004 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000012005 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
12006 if (Instruction *I = visitBitCast(*BCI)) {
12007 if (I != BCI) {
12008 I->takeName(BCI);
12009 BCI->getParent()->getInstList().insert(BCI, I);
12010 ReplaceInstUsesWith(*BCI, I);
12011 }
12012 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000012013 }
Chris Lattner58407792009-01-09 04:53:57 +000012014 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000012015 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000012016 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000012017
12018 // Otherwise, if the offset is non-zero, we need to find out if there is a
12019 // field at Offset in 'A's type. If so, we can pull the cast through the
12020 // GEP.
12021 SmallVector<Value*, 8> NewIndices;
12022 const Type *InTy =
12023 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000012024 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012025 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12026 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
12027 NewIndices.end()) :
12028 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
12029 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012030
12031 if (NGEP->getType() == GEP.getType())
12032 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000012033 NGEP->takeName(&GEP);
12034 return new BitCastInst(NGEP, GEP.getType());
12035 }
Chris Lattner58407792009-01-09 04:53:57 +000012036 }
12037 }
12038
Chris Lattner8a2a3112001-12-14 16:52:21 +000012039 return 0;
12040}
12041
Victor Hernandez7b929da2009-10-23 21:09:37 +000012042Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000012043 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012044 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000012045 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
12046 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000012047 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000012048 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000012049 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012050 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000012051
Chris Lattner0864acf2002-11-04 16:18:53 +000012052 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000012053 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000012054 //
12055 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000012056 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000012057
12058 // Now that I is pointing to the first non-allocation-inst in the block,
12059 // insert our getelementptr instruction...
12060 //
Owen Anderson1d0be152009-08-13 21:58:54 +000012061 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000012062 Value *Idx[2];
12063 Idx[0] = NullIdx;
12064 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012065 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
12066 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000012067
12068 // Now make everything use the getelementptr instead of the original
12069 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000012070 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000012071 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000012072 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000012073 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012074 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012075
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012076 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000012077 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000012078 // Note that we only do this for alloca's, because malloc should allocate
12079 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000012080 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000012081 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000012082
12083 // If the alignment is 0 (unspecified), assign it the preferred alignment.
12084 if (AI.getAlignment() == 0)
12085 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
12086 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012087
Chris Lattner0864acf2002-11-04 16:18:53 +000012088 return 0;
12089}
12090
Victor Hernandez66284e02009-10-24 04:23:03 +000012091Instruction *InstCombiner::visitFree(Instruction &FI) {
12092 Value *Op = FI.getOperand(1);
12093
12094 // free undef -> unreachable.
12095 if (isa<UndefValue>(Op)) {
12096 // Insert a new store to null because we cannot modify the CFG here.
12097 new StoreInst(ConstantInt::getTrue(*Context),
12098 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
12099 return EraseInstFromFunction(FI);
12100 }
12101
12102 // If we have 'free null' delete the instruction. This can happen in stl code
12103 // when lots of inlining happens.
12104 if (isa<ConstantPointerNull>(Op))
12105 return EraseInstFromFunction(FI);
12106
Victor Hernandez046e78c2009-10-26 23:43:48 +000012107 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000012108 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000012109 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
12110 if (Op->hasOneUse() && CI->hasOneUse()) {
12111 EraseInstFromFunction(FI);
12112 EraseInstFromFunction(*CI);
12113 return EraseInstFromFunction(*cast<Instruction>(Op));
12114 }
12115 } else {
12116 // Op is a call to malloc
12117 if (Op->hasOneUse()) {
12118 EraseInstFromFunction(FI);
12119 return EraseInstFromFunction(*cast<Instruction>(Op));
12120 }
12121 }
Dan Gohman7f712a12009-10-27 00:11:02 +000012122 }
Victor Hernandez66284e02009-10-24 04:23:03 +000012123
12124 return 0;
12125}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000012126
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012127/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000012128static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000012129 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000012130 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000012131 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000012132 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000012133
Mon P Wang6753f952009-02-07 22:19:29 +000012134 const PointerType *DestTy = cast<PointerType>(CI->getType());
12135 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012136 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000012137
12138 // If the address spaces don't match, don't eliminate the cast.
12139 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12140 return 0;
12141
Chris Lattnerb89e0712004-07-13 01:49:43 +000012142 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012143
Reid Spencer42230162007-01-22 05:51:25 +000012144 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012145 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000012146 // If the source is an array, the code below will not succeed. Check to
12147 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12148 // constants.
12149 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12150 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12151 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000012152 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000012153 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12154 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000012155 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000012156 SrcTy = cast<PointerType>(CastOp->getType());
12157 SrcPTy = SrcTy->getElementType();
12158 }
12159
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012160 if (IC.getTargetData() &&
12161 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012162 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000012163 // Do not allow turning this into a load of an integer, which is then
12164 // casted to a pointer, this pessimizes pointer analysis a lot.
12165 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012166 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12167 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000012168
Chris Lattnerf9527852005-01-31 04:50:46 +000012169 // Okay, we are casting from one integer or pointer type to another of
12170 // the same size. Instead of casting the pointer before the load, cast
12171 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012172 Value *NewLoad =
12173 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000012174 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000012175 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000012176 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000012177 }
12178 }
12179 return 0;
12180}
12181
Chris Lattner833b8a42003-06-26 05:06:25 +000012182Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12183 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000012184
Dan Gohman9941f742007-07-20 16:34:21 +000012185 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012186 if (TD) {
12187 unsigned KnownAlign =
12188 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12189 if (KnownAlign >
12190 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12191 LI.getAlignment()))
12192 LI.setAlignment(KnownAlign);
12193 }
Dan Gohman9941f742007-07-20 16:34:21 +000012194
Chris Lattner963f4ba2009-08-30 20:36:46 +000012195 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012196 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000012197 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000012198 return Res;
12199
12200 // None of the following transforms are legal for volatile loads.
12201 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000012202
Dan Gohman2276a7b2008-10-15 23:19:35 +000012203 // Do really simple store-to-load forwarding and load CSE, to catch cases
12204 // where there are several consequtive memory accesses to the same location,
12205 // separated by a few arithmetic operations.
12206 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000012207 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12208 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000012209
Chris Lattner878e4942009-10-22 06:25:11 +000012210 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000012211 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12212 const Value *GEPI0 = GEPI->getOperand(0);
12213 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000012214 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000012215 // Insert a new store to null instruction before the load to indicate
12216 // that this code is not reachable. We do this instead of inserting
12217 // an unreachable instruction directly because we cannot modify the
12218 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012219 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000012220 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012221 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000012222 }
Christopher Lambb15147e2007-12-29 07:56:53 +000012223 }
Chris Lattner37366c12005-05-01 04:24:53 +000012224
Chris Lattner878e4942009-10-22 06:25:11 +000012225 // load null/undef -> unreachable
12226 // TODO: Consider a target hook for valid address spaces for this xform.
12227 if (isa<UndefValue>(Op) ||
12228 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12229 // Insert a new store to null instruction before the load to indicate that
12230 // this code is not reachable. We do this instead of inserting an
12231 // unreachable instruction directly because we cannot modify the CFG.
12232 new StoreInst(UndefValue::get(LI.getType()),
12233 Constant::getNullValue(Op->getType()), &LI);
12234 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000012235 }
Chris Lattner878e4942009-10-22 06:25:11 +000012236
12237 // Instcombine load (constantexpr_cast global) -> cast (load global)
12238 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12239 if (CE->isCast())
12240 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12241 return Res;
12242
Chris Lattner37366c12005-05-01 04:24:53 +000012243 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000012244 // Change select and PHI nodes to select values instead of addresses: this
12245 // helps alias analysis out a lot, allows many others simplifications, and
12246 // exposes redundancy in the code.
12247 //
12248 // Note that we cannot do the transformation unless we know that the
12249 // introduced loads cannot trap! Something like this is valid as long as
12250 // the condition is always false: load (select bool %C, int* null, int* %G),
12251 // but it would not be valid if we transformed it to load from null
12252 // unconditionally.
12253 //
12254 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12255 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000012256 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12257 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012258 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12259 SI->getOperand(1)->getName()+".val");
12260 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12261 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000012262 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000012263 }
12264
Chris Lattner684fe212004-09-23 15:46:00 +000012265 // load (select (cond, null, P)) -> load P
12266 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12267 if (C->isNullValue()) {
12268 LI.setOperand(0, SI->getOperand(2));
12269 return &LI;
12270 }
12271
12272 // load (select (cond, P, null)) -> load P
12273 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12274 if (C->isNullValue()) {
12275 LI.setOperand(0, SI->getOperand(1));
12276 return &LI;
12277 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000012278 }
12279 }
Chris Lattner833b8a42003-06-26 05:06:25 +000012280 return 0;
12281}
12282
Reid Spencer55af2b52007-01-19 21:20:31 +000012283/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000012284/// when possible. This makes it generally easy to do alias analysis and/or
12285/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012286static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12287 User *CI = cast<User>(SI.getOperand(1));
12288 Value *CastOp = CI->getOperand(0);
12289
12290 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012291 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12292 if (SrcTy == 0) return 0;
12293
12294 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012295
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012296 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12297 return 0;
12298
Chris Lattner3914f722009-01-24 01:00:13 +000012299 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12300 /// to its first element. This allows us to handle things like:
12301 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12302 /// on 32-bit hosts.
12303 SmallVector<Value*, 4> NewGEPIndices;
12304
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012305 // If the source is an array, the code below will not succeed. Check to
12306 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12307 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000012308 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12309 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000012310 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000012311 NewGEPIndices.push_back(Zero);
12312
12313 while (1) {
12314 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000012315 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000012316 break;
Chris Lattner3914f722009-01-24 01:00:13 +000012317 NewGEPIndices.push_back(Zero);
12318 SrcPTy = STy->getElementType(0);
12319 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12320 NewGEPIndices.push_back(Zero);
12321 SrcPTy = ATy->getElementType();
12322 } else {
12323 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012324 }
Chris Lattner3914f722009-01-24 01:00:13 +000012325 }
12326
Owen Andersondebcb012009-07-29 22:17:13 +000012327 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000012328 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012329
12330 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12331 return 0;
12332
Chris Lattner71759c42009-01-16 20:12:52 +000012333 // If the pointers point into different address spaces or if they point to
12334 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012335 if (!IC.getTargetData() ||
12336 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000012337 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012338 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12339 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012340 return 0;
12341
12342 // Okay, we are casting from one integer or pointer type to another of
12343 // the same size. Instead of casting the pointer before
12344 // the store, cast the value to be stored.
12345 Value *NewCast;
12346 Value *SIOp0 = SI.getOperand(0);
12347 Instruction::CastOps opcode = Instruction::BitCast;
12348 const Type* CastSrcTy = SIOp0->getType();
12349 const Type* CastDstTy = SrcPTy;
12350 if (isa<PointerType>(CastDstTy)) {
12351 if (CastSrcTy->isInteger())
12352 opcode = Instruction::IntToPtr;
12353 } else if (isa<IntegerType>(CastDstTy)) {
12354 if (isa<PointerType>(SIOp0->getType()))
12355 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012356 }
Chris Lattner3914f722009-01-24 01:00:13 +000012357
12358 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12359 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012360 if (!NewGEPIndices.empty())
12361 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12362 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000012363
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012364 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12365 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012366 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012367}
12368
Chris Lattner4aebaee2008-11-27 08:56:30 +000012369/// equivalentAddressValues - Test if A and B will obviously have the same
12370/// value. This includes recognizing that %t0 and %t1 will have the same
12371/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012372/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012373/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012374/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012375/// %t2 = load i32* %t1
12376///
12377static bool equivalentAddressValues(Value *A, Value *B) {
12378 // Test if the values are trivially equivalent.
12379 if (A == B) return true;
12380
12381 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012382 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12383 // its only used to compare two uses within the same basic block, which
12384 // means that they'll always either have the same value or one of them
12385 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000012386 if (isa<BinaryOperator>(A) ||
12387 isa<CastInst>(A) ||
12388 isa<PHINode>(A) ||
12389 isa<GetElementPtrInst>(A))
12390 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012391 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000012392 return true;
12393
12394 // Otherwise they may not be equivalent.
12395 return false;
12396}
12397
Dale Johannesen4945c652009-03-03 21:26:39 +000012398// If this instruction has two uses, one of which is a llvm.dbg.declare,
12399// return the llvm.dbg.declare.
12400DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12401 if (!V->hasNUses(2))
12402 return 0;
12403 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12404 UI != E; ++UI) {
12405 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12406 return DI;
12407 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12408 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12409 return DI;
12410 }
12411 }
12412 return 0;
12413}
12414
Chris Lattner2f503e62005-01-31 05:36:43 +000012415Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12416 Value *Val = SI.getOperand(0);
12417 Value *Ptr = SI.getOperand(1);
12418
Chris Lattner836692d2007-01-15 06:51:56 +000012419 // If the RHS is an alloca with a single use, zapify the store, making the
12420 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000012421 // If the RHS is an alloca with a two uses, the other one being a
12422 // llvm.dbg.declare, zapify the store and the declare, making the
12423 // alloca dead. We must do this to prevent declare's from affecting
12424 // codegen.
12425 if (!SI.isVolatile()) {
12426 if (Ptr->hasOneUse()) {
12427 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000012428 EraseInstFromFunction(SI);
12429 ++NumCombined;
12430 return 0;
12431 }
Dale Johannesen4945c652009-03-03 21:26:39 +000012432 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12433 if (isa<AllocaInst>(GEP->getOperand(0))) {
12434 if (GEP->getOperand(0)->hasOneUse()) {
12435 EraseInstFromFunction(SI);
12436 ++NumCombined;
12437 return 0;
12438 }
12439 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12440 EraseInstFromFunction(*DI);
12441 EraseInstFromFunction(SI);
12442 ++NumCombined;
12443 return 0;
12444 }
12445 }
12446 }
12447 }
12448 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12449 EraseInstFromFunction(*DI);
12450 EraseInstFromFunction(SI);
12451 ++NumCombined;
12452 return 0;
12453 }
Chris Lattner836692d2007-01-15 06:51:56 +000012454 }
Chris Lattner2f503e62005-01-31 05:36:43 +000012455
Dan Gohman9941f742007-07-20 16:34:21 +000012456 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012457 if (TD) {
12458 unsigned KnownAlign =
12459 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12460 if (KnownAlign >
12461 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12462 SI.getAlignment()))
12463 SI.setAlignment(KnownAlign);
12464 }
Dan Gohman9941f742007-07-20 16:34:21 +000012465
Dale Johannesenacb51a32009-03-03 01:43:03 +000012466 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000012467 // stores to the same location, separated by a few arithmetic operations. This
12468 // situation often occurs with bitfield accesses.
12469 BasicBlock::iterator BBI = &SI;
12470 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12471 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000012472 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012473 // Don't count debug info directives, lest they affect codegen,
12474 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12475 // It is necessary for correctness to skip those that feed into a
12476 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000012477 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012478 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000012479 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000012480 continue;
12481 }
Chris Lattner9ca96412006-02-08 03:25:32 +000012482
12483 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12484 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000012485 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12486 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012487 ++NumDeadStore;
12488 ++BBI;
12489 EraseInstFromFunction(*PrevSI);
12490 continue;
12491 }
12492 break;
12493 }
12494
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012495 // If this is a load, we have to stop. However, if the loaded value is from
12496 // the pointer we're loading and is producing the pointer we're storing,
12497 // then *this* store is dead (X = load P; store X -> P).
12498 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000012499 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12500 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012501 EraseInstFromFunction(SI);
12502 ++NumCombined;
12503 return 0;
12504 }
12505 // Otherwise, this is a load from some other location. Stores before it
12506 // may not be dead.
12507 break;
12508 }
12509
Chris Lattner9ca96412006-02-08 03:25:32 +000012510 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000012511 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000012512 break;
12513 }
12514
12515
12516 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000012517
12518 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000012519 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000012520 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012521 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000012522 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000012523 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000012524 ++NumCombined;
12525 }
12526 return 0; // Do not modify these!
12527 }
12528
12529 // store undef, Ptr -> noop
12530 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012531 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012532 ++NumCombined;
12533 return 0;
12534 }
12535
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012536 // If the pointer destination is a cast, see if we can fold the cast into the
12537 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012538 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012539 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12540 return Res;
12541 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000012542 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012543 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12544 return Res;
12545
Chris Lattner408902b2005-09-12 23:23:25 +000012546
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012547 // If this store is the last instruction in the basic block (possibly
12548 // excepting debug info instructions and the pointer bitcasts that feed
12549 // into them), and if the block ends with an unconditional branch, try
12550 // to move it to the successor block.
12551 BBI = &SI;
12552 do {
12553 ++BBI;
12554 } while (isa<DbgInfoIntrinsic>(BBI) ||
12555 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000012556 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012557 if (BI->isUnconditional())
12558 if (SimplifyStoreAtEndOfBlock(SI))
12559 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000012560
Chris Lattner2f503e62005-01-31 05:36:43 +000012561 return 0;
12562}
12563
Chris Lattner3284d1f2007-04-15 00:07:55 +000012564/// SimplifyStoreAtEndOfBlock - Turn things like:
12565/// if () { *P = v1; } else { *P = v2 }
12566/// into a phi node with a store in the successor.
12567///
Chris Lattner31755a02007-04-15 01:02:18 +000012568/// Simplify things like:
12569/// *P = v1; if () { *P = v2; }
12570/// into a phi node with a store in the successor.
12571///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012572bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12573 BasicBlock *StoreBB = SI.getParent();
12574
12575 // Check to see if the successor block has exactly two incoming edges. If
12576 // so, see if the other predecessor contains a store to the same location.
12577 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012578 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012579
12580 // Determine whether Dest has exactly two predecessors and, if so, compute
12581 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012582 pred_iterator PI = pred_begin(DestBB);
12583 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012584 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012585 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012586 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012587 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012588 return false;
12589
12590 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012591 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012592 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012593 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012594 }
Chris Lattner31755a02007-04-15 01:02:18 +000012595 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012596 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012597
12598 // Bail out if all the relevant blocks aren't distinct (this can happen,
12599 // for example, if SI is in an infinite loop)
12600 if (StoreBB == DestBB || OtherBB == DestBB)
12601 return false;
12602
Chris Lattner31755a02007-04-15 01:02:18 +000012603 // Verify that the other block ends in a branch and is not otherwise empty.
12604 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012605 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012606 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012607 return false;
12608
Chris Lattner31755a02007-04-15 01:02:18 +000012609 // If the other block ends in an unconditional branch, check for the 'if then
12610 // else' case. there is an instruction before the branch.
12611 StoreInst *OtherStore = 0;
12612 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012613 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012614 // Skip over debugging info.
12615 while (isa<DbgInfoIntrinsic>(BBI) ||
12616 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12617 if (BBI==OtherBB->begin())
12618 return false;
12619 --BBI;
12620 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012621 // If this isn't a store, isn't a store to the same location, or if the
12622 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012623 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012624 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12625 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012626 return false;
12627 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012628 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012629 // destinations is StoreBB, then we have the if/then case.
12630 if (OtherBr->getSuccessor(0) != StoreBB &&
12631 OtherBr->getSuccessor(1) != StoreBB)
12632 return false;
12633
12634 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012635 // if/then triangle. See if there is a store to the same ptr as SI that
12636 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012637 for (;; --BBI) {
12638 // Check to see if we find the matching store.
12639 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012640 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12641 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012642 return false;
12643 break;
12644 }
Eli Friedman6903a242008-06-13 22:02:12 +000012645 // If we find something that may be using or overwriting the stored
12646 // value, or if we run out of instructions, we can't do the xform.
12647 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012648 BBI == OtherBB->begin())
12649 return false;
12650 }
12651
12652 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012653 // make sure nothing reads or overwrites the stored value in
12654 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012655 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12656 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012657 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012658 return false;
12659 }
12660 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012661
Chris Lattner31755a02007-04-15 01:02:18 +000012662 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012663 Value *MergedVal = OtherStore->getOperand(0);
12664 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012665 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012666 PN->reserveOperandSpace(2);
12667 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012668 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12669 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012670 }
12671
12672 // Advance to a place where it is safe to insert the new store and
12673 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012674 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012675 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012676 OtherStore->isVolatile(),
12677 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012678
12679 // Nuke the old stores.
12680 EraseInstFromFunction(SI);
12681 EraseInstFromFunction(*OtherStore);
12682 ++NumCombined;
12683 return true;
12684}
12685
Chris Lattner2f503e62005-01-31 05:36:43 +000012686
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012687Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12688 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012689 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012690 BasicBlock *TrueDest;
12691 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012692 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012693 !isa<Constant>(X)) {
12694 // Swap Destinations and condition...
12695 BI.setCondition(X);
12696 BI.setSuccessor(0, FalseDest);
12697 BI.setSuccessor(1, TrueDest);
12698 return &BI;
12699 }
12700
Reid Spencere4d87aa2006-12-23 06:05:41 +000012701 // Cannonicalize fcmp_one -> fcmp_oeq
12702 FCmpInst::Predicate FPred; Value *Y;
12703 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012704 TrueDest, FalseDest)) &&
12705 BI.getCondition()->hasOneUse())
12706 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12707 FPred == FCmpInst::FCMP_OGE) {
12708 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12709 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12710
12711 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012712 BI.setSuccessor(0, FalseDest);
12713 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012714 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012715 return &BI;
12716 }
12717
12718 // Cannonicalize icmp_ne -> icmp_eq
12719 ICmpInst::Predicate IPred;
12720 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012721 TrueDest, FalseDest)) &&
12722 BI.getCondition()->hasOneUse())
12723 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12724 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12725 IPred == ICmpInst::ICMP_SGE) {
12726 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12727 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12728 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012729 BI.setSuccessor(0, FalseDest);
12730 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012731 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012732 return &BI;
12733 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012734
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012735 return 0;
12736}
Chris Lattner0864acf2002-11-04 16:18:53 +000012737
Chris Lattner46238a62004-07-03 00:26:11 +000012738Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12739 Value *Cond = SI.getCondition();
12740 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12741 if (I->getOpcode() == Instruction::Add)
12742 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12743 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12744 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012745 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012746 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012747 AddRHS));
12748 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012749 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012750 return &SI;
12751 }
12752 }
12753 return 0;
12754}
12755
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012756Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012757 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012758
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012759 if (!EV.hasIndices())
12760 return ReplaceInstUsesWith(EV, Agg);
12761
12762 if (Constant *C = dyn_cast<Constant>(Agg)) {
12763 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012764 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012765
12766 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012767 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012768
12769 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12770 // Extract the element indexed by the first index out of the constant
12771 Value *V = C->getOperand(*EV.idx_begin());
12772 if (EV.getNumIndices() > 1)
12773 // Extract the remaining indices out of the constant indexed by the
12774 // first index
12775 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12776 else
12777 return ReplaceInstUsesWith(EV, V);
12778 }
12779 return 0; // Can't handle other constants
12780 }
12781 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12782 // We're extracting from an insertvalue instruction, compare the indices
12783 const unsigned *exti, *exte, *insi, *inse;
12784 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12785 exte = EV.idx_end(), inse = IV->idx_end();
12786 exti != exte && insi != inse;
12787 ++exti, ++insi) {
12788 if (*insi != *exti)
12789 // The insert and extract both reference distinctly different elements.
12790 // This means the extract is not influenced by the insert, and we can
12791 // replace the aggregate operand of the extract with the aggregate
12792 // operand of the insert. i.e., replace
12793 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12794 // %E = extractvalue { i32, { i32 } } %I, 0
12795 // with
12796 // %E = extractvalue { i32, { i32 } } %A, 0
12797 return ExtractValueInst::Create(IV->getAggregateOperand(),
12798 EV.idx_begin(), EV.idx_end());
12799 }
12800 if (exti == exte && insi == inse)
12801 // Both iterators are at the end: Index lists are identical. Replace
12802 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12803 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12804 // with "i32 42"
12805 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12806 if (exti == exte) {
12807 // The extract list is a prefix of the insert list. i.e. replace
12808 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12809 // %E = extractvalue { i32, { i32 } } %I, 1
12810 // with
12811 // %X = extractvalue { i32, { i32 } } %A, 1
12812 // %E = insertvalue { i32 } %X, i32 42, 0
12813 // by switching the order of the insert and extract (though the
12814 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012815 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12816 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012817 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12818 insi, inse);
12819 }
12820 if (insi == inse)
12821 // The insert list is a prefix of the extract list
12822 // We can simply remove the common indices from the extract and make it
12823 // operate on the inserted value instead of the insertvalue result.
12824 // i.e., replace
12825 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12826 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12827 // with
12828 // %E extractvalue { i32 } { i32 42 }, 0
12829 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12830 exti, exte);
12831 }
Chris Lattner7e606e22009-11-09 07:07:56 +000012832 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12833 // We're extracting from an intrinsic, see if we're the only user, which
12834 // allows us to simplify multiple result intrinsics to simpler things that
12835 // just get one value..
12836 if (II->hasOneUse()) {
12837 // Check if we're grabbing the overflow bit or the result of a 'with
12838 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12839 // and replace it with a traditional binary instruction.
12840 switch (II->getIntrinsicID()) {
12841 case Intrinsic::uadd_with_overflow:
12842 case Intrinsic::sadd_with_overflow:
12843 if (*EV.idx_begin() == 0) { // Normal result.
12844 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12845 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12846 EraseInstFromFunction(*II);
12847 return BinaryOperator::CreateAdd(LHS, RHS);
12848 }
12849 break;
12850 case Intrinsic::usub_with_overflow:
12851 case Intrinsic::ssub_with_overflow:
12852 if (*EV.idx_begin() == 0) { // Normal result.
12853 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12854 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12855 EraseInstFromFunction(*II);
12856 return BinaryOperator::CreateSub(LHS, RHS);
12857 }
12858 break;
12859 case Intrinsic::umul_with_overflow:
12860 case Intrinsic::smul_with_overflow:
12861 if (*EV.idx_begin() == 0) { // Normal result.
12862 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12863 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12864 EraseInstFromFunction(*II);
12865 return BinaryOperator::CreateMul(LHS, RHS);
12866 }
12867 break;
12868 default:
12869 break;
12870 }
12871 }
12872 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012873 // Can't simplify extracts from other values. Note that nested extracts are
12874 // already simplified implicitely by the above (extract ( extract (insert) )
12875 // will be translated into extract ( insert ( extract ) ) first and then just
12876 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012877 return 0;
12878}
12879
Chris Lattner220b0cf2006-03-05 00:22:33 +000012880/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12881/// is to leave as a vector operation.
12882static bool CheapToScalarize(Value *V, bool isConstant) {
12883 if (isa<ConstantAggregateZero>(V))
12884 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012885 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012886 if (isConstant) return true;
12887 // If all elts are the same, we can extract.
12888 Constant *Op0 = C->getOperand(0);
12889 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12890 if (C->getOperand(i) != Op0)
12891 return false;
12892 return true;
12893 }
12894 Instruction *I = dyn_cast<Instruction>(V);
12895 if (!I) return false;
12896
12897 // Insert element gets simplified to the inserted element or is deleted if
12898 // this is constant idx extract element and its a constant idx insertelt.
12899 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12900 isa<ConstantInt>(I->getOperand(2)))
12901 return true;
12902 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12903 return true;
12904 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12905 if (BO->hasOneUse() &&
12906 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12907 CheapToScalarize(BO->getOperand(1), isConstant)))
12908 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012909 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12910 if (CI->hasOneUse() &&
12911 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12912 CheapToScalarize(CI->getOperand(1), isConstant)))
12913 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012914
12915 return false;
12916}
12917
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012918/// Read and decode a shufflevector mask.
12919///
12920/// It turns undef elements into values that are larger than the number of
12921/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012922static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12923 unsigned NElts = SVI->getType()->getNumElements();
12924 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12925 return std::vector<unsigned>(NElts, 0);
12926 if (isa<UndefValue>(SVI->getOperand(2)))
12927 return std::vector<unsigned>(NElts, 2*NElts);
12928
12929 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012930 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012931 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12932 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012933 Result.push_back(NElts*2); // undef -> 8
12934 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012935 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012936 return Result;
12937}
12938
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012939/// FindScalarElement - Given a vector and an element number, see if the scalar
12940/// value is already around as a register, for example if it were inserted then
12941/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012942static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012943 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012944 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12945 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012946 unsigned Width = PTy->getNumElements();
12947 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012948 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012949
12950 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012951 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012952 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012953 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012954 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012955 return CP->getOperand(EltNo);
12956 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12957 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012958 if (!isa<ConstantInt>(III->getOperand(2)))
12959 return 0;
12960 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012961
12962 // If this is an insert to the element we are looking for, return the
12963 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012964 if (EltNo == IIElt)
12965 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012966
12967 // Otherwise, the insertelement doesn't modify the value, recurse on its
12968 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012969 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012970 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012971 unsigned LHSWidth =
12972 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012973 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012974 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012975 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012976 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012977 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012978 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012979 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012980 }
12981
12982 // Otherwise, we don't know.
12983 return 0;
12984}
12985
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012986Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012987 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012988 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012989 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012990
Dan Gohman07a96762007-07-16 14:29:03 +000012991 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012992 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012993 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012994
Reid Spencer9d6565a2007-02-15 02:26:10 +000012995 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012996 // If vector val is constant with all elements the same, replace EI with
12997 // that element. When the elements are not identical, we cannot replace yet
12998 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012999 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000013000 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000013001 if (C->getOperand(i) != op0) {
13002 op0 = 0;
13003 break;
13004 }
13005 if (op0)
13006 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013007 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000013008
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013009 // If extracting a specified index from the vector, see if we can recursively
13010 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000013011 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000013012 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000013013 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000013014
13015 // If this is extracting an invalid index, turn this into undef, to avoid
13016 // crashing the code below.
13017 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013018 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000013019
Chris Lattner867b99f2006-10-05 06:55:50 +000013020 // This instruction only demands the single element from the input vector.
13021 // If the input vector has a single use, simplify it based on this use
13022 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000013023 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000013024 APInt UndefElts(VectorWidth, 0);
13025 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000013026 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000013027 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000013028 EI.setOperand(0, V);
13029 return &EI;
13030 }
13031 }
13032
Owen Andersond672ecb2009-07-03 00:17:18 +000013033 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013034 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013035
13036 // If the this extractelement is directly using a bitcast from a vector of
13037 // the same number of elements, see if we can find the source element from
13038 // it. In this case, we will end up needing to bitcast the scalars.
13039 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
13040 if (const VectorType *VT =
13041 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
13042 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000013043 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
13044 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013045 return new BitCastInst(Elt, EI.getType());
13046 }
Chris Lattner389a6f52006-04-10 23:06:36 +000013047 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013048
Chris Lattner73fa49d2006-05-25 22:53:38 +000013049 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000013050 // Push extractelement into predecessor operation if legal and
13051 // profitable to do so
13052 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
13053 if (I->hasOneUse() &&
13054 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
13055 Value *newEI0 =
13056 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
13057 EI.getName()+".lhs");
13058 Value *newEI1 =
13059 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
13060 EI.getName()+".rhs");
13061 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000013062 }
Chris Lattner275a6d62009-09-08 18:48:01 +000013063 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000013064 // Extracting the inserted element?
13065 if (IE->getOperand(2) == EI.getOperand(1))
13066 return ReplaceInstUsesWith(EI, IE->getOperand(1));
13067 // If the inserted and extracted elements are constants, they must not
13068 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000013069 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000013070 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000013071 EI.setOperand(0, IE->getOperand(0));
13072 return &EI;
13073 }
13074 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
13075 // If this is extracting an element from a shufflevector, figure out where
13076 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000013077 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13078 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000013079 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013080 unsigned LHSWidth =
13081 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13082
13083 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000013084 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000013085 else if (SrcIdx < LHSWidth*2) {
13086 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000013087 Src = SVI->getOperand(1);
13088 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013089 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000013090 }
Eric Christophera3500da2009-07-25 02:28:41 +000013091 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000013092 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
13093 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013094 }
13095 }
Eli Friedman2451a642009-07-18 23:06:53 +000013096 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000013097 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013098 return 0;
13099}
13100
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013101/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
13102/// elements from either LHS or RHS, return the shuffle mask and true.
13103/// Otherwise, return false.
13104static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000013105 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013106 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013107 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
13108 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013109 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013110
13111 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013112 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013113 return true;
13114 } else if (V == LHS) {
13115 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013116 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013117 return true;
13118 } else if (V == RHS) {
13119 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013120 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013121 return true;
13122 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13123 // If this is an insert of an extract from some other vector, include it.
13124 Value *VecOp = IEI->getOperand(0);
13125 Value *ScalarOp = IEI->getOperand(1);
13126 Value *IdxOp = IEI->getOperand(2);
13127
Chris Lattnerd929f062006-04-27 21:14:21 +000013128 if (!isa<ConstantInt>(IdxOp))
13129 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000013130 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000013131
13132 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
13133 // Okay, we can handle this if the vector we are insertinting into is
13134 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000013135 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000013136 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013137 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000013138 return true;
13139 }
13140 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13141 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013142 EI->getOperand(0)->getType() == V->getType()) {
13143 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013144 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013145
13146 // This must be extracting from either LHS or RHS.
13147 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13148 // Okay, we can handle this if the vector we are insertinting into is
13149 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000013150 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013151 // If so, update the mask to reflect the inserted value.
13152 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013153 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013154 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013155 } else {
13156 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013157 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013158 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013159
13160 }
13161 return true;
13162 }
13163 }
13164 }
13165 }
13166 }
13167 // TODO: Handle shufflevector here!
13168
13169 return false;
13170}
13171
13172/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13173/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
13174/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000013175static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013176 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000013177 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013178 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000013179 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013180 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000013181
13182 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013183 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000013184 return V;
13185 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013186 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000013187 return V;
13188 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13189 // If this is an insert of an extract from some other vector, include it.
13190 Value *VecOp = IEI->getOperand(0);
13191 Value *ScalarOp = IEI->getOperand(1);
13192 Value *IdxOp = IEI->getOperand(2);
13193
13194 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13195 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13196 EI->getOperand(0)->getType() == V->getType()) {
13197 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013198 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13199 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013200
13201 // Either the extracted from or inserted into vector must be RHSVec,
13202 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013203 if (EI->getOperand(0) == RHS || RHS == 0) {
13204 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000013205 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013206 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013207 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000013208 return V;
13209 }
13210
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013211 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000013212 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13213 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000013214 // Everything but the extracted element is replaced with the RHS.
13215 for (unsigned i = 0; i != NumElts; ++i) {
13216 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000013217 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000013218 }
13219 return V;
13220 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013221
13222 // If this insertelement is a chain that comes from exactly these two
13223 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000013224 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13225 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013226 return EI->getOperand(0);
13227
Chris Lattnerefb47352006-04-15 01:39:45 +000013228 }
13229 }
13230 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013231 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000013232
13233 // Otherwise, can't do anything fancy. Return an identity vector.
13234 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013235 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000013236 return V;
13237}
13238
13239Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13240 Value *VecOp = IE.getOperand(0);
13241 Value *ScalarOp = IE.getOperand(1);
13242 Value *IdxOp = IE.getOperand(2);
13243
Chris Lattner599ded12007-04-09 01:11:16 +000013244 // Inserting an undef or into an undefined place, remove this.
13245 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13246 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000013247
Chris Lattnerefb47352006-04-15 01:39:45 +000013248 // If the inserted element was extracted from some other vector, and if the
13249 // indexes are constant, try to turn this into a shufflevector operation.
13250 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13251 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13252 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000013253 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000013254 unsigned ExtractedIdx =
13255 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000013256 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013257
13258 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13259 return ReplaceInstUsesWith(IE, VecOp);
13260
13261 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013262 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000013263
13264 // If we are extracting a value from a vector, then inserting it right
13265 // back into the same place, just use the input vector.
13266 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13267 return ReplaceInstUsesWith(IE, VecOp);
13268
Chris Lattnerefb47352006-04-15 01:39:45 +000013269 // If this insertelement isn't used by some other insertelement, turn it
13270 // (and any insertelements it points to), into one big shuffle.
13271 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13272 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013273 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000013274 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013275 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013276 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000013277 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000013278 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000013279 }
13280 }
13281 }
13282
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000013283 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13284 APInt UndefElts(VWidth, 0);
13285 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13286 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13287 return &IE;
13288
Chris Lattnerefb47352006-04-15 01:39:45 +000013289 return 0;
13290}
13291
13292
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013293Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13294 Value *LHS = SVI.getOperand(0);
13295 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000013296 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013297
13298 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013299
Chris Lattner867b99f2006-10-05 06:55:50 +000013300 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000013301 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013302 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000013303
Dan Gohman488fbfc2008-09-09 18:11:14 +000013304 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000013305
13306 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13307 return 0;
13308
Evan Cheng388df622009-02-03 10:05:09 +000013309 APInt UndefElts(VWidth, 0);
13310 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13311 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000013312 LHS = SVI.getOperand(0);
13313 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000013314 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000013315 }
Chris Lattnerefb47352006-04-15 01:39:45 +000013316
Chris Lattner863bcff2006-05-25 23:48:38 +000013317 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13318 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13319 if (LHS == RHS || isa<UndefValue>(LHS)) {
13320 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013321 // shuffle(undef,undef,mask) -> undef.
13322 return ReplaceInstUsesWith(SVI, LHS);
13323 }
13324
Chris Lattner863bcff2006-05-25 23:48:38 +000013325 // Remap any references to RHS to use LHS.
13326 std::vector<Constant*> Elts;
13327 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013328 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000013329 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013330 else {
13331 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000013332 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013333 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013334 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000013335 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013336 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000013337 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000013338 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013339 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013340 }
Chris Lattner863bcff2006-05-25 23:48:38 +000013341 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013342 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000013343 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013344 LHS = SVI.getOperand(0);
13345 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013346 MadeChange = true;
13347 }
13348
Chris Lattner7b2e27922006-05-26 00:29:06 +000013349 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000013350 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000013351
Chris Lattner863bcff2006-05-25 23:48:38 +000013352 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13353 if (Mask[i] >= e*2) continue; // Ignore undef values.
13354 // Is this an identity shuffle of the LHS value?
13355 isLHSID &= (Mask[i] == i);
13356
13357 // Is this an identity shuffle of the RHS value?
13358 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000013359 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013360
Chris Lattner863bcff2006-05-25 23:48:38 +000013361 // Eliminate identity shuffles.
13362 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13363 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013364
Chris Lattner7b2e27922006-05-26 00:29:06 +000013365 // If the LHS is a shufflevector itself, see if we can combine it with this
13366 // one without producing an unusual shuffle. Here we are really conservative:
13367 // we are absolutely afraid of producing a shuffle mask not in the input
13368 // program, because the code gen may not be smart enough to turn a merged
13369 // shuffle into two specific shuffles: it may produce worse code. As such,
13370 // we only merge two shuffles if the result is one of the two input shuffle
13371 // masks. In this case, merging the shuffles just removes one instruction,
13372 // which we know is safe. This is good for things like turning:
13373 // (splat(splat)) -> splat.
13374 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13375 if (isa<UndefValue>(RHS)) {
13376 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13377
David Greenef941d292009-11-16 21:52:23 +000013378 if (LHSMask.size() == Mask.size()) {
13379 std::vector<unsigned> NewMask;
13380 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sands76700ba2009-11-20 13:19:51 +000013381 if (Mask[i] >= e)
David Greenef941d292009-11-16 21:52:23 +000013382 NewMask.push_back(2*e);
13383 else
13384 NewMask.push_back(LHSMask[Mask[i]]);
Chris Lattner7b2e27922006-05-26 00:29:06 +000013385
David Greenef941d292009-11-16 21:52:23 +000013386 // If the result mask is equal to the src shuffle or this
13387 // shuffle mask, do the replacement.
13388 if (NewMask == LHSMask || NewMask == Mask) {
13389 unsigned LHSInNElts =
13390 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13391 getNumElements();
13392 std::vector<Constant*> Elts;
13393 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13394 if (NewMask[i] >= LHSInNElts*2) {
13395 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13396 } else {
13397 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13398 NewMask[i]));
13399 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013400 }
David Greenef941d292009-11-16 21:52:23 +000013401 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13402 LHSSVI->getOperand(1),
13403 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013404 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013405 }
13406 }
13407 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000013408
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013409 return MadeChange ? &SVI : 0;
13410}
13411
13412
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013413
Chris Lattnerea1c4542004-12-08 23:43:58 +000013414
13415/// TryToSinkInstruction - Try to move the specified instruction from its
13416/// current block into the beginning of DestBlock, which can only happen if it's
13417/// safe to move the instruction past all of the instructions between it and the
13418/// end of its block.
13419static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13420 assert(I->hasOneUse() && "Invariants didn't hold!");
13421
Chris Lattner108e9022005-10-27 17:13:11 +000013422 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000013423 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000013424 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000013425
Chris Lattnerea1c4542004-12-08 23:43:58 +000013426 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000013427 if (isa<AllocaInst>(I) && I->getParent() ==
13428 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013429 return false;
13430
Chris Lattner96a52a62004-12-09 07:14:34 +000013431 // We can only sink load instructions if there is nothing between the load and
13432 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000013433 if (I->mayReadFromMemory()) {
13434 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000013435 Scan != E; ++Scan)
13436 if (Scan->mayWriteToMemory())
13437 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000013438 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000013439
Dan Gohman02dea8b2008-05-23 21:05:58 +000013440 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000013441
Dale Johannesenbd8e6502009-03-03 01:09:07 +000013442 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000013443 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013444 ++NumSunkInst;
13445 return true;
13446}
13447
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013448
13449/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13450/// all reachable code to the worklist.
13451///
13452/// This has a couple of tricks to make the code faster and more powerful. In
13453/// particular, we constant fold and DCE instructions as we go, to avoid adding
13454/// them to the worklist (this significantly speeds up instcombine on code where
13455/// many instructions are dead or constant). Additionally, if we find a branch
13456/// whose condition is a known constant, we only visit the reachable successors.
13457///
Chris Lattner2ee743b2009-10-15 04:59:28 +000013458static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000013459 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000013460 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013461 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000013462 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000013463 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000013464 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000013465
13466 std::vector<Instruction*> InstrsForInstCombineWorklist;
13467 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013468
Chris Lattner2ee743b2009-10-15 04:59:28 +000013469 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13470
Chris Lattner2c7718a2007-03-23 19:17:18 +000013471 while (!Worklist.empty()) {
13472 BB = Worklist.back();
13473 Worklist.pop_back();
13474
13475 // We have now visited this block! If we've already been here, ignore it.
13476 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000013477
Chris Lattner2c7718a2007-03-23 19:17:18 +000013478 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13479 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013480
Chris Lattner2c7718a2007-03-23 19:17:18 +000013481 // DCE instruction if trivially dead.
13482 if (isInstructionTriviallyDead(Inst)) {
13483 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000013484 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000013485 Inst->eraseFromParent();
13486 continue;
13487 }
13488
13489 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013490 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013491 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013492 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13493 << *Inst << '\n');
13494 Inst->replaceAllUsesWith(C);
13495 ++NumConstProp;
13496 Inst->eraseFromParent();
13497 continue;
13498 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000013499
13500
13501
13502 if (TD) {
13503 // See if we can constant fold its operands.
13504 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13505 i != e; ++i) {
13506 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13507 if (CE == 0) continue;
13508
13509 // If we already folded this constant, don't try again.
13510 if (!FoldedConstants.insert(CE))
13511 continue;
13512
Chris Lattner7b550cc2009-11-06 04:27:31 +000013513 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000013514 if (NewC && NewC != CE) {
13515 *i = NewC;
13516 MadeIRChange = true;
13517 }
13518 }
13519 }
13520
Devang Patel7fe1dec2008-11-19 18:56:50 +000013521
Chris Lattner67f7d542009-10-12 03:58:40 +000013522 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013523 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000013524
13525 // Recursively visit successors. If this is a branch or switch on a
13526 // constant, only visit the reachable successor.
13527 TerminatorInst *TI = BB->getTerminator();
13528 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13529 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13530 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000013531 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013532 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013533 continue;
13534 }
13535 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13536 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13537 // See if this is an explicit destination.
13538 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13539 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000013540 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013541 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013542 continue;
13543 }
13544
13545 // Otherwise it is the default destination.
13546 Worklist.push_back(SI->getSuccessor(0));
13547 continue;
13548 }
13549 }
13550
13551 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13552 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013553 }
Chris Lattner67f7d542009-10-12 03:58:40 +000013554
13555 // Once we've found all of the instructions to add to instcombine's worklist,
13556 // add them in reverse order. This way instcombine will visit from the top
13557 // of the function down. This jives well with the way that it adds all uses
13558 // of instructions to the worklist after doing a transformation, thus avoiding
13559 // some N^2 behavior in pathological cases.
13560 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13561 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000013562
13563 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013564}
13565
Chris Lattnerec9c3582007-03-03 02:04:50 +000013566bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013567 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013568
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000013569 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13570 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000013571
Chris Lattnerb3d59702005-07-07 20:40:38 +000013572 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013573 // Do a depth-first traversal of the function, populate the worklist with
13574 // the reachable instructions. Ignore blocks that are not reachable. Keep
13575 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000013576 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000013577 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000013578
Chris Lattnerb3d59702005-07-07 20:40:38 +000013579 // Do a quick scan over the function. If we find any blocks that are
13580 // unreachable, remove any instructions inside of them. This prevents
13581 // the instcombine code from having to deal with some bad special cases.
13582 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13583 if (!Visited.count(BB)) {
13584 Instruction *Term = BB->getTerminator();
13585 while (Term != BB->begin()) { // Remove instrs bottom-up
13586 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000013587
Chris Lattnerbdff5482009-08-23 04:37:46 +000013588 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000013589 // A debug intrinsic shouldn't force another iteration if we weren't
13590 // going to do one without it.
13591 if (!isa<DbgInfoIntrinsic>(I)) {
13592 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013593 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000013594 }
Devang Patel228ebd02009-10-13 22:56:32 +000013595
Devang Patel228ebd02009-10-13 22:56:32 +000013596 // If I is not void type then replaceAllUsesWith undef.
13597 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000013598 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000013599 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013600 I->eraseFromParent();
13601 }
13602 }
13603 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013604
Chris Lattner873ff012009-08-30 05:55:36 +000013605 while (!Worklist.isEmpty()) {
13606 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013607 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013608
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013609 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013610 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013611 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000013612 EraseInstFromFunction(*I);
13613 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013614 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013615 continue;
13616 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013617
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013618 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013619 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013620 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013621 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000013622
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013623 // Add operands to the worklist.
13624 ReplaceInstUsesWith(*I, C);
13625 ++NumConstProp;
13626 EraseInstFromFunction(*I);
13627 MadeIRChange = true;
13628 continue;
13629 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013630
Chris Lattnerea1c4542004-12-08 23:43:58 +000013631 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013632 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013633 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000013634 Instruction *UserInst = cast<Instruction>(I->use_back());
13635 BasicBlock *UserParent;
13636
13637 // Get the block the use occurs in.
13638 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13639 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13640 else
13641 UserParent = UserInst->getParent();
13642
Chris Lattnerea1c4542004-12-08 23:43:58 +000013643 if (UserParent != BB) {
13644 bool UserIsSuccessor = false;
13645 // See if the user is one of our successors.
13646 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13647 if (*SI == UserParent) {
13648 UserIsSuccessor = true;
13649 break;
13650 }
13651
13652 // If the user is one of our immediate successors, and if that successor
13653 // only has us as a predecessors (we'd have to split the critical edge
13654 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000013655 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013656 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013657 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013658 }
13659 }
13660
Chris Lattner74381062009-08-30 07:44:24 +000013661 // Now that we have an instruction, try combining it to simplify it.
13662 Builder->SetInsertPoint(I->getParent(), I);
13663
Reid Spencera9b81012007-03-26 17:44:01 +000013664#ifndef NDEBUG
13665 std::string OrigI;
13666#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013667 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000013668 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13669
Chris Lattner90ac28c2002-08-02 19:29:35 +000013670 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013671 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013672 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013673 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013674 DEBUG(errs() << "IC: Old = " << *I << '\n'
13675 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013676
Chris Lattnerf523d062004-06-09 05:08:07 +000013677 // Everything uses the new instruction now.
13678 I->replaceAllUsesWith(Result);
13679
13680 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013681 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013682 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013683
Chris Lattner6934a042007-02-11 01:23:03 +000013684 // Move the name to the new instruction first.
13685 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013686
13687 // Insert the new instruction into the basic block...
13688 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013689 BasicBlock::iterator InsertPos = I;
13690
13691 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13692 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13693 ++InsertPos;
13694
13695 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013696
Chris Lattner7a1e9242009-08-30 06:13:40 +000013697 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013698 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013699#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013700 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13701 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013702#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013703
Chris Lattner90ac28c2002-08-02 19:29:35 +000013704 // If the instruction was modified, it's possible that it is now dead.
13705 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013706 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013707 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013708 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013709 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013710 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013711 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013712 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013713 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013714 }
13715 }
13716
Chris Lattner873ff012009-08-30 05:55:36 +000013717 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013718 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013719}
13720
Chris Lattnerec9c3582007-03-03 02:04:50 +000013721
13722bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013723 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013724 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013725 TD = getAnalysisIfAvailable<TargetData>();
13726
Chris Lattner74381062009-08-30 07:44:24 +000013727
13728 /// Builder - This is an IRBuilder that automatically inserts new
13729 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013730 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000013731 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000013732 InstCombineIRInserter(Worklist));
13733 Builder = &TheBuilder;
13734
Chris Lattnerec9c3582007-03-03 02:04:50 +000013735 bool EverMadeChange = false;
13736
13737 // Iterate while there is work to do.
13738 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013739 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013740 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000013741
13742 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013743 return EverMadeChange;
13744}
13745
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013746FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013747 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013748}