blob: 64f99e34c2946c5e2dd19202b46a8721b230d01b [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 Lattner173234a2008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000051#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000054#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000055#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000056#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000057#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000058#include "llvm/Support/Compiler.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000059#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000060#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000061#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000062#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000063#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000064#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000065#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000066#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000067using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000068using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000075
Chris Lattner0e5f4992006-12-19 21:40:18 +000076namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000077 /// InstCombineWorklist - This is the worklist management logic for
78 /// InstCombine.
79 class InstCombineWorklist {
80 SmallVector<Instruction*, 256> Worklist;
81 DenseMap<Instruction*, unsigned> WorklistMap;
82
83 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
84 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85 public:
86 InstCombineWorklist() {}
87
88 bool isEmpty() const { return Worklist.empty(); }
89
90 /// Add - Add the specified instruction to the worklist if it isn't already
91 /// in it.
92 void Add(Instruction *I) {
93 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94 Worklist.push_back(I);
95 }
96
Chris Lattner3c4e38e2009-08-30 06:27:41 +000097 void AddValue(Value *V) {
98 if (Instruction *I = dyn_cast<Instruction>(V))
99 Add(I);
100 }
101
Chris Lattner7a1e9242009-08-30 06:13:40 +0000102 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000103 void Remove(Instruction *I) {
104 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
105 if (It == WorklistMap.end()) return; // Not in worklist.
106
107 // Don't bother moving everything down, just null out the slot.
108 Worklist[It->second] = 0;
109
110 WorklistMap.erase(It);
111 }
112
113 Instruction *RemoveOne() {
114 Instruction *I = Worklist.back();
115 Worklist.pop_back();
116 WorklistMap.erase(I);
117 return I;
118 }
119
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000120 /// AddUsersToWorkList - When an instruction is simplified, add all users of
121 /// the instruction to the work lists because they might get more simplified
122 /// now.
123 ///
124 void AddUsersToWorkList(Instruction &I) {
125 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
126 UI != UE; ++UI)
127 Add(cast<Instruction>(*UI));
128 }
129
Chris Lattner873ff012009-08-30 05:55:36 +0000130
131 /// Zap - check that the worklist is empty and nuke the backing store for
132 /// the map if it is large.
133 void Zap() {
134 assert(WorklistMap.empty() && "Worklist empty, but map not?");
135
136 // Do an explicit clear, this shrinks the map if needed.
137 WorklistMap.clear();
138 }
139 };
140} // end anonymous namespace.
141
142
143namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000144 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
145 /// just like the normal insertion helper, but also adds any new instructions
146 /// to the instcombine worklist.
147 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
148 InstCombineWorklist &Worklist;
149 public:
150 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
151
152 void InsertHelper(Instruction *I, const Twine &Name,
153 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
154 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
155 Worklist.Add(I);
156 }
157 };
158} // end anonymous namespace
159
160
161namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +0000162 class VISIBILITY_HIDDEN InstCombiner
163 : public FunctionPass,
164 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000165 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000166 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000167 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000168 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000169 InstCombineWorklist Worklist;
170
Chris Lattner74381062009-08-30 07:44:24 +0000171 /// Builder - This is an IRBuilder that automatically inserts new
172 /// instructions into the worklist when they are created.
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000173 typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
174 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000175
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000176 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000177 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000178
Owen Andersone922c022009-07-22 00:24:57 +0000179 LLVMContext *Context;
180 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000181
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000182 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000183 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000184
185 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000186
Chris Lattner97e52e42002-04-28 21:27:06 +0000187 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000188 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000189 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000190 }
191
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000192 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000193
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000194 // Visitation implementation - Implement instruction combining for different
195 // instruction types. The semantics are as follows:
196 // Return Value:
197 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000198 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000199 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000200 //
Chris Lattner7e708292002-06-25 16:13:24 +0000201 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000202 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000203 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000204 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000205 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000206 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000207 Instruction *visitURem(BinaryOperator &I);
208 Instruction *visitSRem(BinaryOperator &I);
209 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000210 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000211 Instruction *commonRemTransforms(BinaryOperator &I);
212 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000213 Instruction *commonDivTransforms(BinaryOperator &I);
214 Instruction *commonIDivTransforms(BinaryOperator &I);
215 Instruction *visitUDiv(BinaryOperator &I);
216 Instruction *visitSDiv(BinaryOperator &I);
217 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000218 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000219 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000220 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000221 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000222 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000223 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000224 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000225 Instruction *visitOr (BinaryOperator &I);
226 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000227 Instruction *visitShl(BinaryOperator &I);
228 Instruction *visitAShr(BinaryOperator &I);
229 Instruction *visitLShr(BinaryOperator &I);
230 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000231 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
232 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000233 Instruction *visitFCmpInst(FCmpInst &I);
234 Instruction *visitICmpInst(ICmpInst &I);
235 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000236 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
237 Instruction *LHS,
238 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000239 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
240 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000241
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000242 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000243 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000244 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000245 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000246 Instruction *commonCastTransforms(CastInst &CI);
247 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000248 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000249 Instruction *visitTrunc(TruncInst &CI);
250 Instruction *visitZExt(ZExtInst &CI);
251 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000252 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000253 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000254 Instruction *visitFPToUI(FPToUIInst &FI);
255 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000256 Instruction *visitUIToFP(CastInst &CI);
257 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000258 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000259 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000260 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000261 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
262 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000263 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000264 Instruction *visitSelectInst(SelectInst &SI);
265 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000266 Instruction *visitCallInst(CallInst &CI);
267 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000268 Instruction *visitPHINode(PHINode &PN);
269 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000270 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000271 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000272 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000273 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000274 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000275 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000276 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000277 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000278 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000279 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000280
281 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000282 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000283
Chris Lattner9fe38862003-06-19 17:00:31 +0000284 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000285 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000286 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000287 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000288 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
289 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000290 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000291 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
292
Chris Lattner9fe38862003-06-19 17:00:31 +0000293
Chris Lattner28977af2004-04-05 01:30:19 +0000294 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000295 // InsertNewInstBefore - insert an instruction New before instruction Old
296 // in the program. Add the new instruction to the worklist.
297 //
Chris Lattner955f3312004-09-28 21:48:02 +0000298 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000299 assert(New && New->getParent() == 0 &&
300 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000301 BasicBlock *BB = Old.getParent();
302 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000303 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000304 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000305 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000306
Chris Lattner8b170942002-08-09 23:47:40 +0000307 // ReplaceInstUsesWith - This method is to be used when an instruction is
308 // found to be dead, replacable with another preexisting expression. Here
309 // we add all uses of I to the worklist, replace all uses of I with the new
310 // value, then return I, so that the inst combiner will know that I was
311 // modified.
312 //
313 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000314 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000315
316 // If we are replacing the instruction with itself, this must be in a
317 // segment of unreachable code, so just clobber the instruction.
318 if (&I == V)
319 V = UndefValue::get(I.getType());
320
321 I.replaceAllUsesWith(V);
322 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000323 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000324
325 // EraseInstFromFunction - When dealing with an instruction that has side
326 // effects or produces a void value, we can't rely on DCE to delete the
327 // instruction. Instead, visit methods should return the value returned by
328 // this function.
329 Instruction *EraseInstFromFunction(Instruction &I) {
330 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000331 // Make sure that we reprocess all operands now that we reduced their
332 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000333 if (I.getNumOperands() < 8) {
334 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
335 if (Instruction *Op = dyn_cast<Instruction>(*i))
336 Worklist.Add(Op);
337 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000338 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000339 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000340 return 0; // Don't do anything with FI
341 }
Chris Lattner173234a2008-06-02 01:18:21 +0000342
343 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
344 APInt &KnownOne, unsigned Depth = 0) const {
345 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
346 }
347
348 bool MaskedValueIsZero(Value *V, const APInt &Mask,
349 unsigned Depth = 0) const {
350 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
351 }
352 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
353 return llvm::ComputeNumSignBits(Op, TD, Depth);
354 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000355
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000356 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000357
Reid Spencere4d87aa2006-12-23 06:05:41 +0000358 /// SimplifyCommutative - This performs a few simplifications for
359 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000360 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000361
Reid Spencere4d87aa2006-12-23 06:05:41 +0000362 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
363 /// most-complex to least-complex order.
364 bool SimplifyCompare(CmpInst &I);
365
Chris Lattner886ab6c2009-01-31 08:15:18 +0000366 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
367 /// based on the demanded bits.
368 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
369 APInt& KnownZero, APInt& KnownOne,
370 unsigned Depth);
371 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000372 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000373 unsigned Depth=0);
374
375 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
376 /// SimplifyDemandedBits knows about. See if the instruction has any
377 /// properties that allow us to simplify its operands.
378 bool SimplifyDemandedInstructionBits(Instruction &Inst);
379
Evan Cheng388df622009-02-03 10:05:09 +0000380 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
381 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000382
Chris Lattner4e998b22004-09-29 05:07:12 +0000383 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
384 // PHI node as operand #0, see if we can fold the instruction into the PHI
385 // (which is only possible if all operands to the PHI are constants).
386 Instruction *FoldOpIntoPhi(Instruction &I);
387
Chris Lattnerbac32862004-11-14 19:13:23 +0000388 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
389 // operator and they all are only used by the PHI, PHI together their
390 // inputs, and do the operation once, to the result of the PHI.
391 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000392 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000393 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
394
Chris Lattner7da52b22006-11-01 04:51:18 +0000395
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000396 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
397 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000398
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000399 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000400 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000401 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000402 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000403 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000404 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000405 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000406 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000407 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000408
Chris Lattnerafe91a52006-06-15 19:07:26 +0000409
Reid Spencerc55b2432006-12-13 18:21:21 +0000410 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000411
Dan Gohman6de29f82009-06-15 22:12:54 +0000412 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000413 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000414 unsigned GetOrEnforceKnownAlignment(Value *V,
415 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000416
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000417 };
Chris Lattner873ff012009-08-30 05:55:36 +0000418} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000419
Dan Gohman844731a2008-05-13 00:00:25 +0000420char InstCombiner::ID = 0;
421static RegisterPass<InstCombiner>
422X("instcombine", "Combine redundant instructions");
423
Chris Lattner4f98c562003-03-10 21:43:22 +0000424// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000425// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000426static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000427 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000428 if (BinaryOperator::isNeg(V) ||
429 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000430 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000431 return 3;
432 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000433 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000434 if (isa<Argument>(V)) return 3;
435 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000436}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000437
Chris Lattnerc8802d22003-03-11 00:12:48 +0000438// isOnlyUse - Return true if this instruction will be deleted if we stop using
439// it.
440static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000441 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000442}
443
Chris Lattner4cb170c2004-02-23 06:38:22 +0000444// getPromotedType - Return the specified type promoted as it would be to pass
445// though a va_arg area...
446static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000447 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
448 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000449 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000450 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000451 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000452}
453
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000454/// getBitCastOperand - If the specified operand is a CastInst, a constant
455/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
456/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000457static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000458 if (Operator *O = dyn_cast<Operator>(V)) {
459 if (O->getOpcode() == Instruction::BitCast)
460 return O->getOperand(0);
461 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
462 if (GEP->hasAllZeroIndices())
463 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000464 }
Chris Lattnereed48272005-09-13 00:40:14 +0000465 return 0;
466}
467
Reid Spencer3da59db2006-11-27 01:05:10 +0000468/// This function is a wrapper around CastInst::isEliminableCastPair. It
469/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000470static Instruction::CastOps
471isEliminableCastPair(
472 const CastInst *CI, ///< The first cast instruction
473 unsigned opcode, ///< The opcode of the second cast instruction
474 const Type *DstTy, ///< The target type for the second cast instruction
475 TargetData *TD ///< The target data for pointer size
476) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000477
Reid Spencer3da59db2006-11-27 01:05:10 +0000478 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
479 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000480
Reid Spencer3da59db2006-11-27 01:05:10 +0000481 // Get the opcodes of the two Cast instructions
482 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
483 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000484
Chris Lattnera0e69692009-03-24 18:35:40 +0000485 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000486 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000487 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000488
489 // We don't want to form an inttoptr or ptrtoint that converts to an integer
490 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000491 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000492 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000493 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000494 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000495 Res = 0;
496
497 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000498}
499
500/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
501/// in any code being generated. It does not require codegen if V is simple
502/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000503static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
504 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000505 if (V->getType() == Ty || isa<Constant>(V)) return false;
506
Chris Lattner01575b72006-05-25 23:24:33 +0000507 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000508 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000509 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000510 return false;
511 return true;
512}
513
Chris Lattner4f98c562003-03-10 21:43:22 +0000514// SimplifyCommutative - This performs a few simplifications for commutative
515// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000516//
Chris Lattner4f98c562003-03-10 21:43:22 +0000517// 1. Order operands such that they are listed from right (least complex) to
518// left (most complex). This puts constants before unary operators before
519// binary operators.
520//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
522// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000523//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000524bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000525 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000526 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000527 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000528
Chris Lattner4f98c562003-03-10 21:43:22 +0000529 if (!I.isAssociative()) return Changed;
530 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000531 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
532 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
533 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000534 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000535 cast<Constant>(I.getOperand(1)),
536 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000537 I.setOperand(0, Op->getOperand(0));
538 I.setOperand(1, Folded);
539 return true;
540 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
541 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
542 isOnlyUse(Op) && isOnlyUse(Op1)) {
543 Constant *C1 = cast<Constant>(Op->getOperand(1));
544 Constant *C2 = cast<Constant>(Op1->getOperand(1));
545
546 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000547 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000548 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000549 Op1->getOperand(0),
550 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000551 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000552 I.setOperand(0, New);
553 I.setOperand(1, Folded);
554 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000555 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000556 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000557 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000558}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000559
Reid Spencere4d87aa2006-12-23 06:05:41 +0000560/// SimplifyCompare - For a CmpInst this function just orders the operands
561/// so that theyare listed from right (least complex) to left (most complex).
562/// This puts constants before unary operators before binary operators.
563bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000564 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000565 return false;
566 I.swapOperands();
567 // Compare instructions are not associative so there's nothing else we can do.
568 return true;
569}
570
Chris Lattner8d969642003-03-10 23:06:50 +0000571// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
572// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000573//
Dan Gohman186a6362009-08-12 16:04:34 +0000574static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000575 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000576 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000577
Chris Lattner0ce85802004-12-14 20:08:06 +0000578 // Constants can be considered to be negated values if they can be folded.
579 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000580 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000581
582 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
583 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000584 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000585
Chris Lattner8d969642003-03-10 23:06:50 +0000586 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000587}
588
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000589// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
590// instruction if the LHS is a constant negative zero (which is the 'negate'
591// form).
592//
Dan Gohman186a6362009-08-12 16:04:34 +0000593static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000594 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000595 return BinaryOperator::getFNegArgument(V);
596
597 // Constants can be considered to be negated values if they can be folded.
598 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000599 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000600
601 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
602 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000603 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000604
605 return 0;
606}
607
Dan Gohman186a6362009-08-12 16:04:34 +0000608static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000609 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000610 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000611
612 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000613 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000614 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000615 return 0;
616}
617
Chris Lattnerc8802d22003-03-11 00:12:48 +0000618// dyn_castFoldableMul - If this value is a multiply that can be folded into
619// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000620// non-constant operand of the multiply, and set CST to point to the multiplier.
621// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000622//
Dan Gohman186a6362009-08-12 16:04:34 +0000623static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000624 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000625 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000626 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000627 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000628 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000629 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000630 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000631 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000632 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000633 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000634 CST = ConstantInt::get(V->getType()->getContext(),
635 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000636 return I->getOperand(0);
637 }
638 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000639 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000640}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000641
Reid Spencer7177c3a2007-03-25 05:33:51 +0000642/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000643static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000644 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000645 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000646}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000647/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000648static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000649 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000650 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000651}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000652/// MultiplyOverflows - True if the multiply can not be expressed in an int
653/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000654static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000655 uint32_t W = C1->getBitWidth();
656 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
657 if (sign) {
658 LHSExt.sext(W * 2);
659 RHSExt.sext(W * 2);
660 } else {
661 LHSExt.zext(W * 2);
662 RHSExt.zext(W * 2);
663 }
664
665 APInt MulExt = LHSExt * RHSExt;
666
667 if (sign) {
668 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
669 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
670 return MulExt.slt(Min) || MulExt.sgt(Max);
671 } else
672 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
673}
Chris Lattner955f3312004-09-28 21:48:02 +0000674
Reid Spencere7816b52007-03-08 01:52:58 +0000675
Chris Lattner255d8912006-02-11 09:31:47 +0000676/// ShrinkDemandedConstant - Check to see if the specified operand of the
677/// specified instruction is a constant integer. If so, check to see if there
678/// are any bits set in the constant that are not demanded. If so, shrink the
679/// constant and return true.
680static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000681 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000682 assert(I && "No instruction?");
683 assert(OpNo < I->getNumOperands() && "Operand index too large");
684
685 // If the operand is not a constant integer, nothing to do.
686 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
687 if (!OpC) return false;
688
689 // If there are no bits set that aren't demanded, nothing to do.
690 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
691 if ((~Demanded & OpC->getValue()) == 0)
692 return false;
693
694 // This instruction is producing bits that are not demanded. Shrink the RHS.
695 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000696 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000697 return true;
698}
699
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000700// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
701// set of known zero and one bits, compute the maximum and minimum values that
702// could have the specified known zero and known one bits, returning them in
703// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000704static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000705 const APInt& KnownOne,
706 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000707 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
708 KnownZero.getBitWidth() == Min.getBitWidth() &&
709 KnownZero.getBitWidth() == Max.getBitWidth() &&
710 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000711 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000712
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000713 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
714 // bit if it is unknown.
715 Min = KnownOne;
716 Max = KnownOne|UnknownBits;
717
Dan Gohman1c8491e2009-04-25 17:12:48 +0000718 if (UnknownBits.isNegative()) { // Sign bit is unknown
719 Min.set(Min.getBitWidth()-1);
720 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000721 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000722}
723
724// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
725// a set of known zero and one bits, compute the maximum and minimum values that
726// could have the specified known zero and known one bits, returning them in
727// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000728static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000729 const APInt &KnownOne,
730 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000731 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
732 KnownZero.getBitWidth() == Min.getBitWidth() &&
733 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000734 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000735 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000736
737 // The minimum value is when the unknown bits are all zeros.
738 Min = KnownOne;
739 // The maximum value is when the unknown bits are all ones.
740 Max = KnownOne|UnknownBits;
741}
Chris Lattner255d8912006-02-11 09:31:47 +0000742
Chris Lattner886ab6c2009-01-31 08:15:18 +0000743/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
744/// SimplifyDemandedBits knows about. See if the instruction has any
745/// properties that allow us to simplify its operands.
746bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000747 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000748 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
749 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
750
751 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
752 KnownZero, KnownOne, 0);
753 if (V == 0) return false;
754 if (V == &Inst) return true;
755 ReplaceInstUsesWith(Inst, V);
756 return true;
757}
758
759/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
760/// specified instruction operand if possible, updating it in place. It returns
761/// true if it made any change and false otherwise.
762bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
763 APInt &KnownZero, APInt &KnownOne,
764 unsigned Depth) {
765 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
766 KnownZero, KnownOne, Depth);
767 if (NewVal == 0) return false;
768 U.set(NewVal);
769 return true;
770}
771
772
773/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
774/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000775/// that only the bits set in DemandedMask of the result of V are ever used
776/// downstream. Consequently, depending on the mask and V, it may be possible
777/// to replace V with a constant or one of its operands. In such cases, this
778/// function does the replacement and returns true. In all other cases, it
779/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000780/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000781/// to be zero in the expression. These are provided to potentially allow the
782/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
783/// the expression. KnownOne and KnownZero always follow the invariant that
784/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
785/// the bits in KnownOne and KnownZero may only be accurate for those bits set
786/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
787/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000788///
789/// This returns null if it did not change anything and it permits no
790/// simplification. This returns V itself if it did some simplification of V's
791/// operands based on the information about what bits are demanded. This returns
792/// some other non-null value if it found out that V is equal to another value
793/// in the context where the specified bits are demanded, but not for all users.
794Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
795 APInt &KnownZero, APInt &KnownOne,
796 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000797 assert(V != 0 && "Null pointer of Value???");
798 assert(Depth <= 6 && "Limit Search Depth");
799 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000800 const Type *VTy = V->getType();
801 assert((TD || !isa<PointerType>(VTy)) &&
802 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000803 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
804 (!VTy->isIntOrIntVector() ||
805 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000806 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000807 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000808 "Value *V, DemandedMask, KnownZero and KnownOne "
809 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000810 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
811 // We know all of the bits for a constant!
812 KnownOne = CI->getValue() & DemandedMask;
813 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000814 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000815 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000816 if (isa<ConstantPointerNull>(V)) {
817 // We know all of the bits for a constant!
818 KnownOne.clear();
819 KnownZero = DemandedMask;
820 return 0;
821 }
822
Chris Lattner08d2cc72009-01-31 07:26:06 +0000823 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000824 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000825 if (DemandedMask == 0) { // Not demanding any bits from V.
826 if (isa<UndefValue>(V))
827 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000828 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000829 }
830
Chris Lattner4598c942009-01-31 08:24:16 +0000831 if (Depth == 6) // Limit search depth.
832 return 0;
833
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000834 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
835 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
836
Dan Gohman1c8491e2009-04-25 17:12:48 +0000837 Instruction *I = dyn_cast<Instruction>(V);
838 if (!I) {
839 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
840 return 0; // Only analyze instructions.
841 }
842
Chris Lattner4598c942009-01-31 08:24:16 +0000843 // If there are multiple uses of this value and we aren't at the root, then
844 // we can't do any simplifications of the operands, because DemandedMask
845 // only reflects the bits demanded by *one* of the users.
846 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000847 // Despite the fact that we can't simplify this instruction in all User's
848 // context, we can at least compute the knownzero/knownone bits, and we can
849 // do simplifications that apply to *just* the one user if we know that
850 // this instruction has a simpler value in that context.
851 if (I->getOpcode() == Instruction::And) {
852 // If either the LHS or the RHS are Zero, the result is zero.
853 ComputeMaskedBits(I->getOperand(1), DemandedMask,
854 RHSKnownZero, RHSKnownOne, Depth+1);
855 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
856 LHSKnownZero, LHSKnownOne, Depth+1);
857
858 // If all of the demanded bits are known 1 on one side, return the other.
859 // These bits cannot contribute to the result of the 'and' in this
860 // context.
861 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
862 (DemandedMask & ~LHSKnownZero))
863 return I->getOperand(0);
864 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
865 (DemandedMask & ~RHSKnownZero))
866 return I->getOperand(1);
867
868 // If all of the demanded bits in the inputs are known zeros, return zero.
869 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000870 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000871
872 } else if (I->getOpcode() == Instruction::Or) {
873 // We can simplify (X|Y) -> X or Y in the user's context if we know that
874 // only bits from X or Y are demanded.
875
876 // If either the LHS or the RHS are One, the result is One.
877 ComputeMaskedBits(I->getOperand(1), DemandedMask,
878 RHSKnownZero, RHSKnownOne, Depth+1);
879 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
880 LHSKnownZero, LHSKnownOne, Depth+1);
881
882 // If all of the demanded bits are known zero on one side, return the
883 // other. These bits cannot contribute to the result of the 'or' in this
884 // context.
885 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
886 (DemandedMask & ~LHSKnownOne))
887 return I->getOperand(0);
888 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
889 (DemandedMask & ~RHSKnownOne))
890 return I->getOperand(1);
891
892 // If all of the potentially set bits on one side are known to be set on
893 // the other side, just use the 'other' side.
894 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
895 (DemandedMask & (~RHSKnownZero)))
896 return I->getOperand(0);
897 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
898 (DemandedMask & (~LHSKnownZero)))
899 return I->getOperand(1);
900 }
901
Chris Lattner4598c942009-01-31 08:24:16 +0000902 // Compute the KnownZero/KnownOne bits to simplify things downstream.
903 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
904 return 0;
905 }
906
907 // If this is the root being simplified, allow it to have multiple uses,
908 // just set the DemandedMask to all bits so that we can try to simplify the
909 // operands. This allows visitTruncInst (for example) to simplify the
910 // operand of a trunc without duplicating all the logic below.
911 if (Depth == 0 && !V->hasOneUse())
912 DemandedMask = APInt::getAllOnesValue(BitWidth);
913
Reid Spencer8cb68342007-03-12 17:25:59 +0000914 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000915 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000916 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000917 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000918 case Instruction::And:
919 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000920 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
921 RHSKnownZero, RHSKnownOne, Depth+1) ||
922 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000923 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000924 return I;
925 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
926 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000927
928 // If all of the demanded bits are known 1 on one side, return the other.
929 // These bits cannot contribute to the result of the 'and'.
930 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
931 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000932 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000933 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
934 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000935 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000936
937 // If all of the demanded bits in the inputs are known zeros, return zero.
938 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000939 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000940
941 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000942 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000943 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000944
945 // Output known-1 bits are only known if set in both the LHS & RHS.
946 RHSKnownOne &= LHSKnownOne;
947 // Output known-0 are known to be clear if zero in either the LHS | RHS.
948 RHSKnownZero |= LHSKnownZero;
949 break;
950 case Instruction::Or:
951 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000952 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
953 RHSKnownZero, RHSKnownOne, Depth+1) ||
954 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000955 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000956 return I;
957 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
958 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000959
960 // If all of the demanded bits are known zero on one side, return the other.
961 // These bits cannot contribute to the result of the 'or'.
962 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
963 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000964 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000965 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
966 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000967 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000968
969 // If all of the potentially set bits on one side are known to be set on
970 // the other side, just use the 'other' side.
971 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
972 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000973 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000974 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
975 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000977
978 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000979 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000980 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000981
982 // Output known-0 bits are only known if clear in both the LHS & RHS.
983 RHSKnownZero &= LHSKnownZero;
984 // Output known-1 are known to be set if set in either the LHS | RHS.
985 RHSKnownOne |= LHSKnownOne;
986 break;
987 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
989 RHSKnownZero, RHSKnownOne, Depth+1) ||
990 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000991 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000992 return I;
993 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
994 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000995
996 // If all of the demanded bits are known zero on one side, return the other.
997 // These bits cannot contribute to the result of the 'xor'.
998 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000999 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001000 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001001 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001002
1003 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1004 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1005 (RHSKnownOne & LHSKnownOne);
1006 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1007 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1008 (RHSKnownOne & LHSKnownZero);
1009
1010 // If all of the demanded bits are known to be zero on one side or the
1011 // other, turn this into an *inclusive* or.
1012 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001013 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1014 Instruction *Or =
1015 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1016 I->getName());
1017 return InsertNewInstBefore(Or, *I);
1018 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001019
1020 // If all of the demanded bits on one side are known, and all of the set
1021 // bits on that side are also known to be set on the other side, turn this
1022 // into an AND, as we know the bits will be cleared.
1023 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1024 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1025 // all known
1026 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001027 Constant *AndC = Constant::getIntegerValue(VTy,
1028 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001029 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001030 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001031 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001032 }
1033 }
1034
1035 // If the RHS is a constant, see if we can simplify it.
1036 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001037 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001038 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001039
1040 RHSKnownZero = KnownZeroOut;
1041 RHSKnownOne = KnownOneOut;
1042 break;
1043 }
1044 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001045 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1046 RHSKnownZero, RHSKnownOne, Depth+1) ||
1047 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001048 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001049 return I;
1050 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1051 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001052
1053 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001054 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1055 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001057
1058 // Only known if known in both the LHS and RHS.
1059 RHSKnownOne &= LHSKnownOne;
1060 RHSKnownZero &= LHSKnownZero;
1061 break;
1062 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001063 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001064 DemandedMask.zext(truncBf);
1065 RHSKnownZero.zext(truncBf);
1066 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001068 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001069 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001070 DemandedMask.trunc(BitWidth);
1071 RHSKnownZero.trunc(BitWidth);
1072 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001073 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001074 break;
1075 }
1076 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001077 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001079
1080 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1081 if (const VectorType *SrcVTy =
1082 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1083 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1084 // Don't touch a bitcast between vectors of different element counts.
1085 return false;
1086 } else
1087 // Don't touch a scalar-to-vector bitcast.
1088 return false;
1089 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1090 // Don't touch a vector-to-scalar bitcast.
1091 return false;
1092
Chris Lattner886ab6c2009-01-31 08:15:18 +00001093 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001094 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001095 return I;
1096 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 break;
1098 case Instruction::ZExt: {
1099 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001100 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001101
Zhou Shengd48653a2007-03-29 04:45:55 +00001102 DemandedMask.trunc(SrcBitWidth);
1103 RHSKnownZero.trunc(SrcBitWidth);
1104 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001105 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001106 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001108 DemandedMask.zext(BitWidth);
1109 RHSKnownZero.zext(BitWidth);
1110 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001111 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001112 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001113 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001114 break;
1115 }
1116 case Instruction::SExt: {
1117 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001118 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001119
Reid Spencer8cb68342007-03-12 17:25:59 +00001120 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001121 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001122
Zhou Sheng01542f32007-03-29 02:26:30 +00001123 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001124 // If any of the sign extended bits are demanded, we know that the sign
1125 // bit is demanded.
1126 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001127 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001128
Zhou Shengd48653a2007-03-29 04:45:55 +00001129 InputDemandedBits.trunc(SrcBitWidth);
1130 RHSKnownZero.trunc(SrcBitWidth);
1131 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001132 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001133 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001134 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 InputDemandedBits.zext(BitWidth);
1136 RHSKnownZero.zext(BitWidth);
1137 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001138 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001139
1140 // If the sign bit of the input is known set or clear, then we know the
1141 // top bits of the result.
1142
1143 // If the input sign bit is known zero, or if the NewBits are not demanded
1144 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001145 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001146 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001147 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1148 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001149 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001150 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001151 }
1152 break;
1153 }
1154 case Instruction::Add: {
1155 // Figure out what the input bits are. If the top bits of the and result
1156 // are not demanded, then the add doesn't demand them from its input
1157 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001158 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001159
1160 // If there is a constant on the RHS, there are a variety of xformations
1161 // we can do.
1162 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1163 // If null, this should be simplified elsewhere. Some of the xforms here
1164 // won't work if the RHS is zero.
1165 if (RHS->isZero())
1166 break;
1167
1168 // If the top bit of the output is demanded, demand everything from the
1169 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001170 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001171
1172 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001173 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001174 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001175 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001176
1177 // If the RHS of the add has bits set that can't affect the input, reduce
1178 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001179 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001180 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001181
1182 // Avoid excess work.
1183 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1184 break;
1185
1186 // Turn it into OR if input bits are zero.
1187 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1188 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001189 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001190 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001191 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001192 }
1193
1194 // We can say something about the output known-zero and known-one bits,
1195 // depending on potential carries from the input constant and the
1196 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1197 // bits set and the RHS constant is 0x01001, then we know we have a known
1198 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1199
1200 // To compute this, we first compute the potential carry bits. These are
1201 // the bits which may be modified. I'm not aware of a better way to do
1202 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001203 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001204 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001205
1206 // Now that we know which bits have carries, compute the known-1/0 sets.
1207
1208 // Bits are known one if they are known zero in one operand and one in the
1209 // other, and there is no input carry.
1210 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1211 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1212
1213 // Bits are known zero if they are known zero in both operands and there
1214 // is no input carry.
1215 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1216 } else {
1217 // If the high-bits of this ADD are not demanded, then it does not demand
1218 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001219 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001220 // Right fill the mask of bits for this ADD to demand the most
1221 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001222 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001223 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1224 LHSKnownZero, LHSKnownOne, Depth+1) ||
1225 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001226 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001227 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001228 }
1229 }
1230 break;
1231 }
1232 case Instruction::Sub:
1233 // If the high-bits of this SUB are not demanded, then it does not demand
1234 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001235 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001236 // Right fill the mask of bits for this SUB to demand the most
1237 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001238 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001239 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001240 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1241 LHSKnownZero, LHSKnownOne, Depth+1) ||
1242 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001243 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001244 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001246 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1247 // the known zeros and ones.
1248 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001249 break;
1250 case Instruction::Shl:
1251 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001252 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001253 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001254 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001255 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001256 return I;
1257 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001258 RHSKnownZero <<= ShiftAmt;
1259 RHSKnownOne <<= ShiftAmt;
1260 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001261 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001262 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001263 }
1264 break;
1265 case Instruction::LShr:
1266 // For a logical shift right
1267 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001268 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001269
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001271 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001272 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001274 return I;
1275 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001276 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1277 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001278 if (ShiftAmt) {
1279 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001280 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001281 RHSKnownZero |= HighBits; // high bits known zero.
1282 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001283 }
1284 break;
1285 case Instruction::AShr:
1286 // If this is an arithmetic shift right and only the low-bit is set, we can
1287 // always convert this into a logical shr, even if the shift amount is
1288 // variable. The low bit of the shift cannot be an input sign bit unless
1289 // the shift amount is >= the size of the datatype, which is undefined.
1290 if (DemandedMask == 1) {
1291 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001292 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001293 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001294 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001296
1297 // If the sign bit is the only bit demanded by this ashr, then there is no
1298 // need to do it, the shift doesn't change the high bit.
1299 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001300 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001301
1302 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001303 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001304
Reid Spencer8cb68342007-03-12 17:25:59 +00001305 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001306 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001307 // If any of the "high bits" are demanded, we should set the sign bit as
1308 // demanded.
1309 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1310 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001311 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001312 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001313 return I;
1314 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001315 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001316 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1318 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1319
1320 // Handle the sign bits.
1321 APInt SignBit(APInt::getSignBit(BitWidth));
1322 // Adjust to where it is now in the mask.
1323 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1324
1325 // If the input sign bit is known to be zero, or if none of the top bits
1326 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001327 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001328 (HighBits & ~DemandedMask) == HighBits) {
1329 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001330 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001331 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001332 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001333 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1334 RHSKnownOne |= HighBits;
1335 }
1336 }
1337 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001338 case Instruction::SRem:
1339 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001340 APInt RA = Rem->getValue().abs();
1341 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001342 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001343 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001344
Nick Lewycky8e394322008-11-02 02:41:50 +00001345 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001346 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001347 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001348 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001349 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001350
1351 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1352 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001353
1354 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001355
Chris Lattner886ab6c2009-01-31 08:15:18 +00001356 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001357 }
1358 }
1359 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001360 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001361 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1362 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001363 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1364 KnownZero2, KnownOne2, Depth+1) ||
1365 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001366 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001367 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001368
Chris Lattner455e9ab2009-01-21 18:09:24 +00001369 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001370 Leaders = std::max(Leaders,
1371 KnownZero2.countLeadingOnes());
1372 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001373 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001374 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001375 case Instruction::Call:
1376 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1377 switch (II->getIntrinsicID()) {
1378 default: break;
1379 case Intrinsic::bswap: {
1380 // If the only bits demanded come from one byte of the bswap result,
1381 // just shift the input byte into position to eliminate the bswap.
1382 unsigned NLZ = DemandedMask.countLeadingZeros();
1383 unsigned NTZ = DemandedMask.countTrailingZeros();
1384
1385 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1386 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1387 // have 14 leading zeros, round to 8.
1388 NLZ &= ~7;
1389 NTZ &= ~7;
1390 // If we need exactly one byte, we can do this transformation.
1391 if (BitWidth-NLZ-NTZ == 8) {
1392 unsigned ResultBit = NTZ;
1393 unsigned InputBit = BitWidth-NTZ-8;
1394
1395 // Replace this with either a left or right shift to get the byte into
1396 // the right place.
1397 Instruction *NewVal;
1398 if (InputBit > ResultBit)
1399 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001400 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001401 else
1402 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001403 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001404 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001405 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001406 }
1407
1408 // TODO: Could compute known zero/one bits based on the input.
1409 break;
1410 }
1411 }
1412 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001413 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001414 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001415 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001416
1417 // If the client is only demanding bits that we know, return the known
1418 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001419 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1420 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001421 return false;
1422}
1423
Chris Lattner867b99f2006-10-05 06:55:50 +00001424
Mon P Wangaeb06d22008-11-10 04:46:22 +00001425/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001426/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001427/// actually used by the caller. This method analyzes which elements of the
1428/// operand are undef and returns that information in UndefElts.
1429///
1430/// If the information about demanded elements can be used to simplify the
1431/// operation, the operation is simplified, then the resultant value is
1432/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001433Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1434 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001435 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001436 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001437 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001438 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001439
1440 if (isa<UndefValue>(V)) {
1441 // If the entire vector is undefined, just return this info.
1442 UndefElts = EltMask;
1443 return 0;
1444 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1445 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001446 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001447 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001448
Chris Lattner867b99f2006-10-05 06:55:50 +00001449 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001450 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1451 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001452 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001453
1454 std::vector<Constant*> Elts;
1455 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001456 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001457 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001458 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001459 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1460 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001461 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001462 } else { // Otherwise, defined.
1463 Elts.push_back(CP->getOperand(i));
1464 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001465
Chris Lattner867b99f2006-10-05 06:55:50 +00001466 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001467 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001468 return NewCP != CP ? NewCP : 0;
1469 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001470 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001471 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001472
1473 // Check if this is identity. If so, return 0 since we are not simplifying
1474 // anything.
1475 if (DemandedElts == ((1ULL << VWidth) -1))
1476 return 0;
1477
Reid Spencer9d6565a2007-02-15 02:26:10 +00001478 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001479 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001480 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001481 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001482 for (unsigned i = 0; i != VWidth; ++i) {
1483 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1484 Elts.push_back(Elt);
1485 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001486 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001487 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001488 }
1489
Dan Gohman488fbfc2008-09-09 18:11:14 +00001490 // Limit search depth.
1491 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001492 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001493
1494 // If multiple users are using the root value, procede with
1495 // simplification conservatively assuming that all elements
1496 // are needed.
1497 if (!V->hasOneUse()) {
1498 // Quit if we find multiple users of a non-root value though.
1499 // They'll be handled when it's their turn to be visited by
1500 // the main instcombine process.
1501 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001502 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001503 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001504
1505 // Conservatively assume that all elements are needed.
1506 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001507 }
1508
1509 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001510 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001511
1512 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001513 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001514 Value *TmpV;
1515 switch (I->getOpcode()) {
1516 default: break;
1517
1518 case Instruction::InsertElement: {
1519 // If this is a variable index, we don't know which element it overwrites.
1520 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001521 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001522 if (Idx == 0) {
1523 // Note that we can't propagate undef elt info, because we don't know
1524 // which elt is getting updated.
1525 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1526 UndefElts2, Depth+1);
1527 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1528 break;
1529 }
1530
1531 // If this is inserting an element that isn't demanded, remove this
1532 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001533 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001534 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1535 Worklist.Add(I);
1536 return I->getOperand(0);
1537 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001538
1539 // Otherwise, the element inserted overwrites whatever was there, so the
1540 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001541 APInt DemandedElts2 = DemandedElts;
1542 DemandedElts2.clear(IdxNo);
1543 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001544 UndefElts, Depth+1);
1545 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1546
1547 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001548 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001549 break;
1550 }
1551 case Instruction::ShuffleVector: {
1552 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001553 uint64_t LHSVWidth =
1554 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001555 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001556 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001557 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001558 unsigned MaskVal = Shuffle->getMaskValue(i);
1559 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001560 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001561 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001562 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001563 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001564 else
Evan Cheng388df622009-02-03 10:05:09 +00001565 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001566 }
1567 }
1568 }
1569
Nate Begeman7b254672009-02-11 22:36:25 +00001570 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001572 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001573 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1574
Nate Begeman7b254672009-02-11 22:36:25 +00001575 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001576 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1577 UndefElts3, Depth+1);
1578 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1579
1580 bool NewUndefElts = false;
1581 for (unsigned i = 0; i < VWidth; i++) {
1582 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001583 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001584 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001585 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001586 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001587 NewUndefElts = true;
1588 UndefElts.set(i);
1589 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001590 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001591 if (UndefElts3[MaskVal - LHSVWidth]) {
1592 NewUndefElts = true;
1593 UndefElts.set(i);
1594 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001595 }
1596 }
1597
1598 if (NewUndefElts) {
1599 // Add additional discovered undefs.
1600 std::vector<Constant*> Elts;
1601 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001602 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001603 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001604 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001605 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001606 Shuffle->getMaskValue(i)));
1607 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001608 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001609 MadeChange = true;
1610 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001611 break;
1612 }
Chris Lattner69878332007-04-14 22:29:23 +00001613 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001614 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001615 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1616 if (!VTy) break;
1617 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001618 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001619 unsigned Ratio;
1620
1621 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001622 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001623 // elements as are demanded of us.
1624 Ratio = 1;
1625 InputDemandedElts = DemandedElts;
1626 } else if (VWidth > InVWidth) {
1627 // Untested so far.
1628 break;
1629
1630 // If there are more elements in the result than there are in the source,
1631 // then an input element is live if any of the corresponding output
1632 // elements are live.
1633 Ratio = VWidth/InVWidth;
1634 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001635 if (DemandedElts[OutIdx])
1636 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001637 }
1638 } else {
1639 // Untested so far.
1640 break;
1641
1642 // If there are more elements in the source than there are in the result,
1643 // then an input element is live if the corresponding output element is
1644 // live.
1645 Ratio = InVWidth/VWidth;
1646 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001647 if (DemandedElts[InIdx/Ratio])
1648 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001649 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001650
Chris Lattner69878332007-04-14 22:29:23 +00001651 // div/rem demand all inputs, because they don't want divide by zero.
1652 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1653 UndefElts2, Depth+1);
1654 if (TmpV) {
1655 I->setOperand(0, TmpV);
1656 MadeChange = true;
1657 }
1658
1659 UndefElts = UndefElts2;
1660 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001661 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001662 // If there are more elements in the result than there are in the source,
1663 // then an output element is undef if the corresponding input element is
1664 // undef.
1665 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001666 if (UndefElts2[OutIdx/Ratio])
1667 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001668 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001669 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001670 // If there are more elements in the source than there are in the result,
1671 // then a result element is undef if all of the corresponding input
1672 // elements are undef.
1673 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1674 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001675 if (!UndefElts2[InIdx]) // Not undef?
1676 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001677 }
1678 break;
1679 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001680 case Instruction::And:
1681 case Instruction::Or:
1682 case Instruction::Xor:
1683 case Instruction::Add:
1684 case Instruction::Sub:
1685 case Instruction::Mul:
1686 // div/rem demand all inputs, because they don't want divide by zero.
1687 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1688 UndefElts, Depth+1);
1689 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1690 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1691 UndefElts2, Depth+1);
1692 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1693
1694 // Output elements are undefined if both are undefined. Consider things
1695 // like undef&0. The result is known zero, not undef.
1696 UndefElts &= UndefElts2;
1697 break;
1698
1699 case Instruction::Call: {
1700 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1701 if (!II) break;
1702 switch (II->getIntrinsicID()) {
1703 default: break;
1704
1705 // Binary vector operations that work column-wise. A dest element is a
1706 // function of the corresponding input elements from the two inputs.
1707 case Intrinsic::x86_sse_sub_ss:
1708 case Intrinsic::x86_sse_mul_ss:
1709 case Intrinsic::x86_sse_min_ss:
1710 case Intrinsic::x86_sse_max_ss:
1711 case Intrinsic::x86_sse2_sub_sd:
1712 case Intrinsic::x86_sse2_mul_sd:
1713 case Intrinsic::x86_sse2_min_sd:
1714 case Intrinsic::x86_sse2_max_sd:
1715 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1716 UndefElts, Depth+1);
1717 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1718 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1719 UndefElts2, Depth+1);
1720 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1721
1722 // If only the low elt is demanded and this is a scalarizable intrinsic,
1723 // scalarize it now.
1724 if (DemandedElts == 1) {
1725 switch (II->getIntrinsicID()) {
1726 default: break;
1727 case Intrinsic::x86_sse_sub_ss:
1728 case Intrinsic::x86_sse_mul_ss:
1729 case Intrinsic::x86_sse2_sub_sd:
1730 case Intrinsic::x86_sse2_mul_sd:
1731 // TODO: Lower MIN/MAX/ABS/etc
1732 Value *LHS = II->getOperand(1);
1733 Value *RHS = II->getOperand(2);
1734 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001735 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001736 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001737 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001738 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001739
1740 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001741 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001742 case Intrinsic::x86_sse_sub_ss:
1743 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001744 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001745 II->getName()), *II);
1746 break;
1747 case Intrinsic::x86_sse_mul_ss:
1748 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001749 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001750 II->getName()), *II);
1751 break;
1752 }
1753
1754 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001755 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001756 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001757 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001758 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001759 return New;
1760 }
1761 }
1762
1763 // Output elements are undefined if both are undefined. Consider things
1764 // like undef&0. The result is known zero, not undef.
1765 UndefElts &= UndefElts2;
1766 break;
1767 }
1768 break;
1769 }
1770 }
1771 return MadeChange ? I : 0;
1772}
1773
Dan Gohman45b4e482008-05-19 22:14:15 +00001774
Chris Lattner564a7272003-08-13 19:01:45 +00001775/// AssociativeOpt - Perform an optimization on an associative operator. This
1776/// function is designed to check a chain of associative operators for a
1777/// potential to apply a certain optimization. Since the optimization may be
1778/// applicable if the expression was reassociated, this checks the chain, then
1779/// reassociates the expression as necessary to expose the optimization
1780/// opportunity. This makes use of a special Functor, which must define
1781/// 'shouldApply' and 'apply' methods.
1782///
1783template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001784static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001785 unsigned Opcode = Root.getOpcode();
1786 Value *LHS = Root.getOperand(0);
1787
1788 // Quick check, see if the immediate LHS matches...
1789 if (F.shouldApply(LHS))
1790 return F.apply(Root);
1791
1792 // Otherwise, if the LHS is not of the same opcode as the root, return.
1793 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001794 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001795 // Should we apply this transform to the RHS?
1796 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1797
1798 // If not to the RHS, check to see if we should apply to the LHS...
1799 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1800 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1801 ShouldApply = true;
1802 }
1803
1804 // If the functor wants to apply the optimization to the RHS of LHSI,
1805 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1806 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001807 // Now all of the instructions are in the current basic block, go ahead
1808 // and perform the reassociation.
1809 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1810
1811 // First move the selected RHS to the LHS of the root...
1812 Root.setOperand(0, LHSI->getOperand(1));
1813
1814 // Make what used to be the LHS of the root be the user of the root...
1815 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001816 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001817 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001818 return 0;
1819 }
Chris Lattner65725312004-04-16 18:08:07 +00001820 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001821 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001822 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001823 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001824 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001825
1826 // Now propagate the ExtraOperand down the chain of instructions until we
1827 // get to LHSI.
1828 while (TmpLHSI != LHSI) {
1829 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001830 // Move the instruction to immediately before the chain we are
1831 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001832 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001833 ARI = NextLHSI;
1834
Chris Lattner564a7272003-08-13 19:01:45 +00001835 Value *NextOp = NextLHSI->getOperand(1);
1836 NextLHSI->setOperand(1, ExtraOperand);
1837 TmpLHSI = NextLHSI;
1838 ExtraOperand = NextOp;
1839 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001840
Chris Lattner564a7272003-08-13 19:01:45 +00001841 // Now that the instructions are reassociated, have the functor perform
1842 // the transformation...
1843 return F.apply(Root);
1844 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001845
Chris Lattner564a7272003-08-13 19:01:45 +00001846 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1847 }
1848 return 0;
1849}
1850
Dan Gohman844731a2008-05-13 00:00:25 +00001851namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001852
Nick Lewycky02d639f2008-05-23 04:34:58 +00001853// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001854struct AddRHS {
1855 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001856 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001857 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1858 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001859 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001860 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001861 }
1862};
1863
1864// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1865// iff C1&C2 == 0
1866struct AddMaskingAnd {
1867 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001868 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001869 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001870 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001871 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001872 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001873 }
1874 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001875 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001876 }
1877};
1878
Dan Gohman844731a2008-05-13 00:00:25 +00001879}
1880
Chris Lattner6e7ba452005-01-01 16:22:27 +00001881static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001882 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001883 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001884 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001885
Chris Lattner2eefe512004-04-09 19:05:30 +00001886 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001887 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1888 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001889
Chris Lattner2eefe512004-04-09 19:05:30 +00001890 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1891 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001892 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1893 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001894 }
1895
1896 Value *Op0 = SO, *Op1 = ConstOperand;
1897 if (!ConstIsRHS)
1898 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001899
Chris Lattner6e7ba452005-01-01 16:22:27 +00001900 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001901 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1902 SO->getName()+".op");
1903 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1904 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1905 SO->getName()+".cmp");
1906 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1907 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1908 SO->getName()+".cmp");
1909 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001910}
1911
1912// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1913// constant as the other operand, try to fold the binary operator into the
1914// select arguments. This also works for Cast instructions, which obviously do
1915// not have a second operand.
1916static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1917 InstCombiner *IC) {
1918 // Don't modify shared select instructions
1919 if (!SI->hasOneUse()) return 0;
1920 Value *TV = SI->getOperand(1);
1921 Value *FV = SI->getOperand(2);
1922
1923 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001924 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001925 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001926
Chris Lattner6e7ba452005-01-01 16:22:27 +00001927 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1928 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1929
Gabor Greif051a9502008-04-06 20:25:17 +00001930 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1931 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001932 }
1933 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001934}
1935
Chris Lattner4e998b22004-09-29 05:07:12 +00001936
1937/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1938/// node as operand #0, see if we can fold the instruction into the PHI (which
1939/// is only possible if all operands to the PHI are constants).
1940Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1941 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001942 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001943 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001944
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001945 // Check to see if all of the operands of the PHI are constants. If there is
1946 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001947 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001948 BasicBlock *NonConstBB = 0;
1949 for (unsigned i = 0; i != NumPHIValues; ++i)
1950 if (!isa<Constant>(PN->getIncomingValue(i))) {
1951 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001952 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001953 NonConstBB = PN->getIncomingBlock(i);
1954
1955 // If the incoming non-constant value is in I's block, we have an infinite
1956 // loop.
1957 if (NonConstBB == I.getParent())
1958 return 0;
1959 }
1960
1961 // If there is exactly one non-constant value, we can insert a copy of the
1962 // operation in that block. However, if this is a critical edge, we would be
1963 // inserting the computation one some other paths (e.g. inside a loop). Only
1964 // do this if the pred block is unconditionally branching into the phi block.
1965 if (NonConstBB) {
1966 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1967 if (!BI || !BI->isUnconditional()) return 0;
1968 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001969
1970 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001971 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001972 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001973 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001974 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001975
1976 // Next, add all of the operands to the PHI.
1977 if (I.getNumOperands() == 2) {
1978 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001979 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001980 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001981 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001982 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001983 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001984 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001985 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001986 } else {
1987 assert(PN->getIncomingBlock(i) == NonConstBB);
1988 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001989 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001990 PN->getIncomingValue(i), C, "phitmp",
1991 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001992 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001993 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001994 CI->getPredicate(),
1995 PN->getIncomingValue(i), C, "phitmp",
1996 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001997 else
Torok Edwinc23197a2009-07-14 16:55:14 +00001998 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001999
Chris Lattner7a1e9242009-08-30 06:13:40 +00002000 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002001 }
2002 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002003 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002004 } else {
2005 CastInst *CI = cast<CastInst>(&I);
2006 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002007 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002008 Value *InV;
2009 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002010 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002011 } else {
2012 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002013 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002014 I.getType(), "phitmp",
2015 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002016 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002017 }
2018 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002019 }
2020 }
2021 return ReplaceInstUsesWith(I, NewPN);
2022}
2023
Chris Lattner2454a2e2008-01-29 06:52:45 +00002024
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002025/// WillNotOverflowSignedAdd - Return true if we can prove that:
2026/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2027/// This basically requires proving that the add in the original type would not
2028/// overflow to change the sign bit or have a carry out.
2029bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2030 // There are different heuristics we can use for this. Here are some simple
2031 // ones.
2032
2033 // Add has the property that adding any two 2's complement numbers can only
2034 // have one carry bit which can change a sign. As such, if LHS and RHS each
2035 // have at least two sign bits, we know that the addition of the two values will
2036 // sign extend fine.
2037 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2038 return true;
2039
2040
2041 // If one of the operands only has one non-zero bit, and if the other operand
2042 // has a known-zero bit in a more significant place than it (not including the
2043 // sign bit) the ripple may go up to and fill the zero, but won't change the
2044 // sign. For example, (X & ~4) + 1.
2045
2046 // TODO: Implement.
2047
2048 return false;
2049}
2050
Chris Lattner2454a2e2008-01-29 06:52:45 +00002051
Chris Lattner7e708292002-06-25 16:13:24 +00002052Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002053 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002054 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002055
Chris Lattner66331a42004-04-10 22:01:55 +00002056 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002057 // X + undef -> undef
2058 if (isa<UndefValue>(RHS))
2059 return ReplaceInstUsesWith(I, RHS);
2060
Chris Lattner66331a42004-04-10 22:01:55 +00002061 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002062 if (RHSC->isNullValue())
2063 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002064
Chris Lattner66331a42004-04-10 22:01:55 +00002065 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002066 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002067 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002068 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002069 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002070 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002071
2072 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2073 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002074 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002075 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002076
Eli Friedman709b33d2009-07-13 22:27:52 +00002077 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002078 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002079 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002080 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002081 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002082
2083 if (isa<PHINode>(LHS))
2084 if (Instruction *NV = FoldOpIntoPhi(I))
2085 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002086
Chris Lattner4f637d42006-01-06 17:59:59 +00002087 ConstantInt *XorRHS = 0;
2088 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002089 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002090 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002091 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002092 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002093
Zhou Sheng4351c642007-04-02 08:20:41 +00002094 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002095 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2096 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002097 do {
2098 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002099 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2100 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002101 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2102 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002103 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002104 if (!MaskedValueIsZero(XorLHS,
2105 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002106 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002107 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002108 }
2109 }
2110 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002111 C0080Val = APIntOps::lshr(C0080Val, Size);
2112 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2113 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002114
Reid Spencer35c38852007-03-28 01:36:16 +00002115 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002116 // with funny bit widths then this switch statement should be removed. It
2117 // is just here to get the size of the "middle" type back up to something
2118 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002119 const Type *MiddleType = 0;
2120 switch (Size) {
2121 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002122 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2123 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2124 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002125 }
2126 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002127 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002128 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002129 }
2130 }
Chris Lattner66331a42004-04-10 22:01:55 +00002131 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002132
Owen Anderson1d0be152009-08-13 21:58:54 +00002133 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002134 return BinaryOperator::CreateXor(LHS, RHS);
2135
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002136 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002137 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002138 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002139 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002140
2141 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2142 if (RHSI->getOpcode() == Instruction::Sub)
2143 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2144 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2145 }
2146 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2147 if (LHSI->getOpcode() == Instruction::Sub)
2148 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2149 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2150 }
Robert Bocchino71698282004-07-27 21:02:21 +00002151 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002152
Chris Lattner5c4afb92002-05-08 22:46:53 +00002153 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002154 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002155 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002156 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002157 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002158 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002159 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002160 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002161 }
2162
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002163 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002164 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002165
2166 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002167 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002168 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002169 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002170
Misha Brukmanfd939082005-04-21 23:48:37 +00002171
Chris Lattner50af16a2004-11-13 19:50:12 +00002172 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002173 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002174 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002175 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002176
2177 // X*C1 + X*C2 --> X * (C1+C2)
2178 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002179 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002180 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002181 }
2182
2183 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002184 if (dyn_castFoldableMul(RHS, C2) == LHS)
2185 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002186
Chris Lattnere617c9e2007-01-05 02:17:46 +00002187 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002188 if (dyn_castNotVal(LHS) == RHS ||
2189 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002190 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002191
Chris Lattnerad3448c2003-02-18 19:57:07 +00002192
Chris Lattner564a7272003-08-13 19:01:45 +00002193 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002194 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2195 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002196 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002197
2198 // A+B --> A|B iff A and B have no bits set in common.
2199 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2200 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2201 APInt LHSKnownOne(IT->getBitWidth(), 0);
2202 APInt LHSKnownZero(IT->getBitWidth(), 0);
2203 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2204 if (LHSKnownZero != 0) {
2205 APInt RHSKnownOne(IT->getBitWidth(), 0);
2206 APInt RHSKnownZero(IT->getBitWidth(), 0);
2207 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2208
2209 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002210 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002211 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002212 }
2213 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002214
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002215 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002216 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002217 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002218 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2219 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002220 if (W != Y) {
2221 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002222 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002223 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002224 std::swap(W, X);
2225 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002226 std::swap(Y, Z);
2227 std::swap(W, X);
2228 }
2229 }
2230
2231 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002232 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002233 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002234 }
2235 }
2236 }
2237
Chris Lattner6b032052003-10-02 15:11:26 +00002238 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002239 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002240 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002241 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002242
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002243 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002244 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002245 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002246 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002247 if (Anded == CRHS) {
2248 // See if all bits from the first bit set in the Add RHS up are included
2249 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002250 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002251
2252 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002253 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002254
2255 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002256 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002257
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002258 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2259 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002260 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002261 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002262 }
2263 }
2264 }
2265
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002266 // Try to fold constant add into select arguments.
2267 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002268 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002269 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002270 }
2271
Chris Lattner42790482007-12-20 01:56:58 +00002272 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002273 {
2274 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002275 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002276 if (!SI) {
2277 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002278 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002279 }
Chris Lattner42790482007-12-20 01:56:58 +00002280 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002281 Value *TV = SI->getTrueValue();
2282 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002283 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002284
2285 // Can we fold the add into the argument of the select?
2286 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002287 if (match(FV, m_Zero()) &&
2288 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002289 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002290 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002291 if (match(TV, m_Zero()) &&
2292 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002293 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002294 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002295 }
2296 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002297
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002298 // Check for (add (sext x), y), see if we can merge this into an
2299 // integer add followed by a sext.
2300 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2301 // (add (sext x), cst) --> (sext (add x, cst'))
2302 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2303 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002304 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002305 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002306 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002307 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2308 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002309 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2310 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002311 return new SExtInst(NewAdd, I.getType());
2312 }
2313 }
2314
2315 // (add (sext x), (sext y)) --> (sext (add int x, y))
2316 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2317 // Only do this if x/y have the same type, if at last one of them has a
2318 // single use (so we don't increase the number of sexts), and if the
2319 // integer add will not overflow.
2320 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2321 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2322 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2323 RHSConv->getOperand(0))) {
2324 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002325 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2326 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002327 return new SExtInst(NewAdd, I.getType());
2328 }
2329 }
2330 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002331
2332 return Changed ? &I : 0;
2333}
2334
2335Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2336 bool Changed = SimplifyCommutative(I);
2337 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2338
2339 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2340 // X + 0 --> X
2341 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002342 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002343 (I.getType())->getValueAPF()))
2344 return ReplaceInstUsesWith(I, LHS);
2345 }
2346
2347 if (isa<PHINode>(LHS))
2348 if (Instruction *NV = FoldOpIntoPhi(I))
2349 return NV;
2350 }
2351
2352 // -A + B --> B - A
2353 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002354 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002355 return BinaryOperator::CreateFSub(RHS, LHSV);
2356
2357 // A + -B --> A - B
2358 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002359 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002360 return BinaryOperator::CreateFSub(LHS, V);
2361
2362 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2363 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2364 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2365 return ReplaceInstUsesWith(I, LHS);
2366
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002367 // Check for (add double (sitofp x), y), see if we can merge this into an
2368 // integer add followed by a promotion.
2369 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2370 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2371 // ... if the constant fits in the integer value. This is useful for things
2372 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2373 // requires a constant pool load, and generally allows the add to be better
2374 // instcombined.
2375 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2376 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002377 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002378 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002379 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002380 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2381 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002382 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2383 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002384 return new SIToFPInst(NewAdd, I.getType());
2385 }
2386 }
2387
2388 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2389 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2390 // Only do this if x/y have the same type, if at last one of them has a
2391 // single use (so we don't increase the number of int->fp conversions),
2392 // and if the integer add will not overflow.
2393 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2394 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2395 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2396 RHSConv->getOperand(0))) {
2397 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002398 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2399 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002400 return new SIToFPInst(NewAdd, I.getType());
2401 }
2402 }
2403 }
2404
Chris Lattner7e708292002-06-25 16:13:24 +00002405 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002406}
2407
Chris Lattner7e708292002-06-25 16:13:24 +00002408Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002410
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002411 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002412 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002413
Chris Lattner233f7dc2002-08-12 21:17:25 +00002414 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002415 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002416 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002417
Chris Lattnere87597f2004-10-16 18:11:37 +00002418 if (isa<UndefValue>(Op0))
2419 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2420 if (isa<UndefValue>(Op1))
2421 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2422
Chris Lattnerd65460f2003-11-05 01:06:05 +00002423 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2424 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002425 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002426 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002427
Chris Lattnerd65460f2003-11-05 01:06:05 +00002428 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002429 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002430 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002431 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002432
Chris Lattner76b7a062007-01-15 07:02:54 +00002433 // -(X >>u 31) -> (X >>s 31)
2434 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002435 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002436 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002437 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002438 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002439 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002440 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002441 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002442 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002443 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002444 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002445 }
2446 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002447 }
2448 else if (SI->getOpcode() == Instruction::AShr) {
2449 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2450 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002451 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002452 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002453 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002454 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002455 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002456 }
2457 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002458 }
2459 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002460 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002461
2462 // Try to fold constant sub into select arguments.
2463 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002464 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002465 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002466
2467 // C - zext(bool) -> bool ? C - 1 : C
2468 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002469 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002470 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002471 }
2472
Owen Anderson1d0be152009-08-13 21:58:54 +00002473 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002474 return BinaryOperator::CreateXor(Op0, Op1);
2475
Chris Lattner43d84d62005-04-07 16:15:25 +00002476 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002477 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002478 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002479 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002480 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002481 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002482 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002483 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002484 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2485 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2486 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002487 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002488 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002489 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002490 }
2491
Chris Lattnerfd059242003-10-15 16:48:29 +00002492 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002493 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2494 // is not used by anyone else...
2495 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002496 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002497 // Swap the two operands of the subexpr...
2498 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2499 Op1I->setOperand(0, IIOp1);
2500 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002501
Chris Lattnera2881962003-02-18 19:28:33 +00002502 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002503 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002504 }
2505
2506 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2507 //
2508 if (Op1I->getOpcode() == Instruction::And &&
2509 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2510 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2511
Chris Lattner74381062009-08-30 07:44:24 +00002512 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002513 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002514 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002515
Reid Spencerac5209e2006-10-16 23:08:08 +00002516 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002517 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002518 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002519 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002520 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002521 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002522 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002523
Chris Lattnerad3448c2003-02-18 19:57:07 +00002524 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002525 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002526 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002527 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002528 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002529 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002530 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002531 }
Chris Lattner40371712002-05-09 01:29:19 +00002532 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002533 }
Chris Lattnera2881962003-02-18 19:28:33 +00002534
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002535 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2536 if (Op0I->getOpcode() == Instruction::Add) {
2537 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2538 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2539 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2540 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2541 } else if (Op0I->getOpcode() == Instruction::Sub) {
2542 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002543 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002544 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002545 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002546 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002547
Chris Lattner50af16a2004-11-13 19:50:12 +00002548 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002549 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002550 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002551 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002552
Chris Lattner50af16a2004-11-13 19:50:12 +00002553 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002554 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002555 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002556 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002557 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002558}
2559
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002560Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2561 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2562
2563 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002564 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002565 return BinaryOperator::CreateFAdd(Op0, V);
2566
2567 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2568 if (Op1I->getOpcode() == Instruction::FAdd) {
2569 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002570 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002571 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002572 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002573 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002574 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002575 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002576 }
2577
2578 return 0;
2579}
2580
Chris Lattnera0141b92007-07-15 20:42:37 +00002581/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2582/// comparison only checks the sign bit. If it only checks the sign bit, set
2583/// TrueIfSigned if the result of the comparison is true when the input value is
2584/// signed.
2585static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2586 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002587 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002588 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2589 TrueIfSigned = true;
2590 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002591 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2592 TrueIfSigned = true;
2593 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002594 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2595 TrueIfSigned = false;
2596 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002597 case ICmpInst::ICMP_UGT:
2598 // True if LHS u> RHS and RHS == high-bit-mask - 1
2599 TrueIfSigned = true;
2600 return RHS->getValue() ==
2601 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2602 case ICmpInst::ICMP_UGE:
2603 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2604 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002605 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002606 default:
2607 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002608 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002609}
2610
Chris Lattner7e708292002-06-25 16:13:24 +00002611Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002612 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002613 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002614
Eli Friedman1694e092009-07-18 09:12:15 +00002615 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002616 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002617
Chris Lattner233f7dc2002-08-12 21:17:25 +00002618 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002619 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2620 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002621
2622 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002623 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002624 if (SI->getOpcode() == Instruction::Shl)
2625 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002626 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002627 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002628
Zhou Sheng843f07672007-04-19 05:39:12 +00002629 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002630 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2631 if (CI->equalsInt(1)) // X * 1 == X
2632 return ReplaceInstUsesWith(I, Op0);
2633 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002634 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002635
Zhou Sheng97b52c22007-03-29 01:57:21 +00002636 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002637 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002638 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002639 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002640 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002641 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002642 if (Op1->isNullValue())
2643 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002644
2645 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2646 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002647 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002648
2649 // As above, vector X*splat(1.0) -> X in all defined cases.
2650 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002651 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2652 if (CI->equalsInt(1))
2653 return ReplaceInstUsesWith(I, Op0);
2654 }
2655 }
Chris Lattnera2881962003-02-18 19:28:33 +00002656 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002657
2658 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2659 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002660 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002661 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner74381062009-08-30 07:44:24 +00002662 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2663 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002664 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002665
2666 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002667
2668 // Try to fold constant mul into select arguments.
2669 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002670 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002671 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002672
2673 if (isa<PHINode>(Op0))
2674 if (Instruction *NV = FoldOpIntoPhi(I))
2675 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002676 }
2677
Dan Gohman186a6362009-08-12 16:04:34 +00002678 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2679 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002680 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002681
Nick Lewycky0c730792008-11-21 07:33:58 +00002682 // (X / Y) * Y = X - (X % Y)
2683 // (X / Y) * -Y = (X % Y) - X
2684 {
2685 Value *Op1 = I.getOperand(1);
2686 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2687 if (!BO ||
2688 (BO->getOpcode() != Instruction::UDiv &&
2689 BO->getOpcode() != Instruction::SDiv)) {
2690 Op1 = Op0;
2691 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2692 }
Dan Gohman186a6362009-08-12 16:04:34 +00002693 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002694 if (BO && BO->hasOneUse() &&
2695 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2696 (BO->getOpcode() == Instruction::UDiv ||
2697 BO->getOpcode() == Instruction::SDiv)) {
2698 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2699
Dan Gohmanfa94b942009-08-12 16:33:09 +00002700 // If the division is exact, X % Y is zero.
2701 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2702 if (SDiv->isExact()) {
2703 if (Op1BO == Op1)
2704 return ReplaceInstUsesWith(I, Op0BO);
2705 else
2706 return BinaryOperator::CreateNeg(Op0BO);
2707 }
2708
Chris Lattner74381062009-08-30 07:44:24 +00002709 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002710 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002711 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002712 else
Chris Lattner74381062009-08-30 07:44:24 +00002713 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002714 Rem->takeName(BO);
2715
2716 if (Op1BO == Op1)
2717 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002718 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002719 }
2720 }
2721
Owen Anderson1d0be152009-08-13 21:58:54 +00002722 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002723 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2724
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002725 // If one of the operands of the multiply is a cast from a boolean value, then
2726 // we know the bool is either zero or one, so this is a 'masking' multiply.
2727 // See if we can simplify things based on how the boolean was originally
2728 // formed.
2729 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002730 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson1d0be152009-08-13 21:58:54 +00002731 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002732 BoolCast = CI;
2733 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002734 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00002735 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002736 BoolCast = CI;
2737 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002738 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002739 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2740 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002741 bool TIS = false;
2742
Reid Spencere4d87aa2006-12-23 06:05:41 +00002743 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002744 // multiply into a shift/and combination.
2745 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002746 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2747 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002748 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002749 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002750 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner74381062009-08-30 07:44:24 +00002751 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2752 BoolCast->getOperand(0)->getName()+".mask");
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002753
2754 // If the multiply type is not the same as the source type, sign extend
2755 // or truncate to the multiply type.
Chris Lattner2345d1d2009-08-30 20:01:10 +00002756 if (I.getType() != V->getType())
2757 V = Builder->CreateIntCast(V, I.getType(), true);
Misha Brukmanfd939082005-04-21 23:48:37 +00002758
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002759 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002760 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002761 }
2762 }
2763 }
2764
Chris Lattner7e708292002-06-25 16:13:24 +00002765 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002766}
2767
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002768Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2769 bool Changed = SimplifyCommutative(I);
2770 Value *Op0 = I.getOperand(0);
2771
2772 // Simplify mul instructions with a constant RHS...
2773 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2774 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2775 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2776 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2777 if (Op1F->isExactlyValue(1.0))
2778 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2779 } else if (isa<VectorType>(Op1->getType())) {
2780 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2781 // As above, vector X*splat(1.0) -> X in all defined cases.
2782 if (Constant *Splat = Op1V->getSplatValue()) {
2783 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2784 if (F->isExactlyValue(1.0))
2785 return ReplaceInstUsesWith(I, Op0);
2786 }
2787 }
2788 }
2789
2790 // Try to fold constant mul into select arguments.
2791 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2792 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2793 return R;
2794
2795 if (isa<PHINode>(Op0))
2796 if (Instruction *NV = FoldOpIntoPhi(I))
2797 return NV;
2798 }
2799
Dan Gohman186a6362009-08-12 16:04:34 +00002800 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2801 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002802 return BinaryOperator::CreateFMul(Op0v, Op1v);
2803
2804 return Changed ? &I : 0;
2805}
2806
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002807/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2808/// instruction.
2809bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2810 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2811
2812 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2813 int NonNullOperand = -1;
2814 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2815 if (ST->isNullValue())
2816 NonNullOperand = 2;
2817 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2818 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2819 if (ST->isNullValue())
2820 NonNullOperand = 1;
2821
2822 if (NonNullOperand == -1)
2823 return false;
2824
2825 Value *SelectCond = SI->getOperand(0);
2826
2827 // Change the div/rem to use 'Y' instead of the select.
2828 I.setOperand(1, SI->getOperand(NonNullOperand));
2829
2830 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2831 // problem. However, the select, or the condition of the select may have
2832 // multiple uses. Based on our knowledge that the operand must be non-zero,
2833 // propagate the known value for the select into other uses of it, and
2834 // propagate a known value of the condition into its other users.
2835
2836 // If the select and condition only have a single use, don't bother with this,
2837 // early exit.
2838 if (SI->use_empty() && SelectCond->hasOneUse())
2839 return true;
2840
2841 // Scan the current block backward, looking for other uses of SI.
2842 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2843
2844 while (BBI != BBFront) {
2845 --BBI;
2846 // If we found a call to a function, we can't assume it will return, so
2847 // information from below it cannot be propagated above it.
2848 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2849 break;
2850
2851 // Replace uses of the select or its condition with the known values.
2852 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2853 I != E; ++I) {
2854 if (*I == SI) {
2855 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002856 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002857 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002858 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2859 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002860 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002861 }
2862 }
2863
2864 // If we past the instruction, quit looking for it.
2865 if (&*BBI == SI)
2866 SI = 0;
2867 if (&*BBI == SelectCond)
2868 SelectCond = 0;
2869
2870 // If we ran out of things to eliminate, break out of the loop.
2871 if (SelectCond == 0 && SI == 0)
2872 break;
2873
2874 }
2875 return true;
2876}
2877
2878
Reid Spencer1628cec2006-10-26 06:15:43 +00002879/// This function implements the transforms on div instructions that work
2880/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2881/// used by the visitors to those instructions.
2882/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002883Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002884 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002885
Chris Lattner50b2ca42008-02-19 06:12:18 +00002886 // undef / X -> 0 for integer.
2887 // undef / X -> undef for FP (the undef could be a snan).
2888 if (isa<UndefValue>(Op0)) {
2889 if (Op0->getType()->isFPOrFPVector())
2890 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002891 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002892 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002893
2894 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002895 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002896 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002897
Reid Spencer1628cec2006-10-26 06:15:43 +00002898 return 0;
2899}
Misha Brukmanfd939082005-04-21 23:48:37 +00002900
Reid Spencer1628cec2006-10-26 06:15:43 +00002901/// This function implements the transforms common to both integer division
2902/// instructions (udiv and sdiv). It is called by the visitors to those integer
2903/// division instructions.
2904/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002905Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2907
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002908 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002909 if (Op0 == Op1) {
2910 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002911 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002912 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002913 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002914 }
2915
Owen Andersoneed707b2009-07-24 23:12:02 +00002916 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002917 return ReplaceInstUsesWith(I, CI);
2918 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002919
Reid Spencer1628cec2006-10-26 06:15:43 +00002920 if (Instruction *Common = commonDivTransforms(I))
2921 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002922
2923 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2924 // This does not apply for fdiv.
2925 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2926 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002927
2928 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2929 // div X, 1 == X
2930 if (RHS->equalsInt(1))
2931 return ReplaceInstUsesWith(I, Op0);
2932
2933 // (X / C1) / C2 -> X / (C1*C2)
2934 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2935 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2936 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002937 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002938 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002939 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002940 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002941 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002942 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002943 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002944
Reid Spencerbca0e382007-03-23 20:05:17 +00002945 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002946 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2947 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2948 return R;
2949 if (isa<PHINode>(Op0))
2950 if (Instruction *NV = FoldOpIntoPhi(I))
2951 return NV;
2952 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002953 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002954
Chris Lattnera2881962003-02-18 19:28:33 +00002955 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002956 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002957 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00002958 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002959
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002960 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00002961 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002962 return ReplaceInstUsesWith(I, Op0);
2963
Nick Lewycky895f0852008-11-27 20:21:08 +00002964 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2965 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2966 // div X, 1 == X
2967 if (X->isOne())
2968 return ReplaceInstUsesWith(I, Op0);
2969 }
2970
Reid Spencer1628cec2006-10-26 06:15:43 +00002971 return 0;
2972}
2973
2974Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2975 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2976
2977 // Handle the integer div common cases
2978 if (Instruction *Common = commonIDivTransforms(I))
2979 return Common;
2980
Reid Spencer1628cec2006-10-26 06:15:43 +00002981 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002982 // X udiv C^2 -> X >> C
2983 // Check to see if this is an unsigned division with an exact power of 2,
2984 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002985 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002986 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002987 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002988
2989 // X udiv C, where C >= signbit
2990 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00002991 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00002992 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00002993 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002994 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002995 }
2996
2997 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002998 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002999 if (RHSI->getOpcode() == Instruction::Shl &&
3000 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003001 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003002 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003003 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003004 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003005 if (uint32_t C2 = C1.logBase2())
3006 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003007 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003008 }
3009 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003010 }
3011
Reid Spencer1628cec2006-10-26 06:15:43 +00003012 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3013 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003014 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003015 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003016 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003017 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003018 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003019 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003020 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003021 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003022 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003023 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003024
3025 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003026 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003027 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003028
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003029 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003030 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003031 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003032 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003033 return 0;
3034}
3035
Reid Spencer1628cec2006-10-26 06:15:43 +00003036Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3038
3039 // Handle the integer div common cases
3040 if (Instruction *Common = commonIDivTransforms(I))
3041 return Common;
3042
3043 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3044 // sdiv X, -1 == -X
3045 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003046 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003047
Dan Gohmanfa94b942009-08-12 16:33:09 +00003048 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003049 if (cast<SDivOperator>(&I)->isExact() &&
3050 RHS->getValue().isNonNegative() &&
3051 RHS->getValue().isPowerOf2()) {
3052 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3053 RHS->getValue().exactLogBase2());
3054 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3055 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003056
3057 // -X/C --> X/-C provided the negation doesn't overflow.
3058 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3059 if (isa<Constant>(Sub->getOperand(0)) &&
3060 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003061 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003062 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3063 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003064 }
3065
3066 // If the sign bits of both operands are zero (i.e. we can prove they are
3067 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003068 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003069 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003070 if (MaskedValueIsZero(Op0, Mask)) {
3071 if (MaskedValueIsZero(Op1, Mask)) {
3072 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3073 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3074 }
3075 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003076 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003077 ShiftedInt->getValue().isPowerOf2()) {
3078 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3079 // Safe because the only negative value (1 << Y) can take on is
3080 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3081 // the sign bit set.
3082 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3083 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003084 }
Eli Friedman8be17392009-07-18 09:53:21 +00003085 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003086
3087 return 0;
3088}
3089
3090Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3091 return commonDivTransforms(I);
3092}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003093
Reid Spencer0a783f72006-11-02 01:53:59 +00003094/// This function implements the transforms on rem instructions that work
3095/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3096/// is used by the visitors to those instructions.
3097/// @brief Transforms common to all three rem instructions
3098Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003099 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003100
Chris Lattner50b2ca42008-02-19 06:12:18 +00003101 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3102 if (I.getType()->isFPOrFPVector())
3103 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003104 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003105 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003106 if (isa<UndefValue>(Op1))
3107 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003108
3109 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003110 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3111 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003112
Reid Spencer0a783f72006-11-02 01:53:59 +00003113 return 0;
3114}
3115
3116/// This function implements the transforms common to both integer remainder
3117/// instructions (urem and srem). It is called by the visitors to those integer
3118/// remainder instructions.
3119/// @brief Common integer remainder transforms
3120Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3122
3123 if (Instruction *common = commonRemTransforms(I))
3124 return common;
3125
Dale Johannesened6af242009-01-21 00:35:19 +00003126 // 0 % X == 0 for integer, we don't need to preserve faults!
3127 if (Constant *LHS = dyn_cast<Constant>(Op0))
3128 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003129 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003130
Chris Lattner857e8cd2004-12-12 21:48:58 +00003131 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003132 // X % 0 == undef, we don't need to preserve faults!
3133 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003134 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003135
Chris Lattnera2881962003-02-18 19:28:33 +00003136 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003137 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003138
Chris Lattner97943922006-02-28 05:49:21 +00003139 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3140 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3141 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3142 return R;
3143 } else if (isa<PHINode>(Op0I)) {
3144 if (Instruction *NV = FoldOpIntoPhi(I))
3145 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003146 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003147
3148 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003149 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003150 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003151 }
Chris Lattnera2881962003-02-18 19:28:33 +00003152 }
3153
Reid Spencer0a783f72006-11-02 01:53:59 +00003154 return 0;
3155}
3156
3157Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3158 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3159
3160 if (Instruction *common = commonIRemTransforms(I))
3161 return common;
3162
3163 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3164 // X urem C^2 -> X and C
3165 // Check to see if this is an unsigned remainder with an exact power of 2,
3166 // if so, convert to a bitwise and.
3167 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003168 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003169 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003170 }
3171
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003172 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003173 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3174 if (RHSI->getOpcode() == Instruction::Shl &&
3175 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003176 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003177 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003178 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003179 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003180 }
3181 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003182 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003183
Reid Spencer0a783f72006-11-02 01:53:59 +00003184 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3185 // where C1&C2 are powers of two.
3186 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3187 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3188 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3189 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003190 if ((STO->getValue().isPowerOf2()) &&
3191 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003192 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3193 SI->getName()+".t");
3194 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3195 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003196 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003197 }
3198 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003199 }
3200
Chris Lattner3f5b8772002-05-06 16:14:14 +00003201 return 0;
3202}
3203
Reid Spencer0a783f72006-11-02 01:53:59 +00003204Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3205 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3206
Dan Gohmancff55092007-11-05 23:16:33 +00003207 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003208 if (Instruction *Common = commonIRemTransforms(I))
3209 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003210
Dan Gohman186a6362009-08-12 16:04:34 +00003211 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003212 if (!isa<Constant>(RHSNeg) ||
3213 (isa<ConstantInt>(RHSNeg) &&
3214 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003215 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003216 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003217 I.setOperand(1, RHSNeg);
3218 return &I;
3219 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003220
Dan Gohmancff55092007-11-05 23:16:33 +00003221 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003222 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003223 if (I.getType()->isInteger()) {
3224 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3225 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3226 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003227 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003228 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003229 }
3230
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003231 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003232 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3233 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003234
Nick Lewycky9dce8732008-12-20 16:48:00 +00003235 bool hasNegative = false;
3236 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3237 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3238 if (RHS->getValue().isNegative())
3239 hasNegative = true;
3240
3241 if (hasNegative) {
3242 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003243 for (unsigned i = 0; i != VWidth; ++i) {
3244 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3245 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003246 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003247 else
3248 Elts[i] = RHS;
3249 }
3250 }
3251
Owen Andersonaf7ec972009-07-28 21:19:26 +00003252 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003253 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003254 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003255 I.setOperand(1, NewRHSV);
3256 return &I;
3257 }
3258 }
3259 }
3260
Reid Spencer0a783f72006-11-02 01:53:59 +00003261 return 0;
3262}
3263
3264Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003265 return commonRemTransforms(I);
3266}
3267
Chris Lattner457dd822004-06-09 07:59:58 +00003268// isOneBitSet - Return true if there is exactly one bit set in the specified
3269// constant.
3270static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003271 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003272}
3273
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003274// isHighOnes - Return true if the constant is of the form 1+0+.
3275// This is the same as lowones(~X).
3276static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003277 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003278}
3279
Reid Spencere4d87aa2006-12-23 06:05:41 +00003280/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003281/// are carefully arranged to allow folding of expressions such as:
3282///
3283/// (A < B) | (A > B) --> (A != B)
3284///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003285/// Note that this is only valid if the first and second predicates have the
3286/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003287///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003288/// Three bits are used to represent the condition, as follows:
3289/// 0 A > B
3290/// 1 A == B
3291/// 2 A < B
3292///
3293/// <=> Value Definition
3294/// 000 0 Always false
3295/// 001 1 A > B
3296/// 010 2 A == B
3297/// 011 3 A >= B
3298/// 100 4 A < B
3299/// 101 5 A != B
3300/// 110 6 A <= B
3301/// 111 7 Always true
3302///
3303static unsigned getICmpCode(const ICmpInst *ICI) {
3304 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003305 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003306 case ICmpInst::ICMP_UGT: return 1; // 001
3307 case ICmpInst::ICMP_SGT: return 1; // 001
3308 case ICmpInst::ICMP_EQ: return 2; // 010
3309 case ICmpInst::ICMP_UGE: return 3; // 011
3310 case ICmpInst::ICMP_SGE: return 3; // 011
3311 case ICmpInst::ICMP_ULT: return 4; // 100
3312 case ICmpInst::ICMP_SLT: return 4; // 100
3313 case ICmpInst::ICMP_NE: return 5; // 101
3314 case ICmpInst::ICMP_ULE: return 6; // 110
3315 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003316 // True -> 7
3317 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003318 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003319 return 0;
3320 }
3321}
3322
Evan Cheng8db90722008-10-14 17:15:11 +00003323/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3324/// predicate into a three bit mask. It also returns whether it is an ordered
3325/// predicate by reference.
3326static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3327 isOrdered = false;
3328 switch (CC) {
3329 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3330 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003331 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3332 case FCmpInst::FCMP_UGT: return 1; // 001
3333 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3334 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003335 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3336 case FCmpInst::FCMP_UGE: return 3; // 011
3337 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3338 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003339 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3340 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003341 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3342 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003343 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003344 default:
3345 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003346 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003347 return 0;
3348 }
3349}
3350
Reid Spencere4d87aa2006-12-23 06:05:41 +00003351/// getICmpValue - This is the complement of getICmpCode, which turns an
3352/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003353/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003354/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003355static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003356 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003357 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003358 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003359 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003360 case 1:
3361 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003362 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003363 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003364 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3365 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003366 case 3:
3367 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003368 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003369 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003370 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003371 case 4:
3372 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003373 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003374 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003375 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3376 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003377 case 6:
3378 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003379 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003380 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003381 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003382 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003383 }
3384}
3385
Evan Cheng8db90722008-10-14 17:15:11 +00003386/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3387/// opcode and two operands into either a FCmp instruction. isordered is passed
3388/// in to determine which kind of predicate to use in the new fcmp instruction.
3389static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003390 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003391 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003392 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003393 case 0:
3394 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003395 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003396 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003397 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003398 case 1:
3399 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003400 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003401 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003402 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003403 case 2:
3404 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003405 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003406 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003407 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003408 case 3:
3409 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003410 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003411 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003412 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003413 case 4:
3414 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003415 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003416 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003417 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003418 case 5:
3419 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003420 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003421 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003422 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003423 case 6:
3424 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003425 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003426 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003427 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003428 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003429 }
3430}
3431
Chris Lattnerb9553d62008-11-16 04:55:20 +00003432/// PredicatesFoldable - Return true if both predicates match sign or if at
3433/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003434static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3435 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003436 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3437 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003438}
3439
3440namespace {
3441// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3442struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003443 InstCombiner &IC;
3444 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003445 ICmpInst::Predicate pred;
3446 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3447 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3448 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003449 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003450 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3451 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003452 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3453 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003454 return false;
3455 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003456 Instruction *apply(Instruction &Log) const {
3457 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3458 if (ICI->getOperand(0) != LHS) {
3459 assert(ICI->getOperand(1) == LHS);
3460 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003461 }
3462
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003463 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003464 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003465 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003466 unsigned Code;
3467 switch (Log.getOpcode()) {
3468 case Instruction::And: Code = LHSCode & RHSCode; break;
3469 case Instruction::Or: Code = LHSCode | RHSCode; break;
3470 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003471 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003472 }
3473
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003474 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3475 ICmpInst::isSignedPredicate(ICI->getPredicate());
3476
Owen Andersond672ecb2009-07-03 00:17:18 +00003477 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003478 if (Instruction *I = dyn_cast<Instruction>(RV))
3479 return I;
3480 // Otherwise, it's a constant boolean value...
3481 return IC.ReplaceInstUsesWith(Log, RV);
3482 }
3483};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003484} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003485
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003486// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3487// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003488// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003489Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003490 ConstantInt *OpRHS,
3491 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003492 BinaryOperator &TheAnd) {
3493 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003494 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003495 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003496 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003497
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003498 switch (Op->getOpcode()) {
3499 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003500 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003501 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003502 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003503 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003504 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003505 }
3506 break;
3507 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003508 if (Together == AndRHS) // (X | C) & C --> C
3509 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003510
Chris Lattner6e7ba452005-01-01 16:22:27 +00003511 if (Op->hasOneUse() && Together != OpRHS) {
3512 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003513 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003514 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003515 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003516 }
3517 break;
3518 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003519 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003520 // Adding a one to a single bit bit-field should be turned into an XOR
3521 // of the bit. First thing to check is to see if this AND is with a
3522 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003523 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003524
3525 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003526 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003527 // Ok, at this point, we know that we are masking the result of the
3528 // ADD down to exactly one bit. If the constant we are adding has
3529 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003530 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003531
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003532 // Check to see if any bits below the one bit set in AndRHSV are set.
3533 if ((AddRHS & (AndRHSV-1)) == 0) {
3534 // If not, the only thing that can effect the output of the AND is
3535 // the bit specified by AndRHSV. If that bit is set, the effect of
3536 // the XOR is to toggle the bit. If it is clear, then the ADD has
3537 // no effect.
3538 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3539 TheAnd.setOperand(0, X);
3540 return &TheAnd;
3541 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003542 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003543 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003544 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003545 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 }
3547 }
3548 }
3549 }
3550 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003551
3552 case Instruction::Shl: {
3553 // We know that the AND will not produce any of the bits shifted in, so if
3554 // the anded constant includes them, clear them now!
3555 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003556 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003557 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003558 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003559 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003560
Zhou Sheng290bec52007-03-29 08:15:12 +00003561 if (CI->getValue() == ShlMask) {
3562 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003563 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3564 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003565 TheAnd.setOperand(1, CI);
3566 return &TheAnd;
3567 }
3568 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003569 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003570 case Instruction::LShr:
3571 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003572 // We know that the AND will not produce any of the bits shifted in, so if
3573 // the anded constant includes them, clear them now! This only applies to
3574 // unsigned shifts, because a signed shr may bring in set bits!
3575 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003576 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003577 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003578 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003579 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003580
Zhou Sheng290bec52007-03-29 08:15:12 +00003581 if (CI->getValue() == ShrMask) {
3582 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003583 return ReplaceInstUsesWith(TheAnd, Op);
3584 } else if (CI != AndRHS) {
3585 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3586 return &TheAnd;
3587 }
3588 break;
3589 }
3590 case Instruction::AShr:
3591 // Signed shr.
3592 // See if this is shifting in some sign extension, then masking it out
3593 // with an and.
3594 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003595 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003596 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003597 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003598 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003599 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003600 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003601 // Make the argument unsigned.
3602 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003603 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003604 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003605 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003606 }
3607 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003608 }
3609 return 0;
3610}
3611
Chris Lattner8b170942002-08-09 23:47:40 +00003612
Chris Lattnera96879a2004-09-29 17:40:11 +00003613/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3614/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003615/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3616/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003617/// insert new instructions.
3618Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003619 bool isSigned, bool Inside,
3620 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003621 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003622 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003623 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003624
Chris Lattnera96879a2004-09-29 17:40:11 +00003625 if (Inside) {
3626 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003627 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003628
Reid Spencere4d87aa2006-12-23 06:05:41 +00003629 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003630 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003631 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003632 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003633 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003634 }
3635
3636 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003637 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003638 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003639 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003640 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003641 }
3642
3643 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003644 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003645
Reid Spencere4e40032007-03-21 23:19:50 +00003646 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003647 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003648 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003649 ICmpInst::Predicate pred = (isSigned ?
3650 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003651 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003652 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003653
Reid Spencere4e40032007-03-21 23:19:50 +00003654 // Emit V-Lo >u Hi-1-Lo
3655 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003656 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003657 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003658 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003659 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003660}
3661
Chris Lattner7203e152005-09-18 07:22:02 +00003662// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3663// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3664// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3665// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003666static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003667 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003668 uint32_t BitWidth = Val->getType()->getBitWidth();
3669 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003670
3671 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003672 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003673 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003674 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003675 return true;
3676}
3677
Chris Lattner7203e152005-09-18 07:22:02 +00003678/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3679/// where isSub determines whether the operator is a sub. If we can fold one of
3680/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003681///
3682/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3683/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3684/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3685///
3686/// return (A +/- B).
3687///
3688Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003689 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003690 Instruction &I) {
3691 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3692 if (!LHSI || LHSI->getNumOperands() != 2 ||
3693 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3694
3695 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3696
3697 switch (LHSI->getOpcode()) {
3698 default: return 0;
3699 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003700 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003701 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003702 if ((Mask->getValue().countLeadingZeros() +
3703 Mask->getValue().countPopulation()) ==
3704 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003705 break;
3706
3707 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3708 // part, we don't need any explicit masks to take them out of A. If that
3709 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003710 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003711 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003712 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003713 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003714 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003715 break;
3716 }
3717 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003718 return 0;
3719 case Instruction::Or:
3720 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003721 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003722 if ((Mask->getValue().countLeadingZeros() +
3723 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003724 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003725 break;
3726 return 0;
3727 }
3728
Chris Lattnerc8e77562005-09-18 04:24:45 +00003729 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003730 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3731 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003732}
3733
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003734/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3735Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3736 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003737 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003738 ConstantInt *LHSCst, *RHSCst;
3739 ICmpInst::Predicate LHSCC, RHSCC;
3740
Chris Lattnerea065fb2008-11-16 05:10:52 +00003741 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003742 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003743 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003744 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003745 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003746 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003747
3748 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3749 // where C is a power of 2
3750 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3751 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003752 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003753 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003754 }
3755
3756 // From here on, we only handle:
3757 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3758 if (Val != Val2) return 0;
3759
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003760 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3761 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3762 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3763 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3764 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3765 return 0;
3766
3767 // We can't fold (ugt x, C) & (sgt x, C2).
3768 if (!PredicatesFoldable(LHSCC, RHSCC))
3769 return 0;
3770
3771 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003772 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003773 if (ICmpInst::isSignedPredicate(LHSCC) ||
3774 (ICmpInst::isEquality(LHSCC) &&
3775 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003776 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003777 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003778 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3779
3780 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003781 std::swap(LHS, RHS);
3782 std::swap(LHSCst, RHSCst);
3783 std::swap(LHSCC, RHSCC);
3784 }
3785
3786 // At this point, we know we have have two icmp instructions
3787 // comparing a value against two constants and and'ing the result
3788 // together. Because of the above check, we know that we only have
3789 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3790 // (from the FoldICmpLogical check above), that the two constants
3791 // are not equal and that the larger constant is on the RHS
3792 assert(LHSCst != RHSCst && "Compares not folded above?");
3793
3794 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003795 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003796 case ICmpInst::ICMP_EQ:
3797 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003798 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003799 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3800 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3801 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003802 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003803 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3804 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3805 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3806 return ReplaceInstUsesWith(I, LHS);
3807 }
3808 case ICmpInst::ICMP_NE:
3809 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003810 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003811 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003812 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003813 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003814 break; // (X != 13 & X u< 15) -> no change
3815 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003816 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003817 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003818 break; // (X != 13 & X s< 15) -> no change
3819 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3820 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3821 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3822 return ReplaceInstUsesWith(I, RHS);
3823 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003824 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003825 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003826 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003827 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003828 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003829 }
3830 break; // (X != 13 & X != 15) -> no change
3831 }
3832 break;
3833 case ICmpInst::ICMP_ULT:
3834 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003835 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003836 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3837 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003838 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003839 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3840 break;
3841 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3842 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3843 return ReplaceInstUsesWith(I, LHS);
3844 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3845 break;
3846 }
3847 break;
3848 case ICmpInst::ICMP_SLT:
3849 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003850 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003851 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3852 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003853 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003854 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3855 break;
3856 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3857 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3858 return ReplaceInstUsesWith(I, LHS);
3859 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3860 break;
3861 }
3862 break;
3863 case ICmpInst::ICMP_UGT:
3864 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003865 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003866 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3867 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3868 return ReplaceInstUsesWith(I, RHS);
3869 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3870 break;
3871 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003872 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003873 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003874 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003875 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003876 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003877 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003878 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3879 break;
3880 }
3881 break;
3882 case ICmpInst::ICMP_SGT:
3883 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003884 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003885 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3886 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3887 return ReplaceInstUsesWith(I, RHS);
3888 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3889 break;
3890 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003891 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003892 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003893 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003894 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003895 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003896 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003897 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3898 break;
3899 }
3900 break;
3901 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003902
3903 return 0;
3904}
3905
Chris Lattner42d1be02009-07-23 05:14:02 +00003906Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3907 FCmpInst *RHS) {
3908
3909 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3910 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3911 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3912 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3913 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3914 // If either of the constants are nans, then the whole thing returns
3915 // false.
3916 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003917 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003918 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003919 LHS->getOperand(0), RHS->getOperand(0));
3920 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003921
3922 // Handle vector zeros. This occurs because the canonical form of
3923 // "fcmp ord x,x" is "fcmp ord x, 0".
3924 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3925 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003926 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003927 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003928 return 0;
3929 }
3930
3931 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3932 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3933 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3934
3935
3936 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3937 // Swap RHS operands to match LHS.
3938 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3939 std::swap(Op1LHS, Op1RHS);
3940 }
3941
3942 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3943 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3944 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003945 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00003946
3947 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003948 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003949 if (Op0CC == FCmpInst::FCMP_TRUE)
3950 return ReplaceInstUsesWith(I, RHS);
3951 if (Op1CC == FCmpInst::FCMP_TRUE)
3952 return ReplaceInstUsesWith(I, LHS);
3953
3954 bool Op0Ordered;
3955 bool Op1Ordered;
3956 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3957 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3958 if (Op1Pred == 0) {
3959 std::swap(LHS, RHS);
3960 std::swap(Op0Pred, Op1Pred);
3961 std::swap(Op0Ordered, Op1Ordered);
3962 }
3963 if (Op0Pred == 0) {
3964 // uno && ueq -> uno && (uno || eq) -> ueq
3965 // ord && olt -> ord && (ord && lt) -> olt
3966 if (Op0Ordered == Op1Ordered)
3967 return ReplaceInstUsesWith(I, RHS);
3968
3969 // uno && oeq -> uno && (ord && eq) -> false
3970 // uno && ord -> false
3971 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00003972 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003973 // ord && ueq -> ord && (uno || eq) -> oeq
3974 return cast<Instruction>(getFCmpValue(true, Op1Pred,
3975 Op0LHS, Op0RHS, Context));
3976 }
3977 }
3978
3979 return 0;
3980}
3981
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003982
Chris Lattner7e708292002-06-25 16:13:24 +00003983Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003984 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003985 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003986
Chris Lattnere87597f2004-10-16 18:11:37 +00003987 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003988 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003989
Chris Lattner6e7ba452005-01-01 16:22:27 +00003990 // and X, X = X
3991 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003992 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003993
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003994 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003995 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003996 if (SimplifyDemandedInstructionBits(I))
3997 return &I;
3998 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003999 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004000 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004001 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004002 } else if (isa<ConstantAggregateZero>(Op1)) {
4003 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004004 }
4005 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004006
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004007 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004008 const APInt& AndRHSMask = AndRHS->getValue();
4009 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004010
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004011 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004012 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004013 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004014 Value *Op0LHS = Op0I->getOperand(0);
4015 Value *Op0RHS = Op0I->getOperand(1);
4016 switch (Op0I->getOpcode()) {
4017 case Instruction::Xor:
4018 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004019 // If the mask is only needed on one incoming arm, push it up.
4020 if (Op0I->hasOneUse()) {
4021 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4022 // Not masking anything out for the LHS, move to RHS.
Chris Lattner74381062009-08-30 07:44:24 +00004023 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4024 Op0RHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004025 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004026 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004027 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004028 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004029 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4030 // Not masking anything out for the RHS, move to LHS.
Chris Lattner74381062009-08-30 07:44:24 +00004031 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4032 Op0LHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004033 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004034 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4035 }
4036 }
4037
Chris Lattner6e7ba452005-01-01 16:22:27 +00004038 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004039 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004040 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4041 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4042 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4043 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004044 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004045 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004046 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004047 break;
4048
4049 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004050 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4051 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4052 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4053 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004054 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004055
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004056 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4057 // has 1's for all bits that the subtraction with A might affect.
4058 if (Op0I->hasOneUse()) {
4059 uint32_t BitWidth = AndRHSMask.getBitWidth();
4060 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4061 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4062
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004063 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004064 if (!(A && A->isZero()) && // avoid infinite recursion.
4065 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004066 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004067 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4068 }
4069 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004070 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004071
4072 case Instruction::Shl:
4073 case Instruction::LShr:
4074 // (1 << x) & 1 --> zext(x == 0)
4075 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004076 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004077 Value *NewICmp =
4078 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004079 return new ZExtInst(NewICmp, I.getType());
4080 }
4081 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004082 }
4083
Chris Lattner58403262003-07-23 19:25:52 +00004084 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004085 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004086 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004087 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004088 // If this is an integer truncation or change from signed-to-unsigned, and
4089 // if the source is an and/or with immediate, transform it. This
4090 // frequently occurs for bitfield accesses.
4091 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004092 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004093 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004094 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004095 if (CastOp->getOpcode() == Instruction::And) {
4096 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004097 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4098 // This will fold the two constants together, which may allow
4099 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004100 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004101 CastOp->getOperand(0), I.getType(),
4102 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004103 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004104 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004105 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004106 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004107 } else if (CastOp->getOpcode() == Instruction::Or) {
4108 // Change: and (cast (or X, C1) to T), C2
4109 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004110 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004111 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004112 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004113 return ReplaceInstUsesWith(I, AndRHS);
4114 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004115 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004116 }
Chris Lattner06782f82003-07-23 19:36:21 +00004117 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004118
4119 // Try to fold constant and into select arguments.
4120 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004121 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004122 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004123 if (isa<PHINode>(Op0))
4124 if (Instruction *NV = FoldOpIntoPhi(I))
4125 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004126 }
4127
Dan Gohman186a6362009-08-12 16:04:34 +00004128 Value *Op0NotVal = dyn_castNotVal(Op0);
4129 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004130
Chris Lattner5b62aa72004-06-18 06:07:51 +00004131 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004132 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004133
Misha Brukmancb6267b2004-07-30 12:50:08 +00004134 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004135 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004136 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4137 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004138 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004139 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004140
4141 {
Chris Lattner003b6202007-06-15 05:58:24 +00004142 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004143 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004144 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4145 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004146
4147 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004148 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004149 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004150 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004151 }
4152 }
4153
Dan Gohman4ae51262009-08-12 16:23:25 +00004154 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004155 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4156 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004157
4158 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004159 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004160 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004161 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004162 }
4163 }
Chris Lattner64daab52006-04-01 08:03:55 +00004164
4165 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004166 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004167 if (A == Op1) { // (A^B)&A -> A&(A^B)
4168 I.swapOperands(); // Simplify below
4169 std::swap(Op0, Op1);
4170 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4171 cast<BinaryOperator>(Op0)->swapOperands();
4172 I.swapOperands(); // Simplify below
4173 std::swap(Op0, Op1);
4174 }
4175 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004176
Chris Lattner64daab52006-04-01 08:03:55 +00004177 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004178 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004179 if (B == Op0) { // B&(A^B) -> B&(B^A)
4180 cast<BinaryOperator>(Op1)->swapOperands();
4181 std::swap(A, B);
4182 }
Chris Lattner74381062009-08-30 07:44:24 +00004183 if (A == Op0) // A&(A^B) -> A & ~B
4184 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004185 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004186
4187 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004188 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4189 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004190 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004191 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4192 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004193 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004194 }
4195
Reid Spencere4d87aa2006-12-23 06:05:41 +00004196 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4197 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004198 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004199 return R;
4200
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004201 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4202 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4203 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004204 }
4205
Chris Lattner6fc205f2006-05-05 06:39:07 +00004206 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004207 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4208 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4209 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4210 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004211 if (SrcTy == Op1C->getOperand(0)->getType() &&
4212 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004213 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004214 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4215 I.getType(), TD) &&
4216 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4217 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004218 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4219 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004220 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004221 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004222 }
Chris Lattnere511b742006-11-14 07:46:50 +00004223
4224 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004225 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4226 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4227 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004228 SI0->getOperand(1) == SI1->getOperand(1) &&
4229 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004230 Value *NewOp =
4231 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4232 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004233 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004234 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004235 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004236 }
4237
Evan Cheng8db90722008-10-14 17:15:11 +00004238 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004239 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004240 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4241 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4242 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004243 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004244
Chris Lattner7e708292002-06-25 16:13:24 +00004245 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004246}
4247
Chris Lattner8c34cd22008-10-05 02:13:19 +00004248/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4249/// capable of providing pieces of a bswap. The subexpression provides pieces
4250/// of a bswap if it is proven that each of the non-zero bytes in the output of
4251/// the expression came from the corresponding "byte swapped" byte in some other
4252/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4253/// we know that the expression deposits the low byte of %X into the high byte
4254/// of the bswap result and that all other bytes are zero. This expression is
4255/// accepted, the high byte of ByteValues is set to X to indicate a correct
4256/// match.
4257///
4258/// This function returns true if the match was unsuccessful and false if so.
4259/// On entry to the function the "OverallLeftShift" is a signed integer value
4260/// indicating the number of bytes that the subexpression is later shifted. For
4261/// example, if the expression is later right shifted by 16 bits, the
4262/// OverallLeftShift value would be -2 on entry. This is used to specify which
4263/// byte of ByteValues is actually being set.
4264///
4265/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4266/// byte is masked to zero by a user. For example, in (X & 255), X will be
4267/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4268/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4269/// always in the local (OverallLeftShift) coordinate space.
4270///
4271static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4272 SmallVector<Value*, 8> &ByteValues) {
4273 if (Instruction *I = dyn_cast<Instruction>(V)) {
4274 // If this is an or instruction, it may be an inner node of the bswap.
4275 if (I->getOpcode() == Instruction::Or) {
4276 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4277 ByteValues) ||
4278 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4279 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004280 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004281
4282 // If this is a logical shift by a constant multiple of 8, recurse with
4283 // OverallLeftShift and ByteMask adjusted.
4284 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4285 unsigned ShAmt =
4286 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4287 // Ensure the shift amount is defined and of a byte value.
4288 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4289 return true;
4290
4291 unsigned ByteShift = ShAmt >> 3;
4292 if (I->getOpcode() == Instruction::Shl) {
4293 // X << 2 -> collect(X, +2)
4294 OverallLeftShift += ByteShift;
4295 ByteMask >>= ByteShift;
4296 } else {
4297 // X >>u 2 -> collect(X, -2)
4298 OverallLeftShift -= ByteShift;
4299 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004300 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004301 }
4302
4303 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4304 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4305
4306 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4307 ByteValues);
4308 }
4309
4310 // If this is a logical 'and' with a mask that clears bytes, clear the
4311 // corresponding bytes in ByteMask.
4312 if (I->getOpcode() == Instruction::And &&
4313 isa<ConstantInt>(I->getOperand(1))) {
4314 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4315 unsigned NumBytes = ByteValues.size();
4316 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4317 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4318
4319 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4320 // If this byte is masked out by a later operation, we don't care what
4321 // the and mask is.
4322 if ((ByteMask & (1 << i)) == 0)
4323 continue;
4324
4325 // If the AndMask is all zeros for this byte, clear the bit.
4326 APInt MaskB = AndMask & Byte;
4327 if (MaskB == 0) {
4328 ByteMask &= ~(1U << i);
4329 continue;
4330 }
4331
4332 // If the AndMask is not all ones for this byte, it's not a bytezap.
4333 if (MaskB != Byte)
4334 return true;
4335
4336 // Otherwise, this byte is kept.
4337 }
4338
4339 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4340 ByteValues);
4341 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004342 }
4343
Chris Lattner8c34cd22008-10-05 02:13:19 +00004344 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4345 // the input value to the bswap. Some observations: 1) if more than one byte
4346 // is demanded from this input, then it could not be successfully assembled
4347 // into a byteswap. At least one of the two bytes would not be aligned with
4348 // their ultimate destination.
4349 if (!isPowerOf2_32(ByteMask)) return true;
4350 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004351
Chris Lattner8c34cd22008-10-05 02:13:19 +00004352 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4353 // is demanded, it needs to go into byte 0 of the result. This means that the
4354 // byte needs to be shifted until it lands in the right byte bucket. The
4355 // shift amount depends on the position: if the byte is coming from the high
4356 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4357 // low part, it must be shifted left.
4358 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4359 if (InputByteNo < ByteValues.size()/2) {
4360 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4361 return true;
4362 } else {
4363 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4364 return true;
4365 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004366
4367 // If the destination byte value is already defined, the values are or'd
4368 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004369 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004370 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004371 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004372 return false;
4373}
4374
4375/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4376/// If so, insert the new bswap intrinsic and return it.
4377Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004378 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004379 if (!ITy || ITy->getBitWidth() % 16 ||
4380 // ByteMask only allows up to 32-byte values.
4381 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004382 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004383
4384 /// ByteValues - For each byte of the result, we keep track of which value
4385 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004386 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004387 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004388
4389 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004390 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4391 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004392 return 0;
4393
4394 // Check to see if all of the bytes come from the same value.
4395 Value *V = ByteValues[0];
4396 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4397
4398 // Check to make sure that all of the bytes come from the same value.
4399 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4400 if (ByteValues[i] != V)
4401 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004402 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004403 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004404 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004405 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004406}
4407
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004408/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4409/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4410/// we can simplify this expression to "cond ? C : D or B".
4411static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004412 Value *C, Value *D,
4413 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004414 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004415 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004416 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004417 return 0;
4418
Chris Lattnera6a474d2008-11-16 04:26:55 +00004419 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004420 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004421 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004422 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004423 return SelectInst::Create(Cond, C, B);
4424 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004425 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004426 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004427 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004428 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004429 return 0;
4430}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004431
Chris Lattner69d4ced2008-11-16 05:20:07 +00004432/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4433Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4434 ICmpInst *LHS, ICmpInst *RHS) {
4435 Value *Val, *Val2;
4436 ConstantInt *LHSCst, *RHSCst;
4437 ICmpInst::Predicate LHSCC, RHSCC;
4438
4439 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004440 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004441 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004442 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004443 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004444 return 0;
4445
4446 // From here on, we only handle:
4447 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4448 if (Val != Val2) return 0;
4449
4450 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4451 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4452 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4453 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4454 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4455 return 0;
4456
4457 // We can't fold (ugt x, C) | (sgt x, C2).
4458 if (!PredicatesFoldable(LHSCC, RHSCC))
4459 return 0;
4460
4461 // Ensure that the larger constant is on the RHS.
4462 bool ShouldSwap;
4463 if (ICmpInst::isSignedPredicate(LHSCC) ||
4464 (ICmpInst::isEquality(LHSCC) &&
4465 ICmpInst::isSignedPredicate(RHSCC)))
4466 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4467 else
4468 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4469
4470 if (ShouldSwap) {
4471 std::swap(LHS, RHS);
4472 std::swap(LHSCst, RHSCst);
4473 std::swap(LHSCC, RHSCC);
4474 }
4475
4476 // At this point, we know we have have two icmp instructions
4477 // comparing a value against two constants and or'ing the result
4478 // together. Because of the above check, we know that we only have
4479 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4480 // FoldICmpLogical check above), that the two constants are not
4481 // equal.
4482 assert(LHSCst != RHSCst && "Compares not folded above?");
4483
4484 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004485 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004486 case ICmpInst::ICMP_EQ:
4487 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004488 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004489 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004490 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004491 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004492 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004493 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004494 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004495 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004496 }
4497 break; // (X == 13 | X == 15) -> no change
4498 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4499 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4500 break;
4501 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4502 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4503 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4504 return ReplaceInstUsesWith(I, RHS);
4505 }
4506 break;
4507 case ICmpInst::ICMP_NE:
4508 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004509 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004510 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4511 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4512 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4513 return ReplaceInstUsesWith(I, LHS);
4514 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4515 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4516 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004517 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004518 }
4519 break;
4520 case ICmpInst::ICMP_ULT:
4521 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004522 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004523 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4524 break;
4525 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4526 // If RHSCst is [us]MAXINT, it is always false. Not handling
4527 // this can cause overflow.
4528 if (RHSCst->isMaxValue(false))
4529 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004530 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004531 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004532 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4533 break;
4534 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4535 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4536 return ReplaceInstUsesWith(I, RHS);
4537 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4538 break;
4539 }
4540 break;
4541 case ICmpInst::ICMP_SLT:
4542 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004543 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004544 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4545 break;
4546 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4547 // If RHSCst is [us]MAXINT, it is always false. Not handling
4548 // this can cause overflow.
4549 if (RHSCst->isMaxValue(true))
4550 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004551 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004552 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004553 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4554 break;
4555 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4556 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4557 return ReplaceInstUsesWith(I, RHS);
4558 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4559 break;
4560 }
4561 break;
4562 case ICmpInst::ICMP_UGT:
4563 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004564 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004565 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4566 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4567 return ReplaceInstUsesWith(I, LHS);
4568 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4569 break;
4570 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4571 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004572 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004573 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4574 break;
4575 }
4576 break;
4577 case ICmpInst::ICMP_SGT:
4578 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004579 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004580 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4581 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4582 return ReplaceInstUsesWith(I, LHS);
4583 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4584 break;
4585 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4586 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004587 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004588 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4589 break;
4590 }
4591 break;
4592 }
4593 return 0;
4594}
4595
Chris Lattner5414cc52009-07-23 05:46:22 +00004596Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4597 FCmpInst *RHS) {
4598 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4599 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4600 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4601 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4602 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4603 // If either of the constants are nans, then the whole thing returns
4604 // true.
4605 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004606 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004607
4608 // Otherwise, no need to compare the two constants, compare the
4609 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004610 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004611 LHS->getOperand(0), RHS->getOperand(0));
4612 }
4613
4614 // Handle vector zeros. This occurs because the canonical form of
4615 // "fcmp uno x,x" is "fcmp uno x, 0".
4616 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4617 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004618 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004619 LHS->getOperand(0), RHS->getOperand(0));
4620
4621 return 0;
4622 }
4623
4624 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4625 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4626 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4627
4628 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4629 // Swap RHS operands to match LHS.
4630 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4631 std::swap(Op1LHS, Op1RHS);
4632 }
4633 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4634 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4635 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004636 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004637 Op0LHS, Op0RHS);
4638 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004639 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004640 if (Op0CC == FCmpInst::FCMP_FALSE)
4641 return ReplaceInstUsesWith(I, RHS);
4642 if (Op1CC == FCmpInst::FCMP_FALSE)
4643 return ReplaceInstUsesWith(I, LHS);
4644 bool Op0Ordered;
4645 bool Op1Ordered;
4646 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4647 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4648 if (Op0Ordered == Op1Ordered) {
4649 // If both are ordered or unordered, return a new fcmp with
4650 // or'ed predicates.
4651 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4652 Op0LHS, Op0RHS, Context);
4653 if (Instruction *I = dyn_cast<Instruction>(RV))
4654 return I;
4655 // Otherwise, it's a constant boolean value...
4656 return ReplaceInstUsesWith(I, RV);
4657 }
4658 }
4659 return 0;
4660}
4661
Bill Wendlinga698a472008-12-01 08:23:25 +00004662/// FoldOrWithConstants - This helper function folds:
4663///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004664/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004665///
4666/// into:
4667///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004668/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004669///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004670/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004671Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004672 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004673 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4674 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004675
Bill Wendling286a0542008-12-02 06:24:20 +00004676 Value *V1 = 0;
4677 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004678 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004679
Bill Wendling29976b92008-12-02 06:18:11 +00004680 APInt Xor = CI1->getValue() ^ CI2->getValue();
4681 if (!Xor.isAllOnesValue()) return 0;
4682
Bill Wendling286a0542008-12-02 06:24:20 +00004683 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004684 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004685 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004686 }
4687
4688 return 0;
4689}
4690
Chris Lattner7e708292002-06-25 16:13:24 +00004691Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004692 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004693 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004694
Chris Lattner42593e62007-03-24 23:56:43 +00004695 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004696 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004697
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004698 // or X, X = X
4699 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004700 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004701
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004702 // See if we can simplify any instructions used by the instruction whose sole
4703 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004704 if (SimplifyDemandedInstructionBits(I))
4705 return &I;
4706 if (isa<VectorType>(I.getType())) {
4707 if (isa<ConstantAggregateZero>(Op1)) {
4708 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4709 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4710 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4711 return ReplaceInstUsesWith(I, I.getOperand(1));
4712 }
Chris Lattner42593e62007-03-24 23:56:43 +00004713 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004714
Chris Lattner3f5b8772002-05-06 16:14:14 +00004715 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004716 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004717 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004718 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004719 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004720 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004721 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004722 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004723 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004724 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004725 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004726
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004727 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004728 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004729 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004730 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004731 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004732 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004733 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004734 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004735
4736 // Try to fold constant and into select arguments.
4737 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004738 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004739 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004740 if (isa<PHINode>(Op0))
4741 if (Instruction *NV = FoldOpIntoPhi(I))
4742 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004743 }
4744
Chris Lattner4f637d42006-01-06 17:59:59 +00004745 Value *A = 0, *B = 0;
4746 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004747
Dan Gohman4ae51262009-08-12 16:23:25 +00004748 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004749 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4750 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004751 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004752 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4753 return ReplaceInstUsesWith(I, Op0);
4754
Chris Lattner6423d4c2006-07-10 20:25:24 +00004755 // (A | B) | C and A | (B | C) -> bswap if possible.
4756 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004757 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4758 match(Op1, m_Or(m_Value(), m_Value())) ||
4759 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4760 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004761 if (Instruction *BSwap = MatchBSwap(I))
4762 return BSwap;
4763 }
4764
Chris Lattner6e4c6492005-05-09 04:58:36 +00004765 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004766 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004767 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004768 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004769 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004770 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004771 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004772 }
4773
4774 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004775 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004776 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004777 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004778 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004779 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004780 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004781 }
4782
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004783 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004784 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004785 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4786 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004787 Value *V1 = 0, *V2 = 0, *V3 = 0;
4788 C1 = dyn_cast<ConstantInt>(C);
4789 C2 = dyn_cast<ConstantInt>(D);
4790 if (C1 && C2) { // (A & C1)|(B & C2)
4791 // If we have: ((V + N) & C1) | (V & C2)
4792 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4793 // replace with V+N.
4794 if (C1->getValue() == ~C2->getValue()) {
4795 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004796 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004797 // Add commutes, try both ways.
4798 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4799 return ReplaceInstUsesWith(I, A);
4800 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4801 return ReplaceInstUsesWith(I, A);
4802 }
4803 // Or commutes, try both ways.
4804 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004805 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004806 // Add commutes, try both ways.
4807 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4808 return ReplaceInstUsesWith(I, B);
4809 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4810 return ReplaceInstUsesWith(I, B);
4811 }
4812 }
Chris Lattner044e5332007-04-08 08:01:49 +00004813 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004814 }
4815
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004816 // Check to see if we have any common things being and'ed. If so, find the
4817 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004818 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4819 if (A == B) // (A & C)|(A & D) == A & (C|D)
4820 V1 = A, V2 = C, V3 = D;
4821 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4822 V1 = A, V2 = B, V3 = C;
4823 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4824 V1 = C, V2 = A, V3 = D;
4825 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4826 V1 = C, V2 = A, V3 = B;
4827
4828 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004829 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004830 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004831 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004832 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004833
Dan Gohman1975d032008-10-30 20:40:10 +00004834 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004835 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004836 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004837 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004838 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004839 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004840 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004841 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004842 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004843
Bill Wendlingb01865c2008-11-30 13:52:49 +00004844 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004845 if ((match(C, m_Not(m_Specific(D))) &&
4846 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004847 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004848 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004849 if ((match(A, m_Not(m_Specific(D))) &&
4850 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004851 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004852 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004853 if ((match(C, m_Not(m_Specific(B))) &&
4854 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004855 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004856 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004857 if ((match(A, m_Not(m_Specific(B))) &&
4858 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004859 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004860 }
Chris Lattnere511b742006-11-14 07:46:50 +00004861
4862 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004863 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4864 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4865 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004866 SI0->getOperand(1) == SI1->getOperand(1) &&
4867 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004868 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4869 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004870 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004871 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004872 }
4873 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004874
Bill Wendlingb3833d12008-12-01 01:07:11 +00004875 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004876 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4877 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004878 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004879 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004880 }
4881 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004882 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4883 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004884 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004885 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004886 }
4887
Dan Gohman4ae51262009-08-12 16:23:25 +00004888 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004889 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004890 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004891 } else {
4892 A = 0;
4893 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004894 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004895 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004896 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004897 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004898
Misha Brukmancb6267b2004-07-30 12:50:08 +00004899 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004900 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004901 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004902 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004903 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004904 }
Chris Lattnera2881962003-02-18 19:28:33 +00004905
Reid Spencere4d87aa2006-12-23 06:05:41 +00004906 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4907 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004908 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004909 return R;
4910
Chris Lattner69d4ced2008-11-16 05:20:07 +00004911 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4912 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4913 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004914 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004915
4916 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004917 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004918 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004919 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004920 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4921 !isa<ICmpInst>(Op1C->getOperand(0))) {
4922 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004923 if (SrcTy == Op1C->getOperand(0)->getType() &&
4924 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004925 // Only do this if the casts both really cause code to be
4926 // generated.
4927 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4928 I.getType(), TD) &&
4929 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4930 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004931 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4932 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004933 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004934 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004935 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004936 }
Chris Lattner99c65742007-10-24 05:38:08 +00004937 }
4938
4939
4940 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4941 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00004942 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4943 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4944 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004945 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004946
Chris Lattner7e708292002-06-25 16:13:24 +00004947 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004948}
4949
Dan Gohman844731a2008-05-13 00:00:25 +00004950namespace {
4951
Chris Lattnerc317d392004-02-16 01:20:27 +00004952// XorSelf - Implements: X ^ X --> 0
4953struct XorSelf {
4954 Value *RHS;
4955 XorSelf(Value *rhs) : RHS(rhs) {}
4956 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4957 Instruction *apply(BinaryOperator &Xor) const {
4958 return &Xor;
4959 }
4960};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004961
Dan Gohman844731a2008-05-13 00:00:25 +00004962}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004963
Chris Lattner7e708292002-06-25 16:13:24 +00004964Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004965 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004966 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004967
Evan Chengd34af782008-03-25 20:07:13 +00004968 if (isa<UndefValue>(Op1)) {
4969 if (isa<UndefValue>(Op0))
4970 // Handle undef ^ undef -> 0 special case. This is a common
4971 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00004972 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004973 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004974 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004975
Chris Lattnerc317d392004-02-16 01:20:27 +00004976 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00004977 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004978 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00004979 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004980 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004981
4982 // See if we can simplify any instructions used by the instruction whose sole
4983 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004984 if (SimplifyDemandedInstructionBits(I))
4985 return &I;
4986 if (isa<VectorType>(I.getType()))
4987 if (isa<ConstantAggregateZero>(Op1))
4988 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00004989
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004990 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00004991 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004992 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4993 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4994 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4995 if (Op0I->getOpcode() == Instruction::And ||
4996 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00004997 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4998 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00004999 Value *NotY =
5000 Builder->CreateNot(Op0I->getOperand(1),
5001 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005002 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005003 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005004 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005005 }
5006 }
5007 }
5008 }
5009
5010
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005011 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005012 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005013 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005014 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005015 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005016 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005017
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005018 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005019 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005020 FCI->getOperand(0), FCI->getOperand(1));
5021 }
5022
Nick Lewycky517e1f52008-05-31 19:01:33 +00005023 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5024 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5025 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5026 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5027 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005028 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5029 (RHS == ConstantExpr::getCast(Opcode,
5030 ConstantInt::getTrue(*Context),
5031 Op0C->getDestTy()))) {
5032 CI->setPredicate(CI->getInversePredicate());
5033 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005034 }
5035 }
5036 }
5037 }
5038
Reid Spencere4d87aa2006-12-23 06:05:41 +00005039 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005040 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005041 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5042 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005043 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5044 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005045 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005046 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005047 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005048
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005049 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005050 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005051 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005052 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005053 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005054 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005055 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005056 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005057 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005058 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005059 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005060 Constant *C = ConstantInt::get(*Context,
5061 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005062 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005063
Chris Lattner7c4049c2004-01-12 19:35:11 +00005064 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005065 } else if (Op0I->getOpcode() == Instruction::Or) {
5066 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005067 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005068 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005069 // Anything in both C1 and C2 is known to be zero, remove it from
5070 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005071 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5072 NewRHS = ConstantExpr::getAnd(NewRHS,
5073 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005074 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005075 I.setOperand(0, Op0I->getOperand(0));
5076 I.setOperand(1, NewRHS);
5077 return &I;
5078 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005079 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005080 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005081 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005082
5083 // Try to fold constant and into select arguments.
5084 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005085 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005086 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005087 if (isa<PHINode>(Op0))
5088 if (Instruction *NV = FoldOpIntoPhi(I))
5089 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005090 }
5091
Dan Gohman186a6362009-08-12 16:04:34 +00005092 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005093 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005094 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005095
Dan Gohman186a6362009-08-12 16:04:34 +00005096 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005097 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005098 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005099
Chris Lattner318bf792007-03-18 22:51:34 +00005100
5101 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5102 if (Op1I) {
5103 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005104 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005105 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005106 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005107 I.swapOperands();
5108 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005109 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005110 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005111 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005112 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005113 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005114 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005115 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005116 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005117 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005118 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005119 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005120 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005121 std::swap(A, B);
5122 }
Chris Lattner318bf792007-03-18 22:51:34 +00005123 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005124 I.swapOperands(); // Simplified below.
5125 std::swap(Op0, Op1);
5126 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005127 }
Chris Lattner318bf792007-03-18 22:51:34 +00005128 }
5129
5130 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5131 if (Op0I) {
5132 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005133 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005134 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005135 if (A == Op1) // (B|A)^B == (A|B)^B
5136 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005137 if (B == Op1) // (A|B)^B == A & ~B
5138 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005139 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005140 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005141 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005142 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005143 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005144 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005145 if (A == Op1) // (A&B)^A -> (B&A)^A
5146 std::swap(A, B);
5147 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005148 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005149 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005150 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005151 }
Chris Lattner318bf792007-03-18 22:51:34 +00005152 }
5153
5154 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5155 if (Op0I && Op1I && Op0I->isShift() &&
5156 Op0I->getOpcode() == Op1I->getOpcode() &&
5157 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5158 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005159 Value *NewOp =
5160 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5161 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005162 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005163 Op1I->getOperand(1));
5164 }
5165
5166 if (Op0I && Op1I) {
5167 Value *A, *B, *C, *D;
5168 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005169 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5170 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005171 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005172 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005173 }
5174 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005175 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5176 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005177 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005178 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005179 }
5180
5181 // (A & B)^(C & D)
5182 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005183 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5184 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005185 // (X & Y)^(X & Y) -> (Y^Z) & X
5186 Value *X = 0, *Y = 0, *Z = 0;
5187 if (A == C)
5188 X = A, Y = B, Z = D;
5189 else if (A == D)
5190 X = A, Y = B, Z = C;
5191 else if (B == C)
5192 X = B, Y = A, Z = D;
5193 else if (B == D)
5194 X = B, Y = A, Z = C;
5195
5196 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005197 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005198 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005199 }
5200 }
5201 }
5202
Reid Spencere4d87aa2006-12-23 06:05:41 +00005203 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5204 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005205 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005206 return R;
5207
Chris Lattner6fc205f2006-05-05 06:39:07 +00005208 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005209 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005210 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005211 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5212 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005213 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005214 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005215 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5216 I.getType(), TD) &&
5217 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5218 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005219 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5220 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005221 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005222 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005223 }
Chris Lattner99c65742007-10-24 05:38:08 +00005224 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005225
Chris Lattner7e708292002-06-25 16:13:24 +00005226 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005227}
5228
Owen Andersond672ecb2009-07-03 00:17:18 +00005229static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005230 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005231 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005232}
Chris Lattnera96879a2004-09-29 17:40:11 +00005233
Dan Gohman6de29f82009-06-15 22:12:54 +00005234static bool HasAddOverflow(ConstantInt *Result,
5235 ConstantInt *In1, ConstantInt *In2,
5236 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005237 if (IsSigned)
5238 if (In2->getValue().isNegative())
5239 return Result->getValue().sgt(In1->getValue());
5240 else
5241 return Result->getValue().slt(In1->getValue());
5242 else
5243 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005244}
5245
Dan Gohman6de29f82009-06-15 22:12:54 +00005246/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005247/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005248static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005249 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005250 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005251 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005252
Dan Gohman6de29f82009-06-15 22:12:54 +00005253 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5254 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005255 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005256 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5257 ExtractElement(In1, Idx, Context),
5258 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005259 IsSigned))
5260 return true;
5261 }
5262 return false;
5263 }
5264
5265 return HasAddOverflow(cast<ConstantInt>(Result),
5266 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5267 IsSigned);
5268}
5269
5270static bool HasSubOverflow(ConstantInt *Result,
5271 ConstantInt *In1, ConstantInt *In2,
5272 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005273 if (IsSigned)
5274 if (In2->getValue().isNegative())
5275 return Result->getValue().slt(In1->getValue());
5276 else
5277 return Result->getValue().sgt(In1->getValue());
5278 else
5279 return Result->getValue().ugt(In1->getValue());
5280}
5281
Dan Gohman6de29f82009-06-15 22:12:54 +00005282/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5283/// overflowed for this type.
5284static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005285 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005286 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005287 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005288
5289 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5290 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005291 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005292 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5293 ExtractElement(In1, Idx, Context),
5294 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005295 IsSigned))
5296 return true;
5297 }
5298 return false;
5299 }
5300
5301 return HasSubOverflow(cast<ConstantInt>(Result),
5302 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5303 IsSigned);
5304}
5305
Chris Lattner574da9b2005-01-13 20:14:25 +00005306/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5307/// code necessary to compute the offset from the base pointer (without adding
5308/// in the base pointer). Return the result as a signed integer of intptr size.
5309static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005310 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005311 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005312 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005313 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005314
5315 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005316 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005317 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005318
Gabor Greif177dd3f2008-06-12 21:37:33 +00005319 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5320 ++i, ++GTI) {
5321 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005322 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005323 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5324 if (OpC->isZero()) continue;
5325
5326 // Handle a struct index, which adds its field offset to the pointer.
5327 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5328 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5329
Chris Lattner74381062009-08-30 07:44:24 +00005330 Result = IC.Builder->CreateAdd(Result,
5331 ConstantInt::get(IntPtrTy, Size),
5332 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005333 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005334 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005335
Owen Andersoneed707b2009-07-24 23:12:02 +00005336 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005337 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005338 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5339 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005340 // Emit an add instruction.
5341 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005342 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005343 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005344 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005345 if (Op->getType() != IntPtrTy)
5346 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005347 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005348 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005349 // We'll let instcombine(mul) convert this to a shl if possible.
5350 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005351 }
5352
5353 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005354 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005355 }
5356 return Result;
5357}
5358
Chris Lattner10c0d912008-04-22 02:53:33 +00005359
Dan Gohman8f080f02009-07-17 22:16:21 +00005360/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5361/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5362/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5363/// be complex, and scales are involved. The above expression would also be
5364/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5365/// This later form is less amenable to optimization though, and we are allowed
5366/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005367///
5368/// If we can't emit an optimized form for this expression, this returns null.
5369///
5370static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5371 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005372 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005373 gep_type_iterator GTI = gep_type_begin(GEP);
5374
5375 // Check to see if this gep only has a single variable index. If so, and if
5376 // any constant indices are a multiple of its scale, then we can compute this
5377 // in terms of the scale of the variable index. For example, if the GEP
5378 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5379 // because the expression will cross zero at the same point.
5380 unsigned i, e = GEP->getNumOperands();
5381 int64_t Offset = 0;
5382 for (i = 1; i != e; ++i, ++GTI) {
5383 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5384 // Compute the aggregate offset of constant indices.
5385 if (CI->isZero()) continue;
5386
5387 // Handle a struct index, which adds its field offset to the pointer.
5388 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5389 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5390 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005391 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005392 Offset += Size*CI->getSExtValue();
5393 }
5394 } else {
5395 // Found our variable index.
5396 break;
5397 }
5398 }
5399
5400 // If there are no variable indices, we must have a constant offset, just
5401 // evaluate it the general way.
5402 if (i == e) return 0;
5403
5404 Value *VariableIdx = GEP->getOperand(i);
5405 // Determine the scale factor of the variable element. For example, this is
5406 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005407 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005408
5409 // Verify that there are no other variable indices. If so, emit the hard way.
5410 for (++i, ++GTI; i != e; ++i, ++GTI) {
5411 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5412 if (!CI) return 0;
5413
5414 // Compute the aggregate offset of constant indices.
5415 if (CI->isZero()) continue;
5416
5417 // Handle a struct index, which adds its field offset to the pointer.
5418 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5419 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5420 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005421 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005422 Offset += Size*CI->getSExtValue();
5423 }
5424 }
5425
5426 // Okay, we know we have a single variable index, which must be a
5427 // pointer/array/vector index. If there is no offset, life is simple, return
5428 // the index.
5429 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5430 if (Offset == 0) {
5431 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5432 // we don't need to bother extending: the extension won't affect where the
5433 // computation crosses zero.
5434 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005435 VariableIdx = new TruncInst(VariableIdx,
5436 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005437 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005438 return VariableIdx;
5439 }
5440
5441 // Otherwise, there is an index. The computation we will do will be modulo
5442 // the pointer size, so get it.
5443 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5444
5445 Offset &= PtrSizeMask;
5446 VariableScale &= PtrSizeMask;
5447
5448 // To do this transformation, any constant index must be a multiple of the
5449 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5450 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5451 // multiple of the variable scale.
5452 int64_t NewOffs = Offset / (int64_t)VariableScale;
5453 if (Offset != NewOffs*(int64_t)VariableScale)
5454 return 0;
5455
5456 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005457 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005458 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005459 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005460 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005461 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005462 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005463 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005464}
5465
5466
Reid Spencere4d87aa2006-12-23 06:05:41 +00005467/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005468/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005469Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005470 ICmpInst::Predicate Cond,
5471 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005472 // Look through bitcasts.
5473 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5474 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005475
Chris Lattner574da9b2005-01-13 20:14:25 +00005476 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005477 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005478 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005479 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005480 // know pointers can't overflow since the gep is inbounds. See if we can
5481 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005482 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5483
5484 // If not, synthesize the offset the hard way.
5485 if (Offset == 0)
5486 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005487 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005488 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005489 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005490 // If the base pointers are different, but the indices are the same, just
5491 // compare the base pointer.
5492 if (PtrBase != GEPRHS->getOperand(0)) {
5493 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005494 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005495 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005496 if (IndicesTheSame)
5497 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5498 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5499 IndicesTheSame = false;
5500 break;
5501 }
5502
5503 // If all indices are the same, just compare the base pointers.
5504 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005505 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005506 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005507
5508 // Otherwise, the base pointers are different and the indices are
5509 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005510 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005511 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005512
Chris Lattnere9d782b2005-01-13 22:25:21 +00005513 // If one of the GEPs has all zero indices, recurse.
5514 bool AllZeros = true;
5515 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5516 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5517 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5518 AllZeros = false;
5519 break;
5520 }
5521 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005522 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5523 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005524
5525 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005526 AllZeros = true;
5527 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5528 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5529 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5530 AllZeros = false;
5531 break;
5532 }
5533 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005534 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005535
Chris Lattner4401c9c2005-01-14 00:20:05 +00005536 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5537 // If the GEPs only differ by one index, compare it.
5538 unsigned NumDifferences = 0; // Keep track of # differences.
5539 unsigned DiffOperand = 0; // The operand that differs.
5540 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5541 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005542 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5543 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005544 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005545 NumDifferences = 2;
5546 break;
5547 } else {
5548 if (NumDifferences++) break;
5549 DiffOperand = i;
5550 }
5551 }
5552
5553 if (NumDifferences == 0) // SAME GEP?
5554 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005555 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005556 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005557
Chris Lattner4401c9c2005-01-14 00:20:05 +00005558 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005559 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5560 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005561 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005562 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005563 }
5564 }
5565
Reid Spencere4d87aa2006-12-23 06:05:41 +00005566 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005567 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005568 if (TD &&
5569 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005570 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5571 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5572 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5573 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005574 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005575 }
5576 }
5577 return 0;
5578}
5579
Chris Lattnera5406232008-05-19 20:18:56 +00005580/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5581///
5582Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5583 Instruction *LHSI,
5584 Constant *RHSC) {
5585 if (!isa<ConstantFP>(RHSC)) return 0;
5586 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5587
5588 // Get the width of the mantissa. We don't want to hack on conversions that
5589 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005590 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005591 if (MantissaWidth == -1) return 0; // Unknown.
5592
5593 // Check to see that the input is converted from an integer type that is small
5594 // enough that preserves all bits. TODO: check here for "known" sign bits.
5595 // 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 +00005596 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005597
5598 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005599 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5600 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005601 ++InputSize;
5602
5603 // If the conversion would lose info, don't hack on this.
5604 if ((int)InputSize > MantissaWidth)
5605 return 0;
5606
5607 // Otherwise, we can potentially simplify the comparison. We know that it
5608 // will always come through as an integer value and we know the constant is
5609 // not a NAN (it would have been previously simplified).
5610 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5611
5612 ICmpInst::Predicate Pred;
5613 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005614 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005615 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005616 case FCmpInst::FCMP_OEQ:
5617 Pred = ICmpInst::ICMP_EQ;
5618 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005619 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005620 case FCmpInst::FCMP_OGT:
5621 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5622 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005623 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005624 case FCmpInst::FCMP_OGE:
5625 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5626 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005627 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005628 case FCmpInst::FCMP_OLT:
5629 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5630 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005631 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005632 case FCmpInst::FCMP_OLE:
5633 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5634 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005635 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005636 case FCmpInst::FCMP_ONE:
5637 Pred = ICmpInst::ICMP_NE;
5638 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005639 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005640 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005641 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005642 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005643 }
5644
5645 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5646
5647 // Now we know that the APFloat is a normal number, zero or inf.
5648
Chris Lattner85162782008-05-20 03:50:52 +00005649 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005650 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005651 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005652
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005653 if (!LHSUnsigned) {
5654 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5655 // and large values.
5656 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5657 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5658 APFloat::rmNearestTiesToEven);
5659 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5660 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5661 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005662 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5663 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005664 }
5665 } else {
5666 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5667 // +INF and large values.
5668 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5669 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5670 APFloat::rmNearestTiesToEven);
5671 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5672 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5673 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005674 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5675 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005676 }
Chris Lattnera5406232008-05-19 20:18:56 +00005677 }
5678
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005679 if (!LHSUnsigned) {
5680 // See if the RHS value is < SignedMin.
5681 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5682 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5683 APFloat::rmNearestTiesToEven);
5684 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5685 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5686 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005687 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5688 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005689 }
Chris Lattnera5406232008-05-19 20:18:56 +00005690 }
5691
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005692 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5693 // [0, UMAX], but it may still be fractional. See if it is fractional by
5694 // casting the FP value to the integer value and back, checking for equality.
5695 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005696 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005697 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5698 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005699 if (!RHS.isZero()) {
5700 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005701 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5702 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005703 if (!Equal) {
5704 // If we had a comparison against a fractional value, we have to adjust
5705 // the compare predicate and sometimes the value. RHSC is rounded towards
5706 // zero at this point.
5707 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005708 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005709 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005710 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005711 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005712 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005713 case ICmpInst::ICMP_ULE:
5714 // (float)int <= 4.4 --> int <= 4
5715 // (float)int <= -4.4 --> false
5716 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005717 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005718 break;
5719 case ICmpInst::ICMP_SLE:
5720 // (float)int <= 4.4 --> int <= 4
5721 // (float)int <= -4.4 --> int < -4
5722 if (RHS.isNegative())
5723 Pred = ICmpInst::ICMP_SLT;
5724 break;
5725 case ICmpInst::ICMP_ULT:
5726 // (float)int < -4.4 --> false
5727 // (float)int < 4.4 --> int <= 4
5728 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005729 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005730 Pred = ICmpInst::ICMP_ULE;
5731 break;
5732 case ICmpInst::ICMP_SLT:
5733 // (float)int < -4.4 --> int < -4
5734 // (float)int < 4.4 --> int <= 4
5735 if (!RHS.isNegative())
5736 Pred = ICmpInst::ICMP_SLE;
5737 break;
5738 case ICmpInst::ICMP_UGT:
5739 // (float)int > 4.4 --> int > 4
5740 // (float)int > -4.4 --> true
5741 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005742 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005743 break;
5744 case ICmpInst::ICMP_SGT:
5745 // (float)int > 4.4 --> int > 4
5746 // (float)int > -4.4 --> int >= -4
5747 if (RHS.isNegative())
5748 Pred = ICmpInst::ICMP_SGE;
5749 break;
5750 case ICmpInst::ICMP_UGE:
5751 // (float)int >= -4.4 --> true
5752 // (float)int >= 4.4 --> int > 4
5753 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005754 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005755 Pred = ICmpInst::ICMP_UGT;
5756 break;
5757 case ICmpInst::ICMP_SGE:
5758 // (float)int >= -4.4 --> int >= -4
5759 // (float)int >= 4.4 --> int > 4
5760 if (!RHS.isNegative())
5761 Pred = ICmpInst::ICMP_SGT;
5762 break;
5763 }
Chris Lattnera5406232008-05-19 20:18:56 +00005764 }
5765 }
5766
5767 // Lower this FP comparison into an appropriate integer version of the
5768 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005769 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005770}
5771
Reid Spencere4d87aa2006-12-23 06:05:41 +00005772Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5773 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005774 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005775
Chris Lattner58e97462007-01-14 19:42:17 +00005776 // Fold trivial predicates.
5777 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005778 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005779 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005780 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005781
5782 // Simplify 'fcmp pred X, X'
5783 if (Op0 == Op1) {
5784 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005785 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005786 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5787 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5788 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson5defacc2009-07-31 17:39:07 +00005789 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005790 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5791 case FCmpInst::FCMP_OLT: // True if ordered and less than
5792 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson5defacc2009-07-31 17:39:07 +00005793 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005794
5795 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5796 case FCmpInst::FCMP_ULT: // True if unordered or less than
5797 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5798 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5799 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5800 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005801 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005802 return &I;
5803
5804 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5805 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5806 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5807 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5808 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5809 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005810 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005811 return &I;
5812 }
5813 }
5814
Reid Spencere4d87aa2006-12-23 06:05:41 +00005815 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005816 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Chris Lattnere87597f2004-10-16 18:11:37 +00005817
Reid Spencere4d87aa2006-12-23 06:05:41 +00005818 // Handle fcmp with constant RHS
5819 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005820 // If the constant is a nan, see if we can fold the comparison based on it.
5821 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5822 if (CFP->getValueAPF().isNaN()) {
5823 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005824 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005825 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5826 "Comparison must be either ordered or unordered!");
5827 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005828 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005829 }
5830 }
5831
Reid Spencere4d87aa2006-12-23 06:05:41 +00005832 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5833 switch (LHSI->getOpcode()) {
5834 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005835 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5836 // block. If in the same block, we're encouraging jump threading. If
5837 // not, we are just pessimizing the code by making an i1 phi.
5838 if (LHSI->getParent() == I.getParent())
5839 if (Instruction *NV = FoldOpIntoPhi(I))
5840 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005841 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005842 case Instruction::SIToFP:
5843 case Instruction::UIToFP:
5844 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5845 return NV;
5846 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005847 case Instruction::Select:
5848 // If either operand of the select is a constant, we can fold the
5849 // comparison into the select arms, which will cause one to be
5850 // constant folded and the select turned into a bitwise or.
5851 Value *Op1 = 0, *Op2 = 0;
5852 if (LHSI->hasOneUse()) {
5853 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5854 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005855 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005856 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005857 Op2 = Builder->CreateFCmp(I.getPredicate(),
5858 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005859 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5860 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005861 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005862 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005863 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5864 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005865 }
5866 }
5867
5868 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005869 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005870 break;
5871 }
5872 }
5873
5874 return Changed ? &I : 0;
5875}
5876
5877Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5878 bool Changed = SimplifyCompare(I);
5879 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5880 const Type *Ty = Op0->getType();
5881
5882 // icmp X, X
5883 if (Op0 == Op1)
Owen Anderson1d0be152009-08-13 21:58:54 +00005884 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005885 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005886
5887 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005888 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005889
Reid Spencere4d87aa2006-12-23 06:05:41 +00005890 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005891 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005892 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5893 isa<ConstantPointerNull>(Op0)) &&
5894 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005895 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00005896 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005897 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005898
Reid Spencere4d87aa2006-12-23 06:05:41 +00005899 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005900 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005901 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005902 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005903 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005904 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005905 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005906 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005907 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005908 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005909
Reid Spencere4d87aa2006-12-23 06:05:41 +00005910 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005911 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005912 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005913 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00005914 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005915 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005916 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005917 case ICmpInst::ICMP_SGT:
5918 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005919 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005920 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00005921 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005922 return BinaryOperator::CreateAnd(Not, Op0);
5923 }
5924 case ICmpInst::ICMP_UGE:
5925 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5926 // FALL THROUGH
5927 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00005928 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005929 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005930 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005931 case ICmpInst::ICMP_SGE:
5932 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5933 // FALL THROUGH
5934 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00005935 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005936 return BinaryOperator::CreateOr(Not, Op0);
5937 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005938 }
Chris Lattner8b170942002-08-09 23:47:40 +00005939 }
5940
Dan Gohman1c8491e2009-04-25 17:12:48 +00005941 unsigned BitWidth = 0;
5942 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00005943 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5944 else if (Ty->isIntOrIntVector())
5945 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00005946
5947 bool isSignBit = false;
5948
Dan Gohman81b28ce2008-09-16 18:46:06 +00005949 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005950 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005951 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005952
Chris Lattnerb6566012008-01-05 01:18:20 +00005953 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5954 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005955 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00005956 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005957 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005958 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005959
Dan Gohman81b28ce2008-09-16 18:46:06 +00005960 // If we have an icmp le or icmp ge instruction, turn it into the
5961 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5962 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005963 switch (I.getPredicate()) {
5964 default: break;
5965 case ICmpInst::ICMP_ULE:
5966 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005967 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005968 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005969 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005970 case ICmpInst::ICMP_SLE:
5971 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005972 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005973 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005974 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005975 case ICmpInst::ICMP_UGE:
5976 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005977 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005978 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005979 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005980 case ICmpInst::ICMP_SGE:
5981 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005982 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005983 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005984 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005985 }
5986
Chris Lattner183661e2008-07-11 05:40:05 +00005987 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005988 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005989 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00005990 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5991 }
5992
5993 // See if we can fold the comparison based on range information we can get
5994 // by checking whether bits are known to be zero or one in the input.
5995 if (BitWidth != 0) {
5996 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
5997 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
5998
5999 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006000 isSignBit ? APInt::getSignBit(BitWidth)
6001 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006002 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006003 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006004 if (SimplifyDemandedBits(I.getOperandUse(1),
6005 APInt::getAllOnesValue(BitWidth),
6006 Op1KnownZero, Op1KnownOne, 0))
6007 return &I;
6008
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006009 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006010 // in. Compute the Min, Max and RHS values based on the known bits. For the
6011 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006012 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6013 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6014 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6015 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6016 Op0Min, Op0Max);
6017 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6018 Op1Min, Op1Max);
6019 } else {
6020 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6021 Op0Min, Op0Max);
6022 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6023 Op1Min, Op1Max);
6024 }
6025
Chris Lattner183661e2008-07-11 05:40:05 +00006026 // If Min and Max are known to be the same, then SimplifyDemandedBits
6027 // figured out that the LHS is a constant. Just constant fold this now so
6028 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006029 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006030 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006031 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006032 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006033 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006034 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006035
Chris Lattner183661e2008-07-11 05:40:05 +00006036 // Based on the range information we know about the LHS, see if we can
6037 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006038 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006039 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006040 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006041 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006042 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006043 break;
6044 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006045 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006046 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006047 break;
6048 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006049 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006050 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006051 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006052 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006053 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006054 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006055 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6056 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006057 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006058 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006059
6060 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6061 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006062 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006063 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006064 }
Chris Lattner84dff672008-07-11 05:08:55 +00006065 break;
6066 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006067 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006068 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006069 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006070 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006071
6072 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006073 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006074 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6075 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006076 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006077 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006078
6079 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6080 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006081 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006082 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006083 }
Chris Lattner84dff672008-07-11 05:08:55 +00006084 break;
6085 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006086 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006087 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006088 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006089 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006090 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006091 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006092 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6093 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006094 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006095 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006096 }
Chris Lattner84dff672008-07-11 05:08:55 +00006097 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006098 case ICmpInst::ICMP_SGT:
6099 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006100 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006101 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006102 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006103
6104 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006105 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006106 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6107 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006108 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006109 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006110 }
6111 break;
6112 case ICmpInst::ICMP_SGE:
6113 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6114 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006115 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006116 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006117 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006118 break;
6119 case ICmpInst::ICMP_SLE:
6120 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6121 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006122 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006123 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006124 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006125 break;
6126 case ICmpInst::ICMP_UGE:
6127 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6128 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006129 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006130 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006131 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006132 break;
6133 case ICmpInst::ICMP_ULE:
6134 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6135 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006136 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006137 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006138 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006139 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006140 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006141
6142 // Turn a signed comparison into an unsigned one if both operands
6143 // are known to have the same sign.
6144 if (I.isSignedPredicate() &&
6145 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6146 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006147 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006148 }
6149
6150 // Test if the ICmpInst instruction is used exclusively by a select as
6151 // part of a minimum or maximum operation. If so, refrain from doing
6152 // any other folding. This helps out other analyses which understand
6153 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6154 // and CodeGen. And in this case, at least one of the comparison
6155 // operands has at least one user besides the compare (the select),
6156 // which would often largely negate the benefit of folding anyway.
6157 if (I.hasOneUse())
6158 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6159 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6160 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6161 return 0;
6162
6163 // See if we are doing a comparison between a constant and an instruction that
6164 // can be folded into the comparison.
6165 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006166 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006167 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006168 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006169 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006170 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6171 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006172 }
6173
Chris Lattner01deb9d2007-04-03 17:43:25 +00006174 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006175 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6176 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6177 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006178 case Instruction::GetElementPtr:
6179 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006180 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006181 bool isAllZeros = true;
6182 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6183 if (!isa<Constant>(LHSI->getOperand(i)) ||
6184 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6185 isAllZeros = false;
6186 break;
6187 }
6188 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006189 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006190 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006191 }
6192 break;
6193
Chris Lattner6970b662005-04-23 15:31:55 +00006194 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006195 // Only fold icmp into the PHI if the phi and fcmp are in the same
6196 // block. If in the same block, we're encouraging jump threading. If
6197 // not, we are just pessimizing the code by making an i1 phi.
6198 if (LHSI->getParent() == I.getParent())
6199 if (Instruction *NV = FoldOpIntoPhi(I))
6200 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006201 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006202 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006203 // If either operand of the select is a constant, we can fold the
6204 // comparison into the select arms, which will cause one to be
6205 // constant folded and the select turned into a bitwise or.
6206 Value *Op1 = 0, *Op2 = 0;
6207 if (LHSI->hasOneUse()) {
6208 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6209 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006210 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006211 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006212 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6213 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006214 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6215 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006216 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006217 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006218 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6219 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006220 }
6221 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006222
Chris Lattner6970b662005-04-23 15:31:55 +00006223 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006224 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006225 break;
6226 }
Chris Lattner4802d902007-04-06 18:57:34 +00006227 case Instruction::Malloc:
6228 // If we have (malloc != null), and if the malloc has a single use, we
6229 // can assume it is successful and remove the malloc.
6230 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006231 Worklist.Add(LHSI);
Owen Anderson1d0be152009-08-13 21:58:54 +00006232 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006233 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006234 }
6235 break;
6236 }
Chris Lattner6970b662005-04-23 15:31:55 +00006237 }
6238
Reid Spencere4d87aa2006-12-23 06:05:41 +00006239 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006240 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006241 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006242 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006243 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006244 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6245 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006246 return NI;
6247
Reid Spencere4d87aa2006-12-23 06:05:41 +00006248 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006249 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6250 // now.
6251 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6252 if (isa<PointerType>(Op0->getType()) &&
6253 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006254 // We keep moving the cast from the left operand over to the right
6255 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006256 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006257
Chris Lattner57d86372007-01-06 01:45:59 +00006258 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6259 // so eliminate it as well.
6260 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6261 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006262
Chris Lattnerde90b762003-11-03 04:25:02 +00006263 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006264 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006265 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006266 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006267 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006268 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006269 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006270 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006271 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006272 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006273 }
Chris Lattner57d86372007-01-06 01:45:59 +00006274 }
6275
6276 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006277 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006278 // This comes up when you have code like
6279 // int X = A < B;
6280 // if (X) ...
6281 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006282 // with a constant or another cast from the same type.
6283 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006284 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006285 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006286 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006287
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006288 // See if it's the same type of instruction on the left and right.
6289 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6290 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006291 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006292 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006293 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006294 default: break;
6295 case Instruction::Add:
6296 case Instruction::Sub:
6297 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006298 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006299 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006300 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006301 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6302 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6303 if (CI->getValue().isSignBit()) {
6304 ICmpInst::Predicate Pred = I.isSignedPredicate()
6305 ? I.getUnsignedPredicate()
6306 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006307 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006308 Op1I->getOperand(0));
6309 }
6310
6311 if (CI->getValue().isMaxSignedValue()) {
6312 ICmpInst::Predicate Pred = I.isSignedPredicate()
6313 ? I.getUnsignedPredicate()
6314 : I.getSignedPredicate();
6315 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006316 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006317 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006318 }
6319 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006320 break;
6321 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006322 if (!I.isEquality())
6323 break;
6324
Nick Lewycky5d52c452008-08-21 05:56:10 +00006325 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6326 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6327 // Mask = -1 >> count-trailing-zeros(Cst).
6328 if (!CI->isZero() && !CI->isOne()) {
6329 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006330 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006331 APInt::getLowBitsSet(AP.getBitWidth(),
6332 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006333 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006334 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6335 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006336 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006337 }
6338 }
6339 break;
6340 }
6341 }
6342 }
6343 }
6344
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006345 // ~x < ~y --> y < x
6346 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006347 if (match(Op0, m_Not(m_Value(A))) &&
6348 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006349 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006350 }
6351
Chris Lattner65b72ba2006-09-18 04:22:48 +00006352 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006353 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006354
6355 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006356 if (match(Op0, m_Neg(m_Value(A))) &&
6357 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006358 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006359
Dan Gohman4ae51262009-08-12 16:23:25 +00006360 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006361 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6362 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006363 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006364 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006365 }
6366
Dan Gohman4ae51262009-08-12 16:23:25 +00006367 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006368 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006369 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006370 if (match(B, m_ConstantInt(C1)) &&
6371 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006372 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006373 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006374 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6375 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006376 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006377
6378 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006379 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6380 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6381 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6382 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006383 }
6384 }
6385
Dan Gohman4ae51262009-08-12 16:23:25 +00006386 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006387 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006388 // A == (A^B) -> B == 0
6389 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006390 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006391 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006392 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006393
6394 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006395 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006396 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006397 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006398
6399 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006400 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006401 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006402 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006403
Chris Lattner9c2328e2006-11-14 06:06:06 +00006404 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6405 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006406 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6407 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006408 Value *X = 0, *Y = 0, *Z = 0;
6409
6410 if (A == C) {
6411 X = B; Y = D; Z = A;
6412 } else if (A == D) {
6413 X = B; Y = C; Z = A;
6414 } else if (B == C) {
6415 X = A; Y = D; Z = B;
6416 } else if (B == D) {
6417 X = A; Y = C; Z = B;
6418 }
6419
6420 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006421 Op1 = Builder->CreateXor(X, Y, "tmp");
6422 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006423 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006424 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006425 return &I;
6426 }
6427 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006428 }
Chris Lattner7e708292002-06-25 16:13:24 +00006429 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006430}
6431
Chris Lattner562ef782007-06-20 23:46:26 +00006432
6433/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6434/// and CmpRHS are both known to be integer constants.
6435Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6436 ConstantInt *DivRHS) {
6437 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6438 const APInt &CmpRHSV = CmpRHS->getValue();
6439
6440 // FIXME: If the operand types don't match the type of the divide
6441 // then don't attempt this transform. The code below doesn't have the
6442 // logic to deal with a signed divide and an unsigned compare (and
6443 // vice versa). This is because (x /s C1) <s C2 produces different
6444 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6445 // (x /u C1) <u C2. Simply casting the operands and result won't
6446 // work. :( The if statement below tests that condition and bails
6447 // if it finds it.
6448 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6449 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6450 return 0;
6451 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006452 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006453 if (DivIsSigned && DivRHS->isAllOnesValue())
6454 return 0; // The overflow computation also screws up here
6455 if (DivRHS->isOne())
6456 return 0; // Not worth bothering, and eliminates some funny cases
6457 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006458
6459 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6460 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6461 // C2 (CI). By solving for X we can turn this into a range check
6462 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006463 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006464
6465 // Determine if the product overflows by seeing if the product is
6466 // not equal to the divide. Make sure we do the same kind of divide
6467 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006468 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6469 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006470
6471 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006472 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006473
Chris Lattner1dbfd482007-06-21 18:11:19 +00006474 // Figure out the interval that is being checked. For example, a comparison
6475 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6476 // Compute this interval based on the constants involved and the signedness of
6477 // the compare/divide. This computes a half-open interval, keeping track of
6478 // whether either value in the interval overflows. After analysis each
6479 // overflow variable is set to 0 if it's corresponding bound variable is valid
6480 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6481 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006482 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006483
Chris Lattner562ef782007-06-20 23:46:26 +00006484 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006485 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006486 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006487 HiOverflow = LoOverflow = ProdOV;
6488 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006489 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006490 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006491 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006492 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006493 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006494 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006495 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006496 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6497 HiOverflow = LoOverflow = ProdOV;
6498 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006499 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006500 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006501 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006502 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006503 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6504 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006505 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006506 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006507 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006508 true) ? -1 : 0;
6509 }
Chris Lattner562ef782007-06-20 23:46:26 +00006510 }
Dan Gohman76491272008-02-13 22:09:18 +00006511 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006512 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006513 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006514 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006515 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006516 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6517 HiOverflow = 1; // [INTMIN+1, overflow)
6518 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6519 }
Dan Gohman76491272008-02-13 22:09:18 +00006520 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006521 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006522 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006523 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006524 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006525 LoOverflow = AddWithOverflow(LoBound, HiBound,
6526 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006527 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006528 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6529 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006530 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006531 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006532 }
6533
Chris Lattner1dbfd482007-06-21 18:11:19 +00006534 // Dividing by a negative swaps the condition. LT <-> GT
6535 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006536 }
6537
6538 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006539 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006540 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006541 case ICmpInst::ICMP_EQ:
6542 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006543 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006544 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006545 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006546 ICmpInst::ICMP_UGE, X, LoBound);
6547 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006548 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006549 ICmpInst::ICMP_ULT, X, HiBound);
6550 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006551 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006552 case ICmpInst::ICMP_NE:
6553 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006554 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006555 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006556 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006557 ICmpInst::ICMP_ULT, X, LoBound);
6558 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006559 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006560 ICmpInst::ICMP_UGE, X, HiBound);
6561 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006562 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006563 case ICmpInst::ICMP_ULT:
6564 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006565 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006566 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006567 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006568 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006569 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006570 case ICmpInst::ICMP_UGT:
6571 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006572 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006573 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006574 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006575 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006576 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006577 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006578 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006579 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006580 }
6581}
6582
6583
Chris Lattner01deb9d2007-04-03 17:43:25 +00006584/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6585///
6586Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6587 Instruction *LHSI,
6588 ConstantInt *RHS) {
6589 const APInt &RHSV = RHS->getValue();
6590
6591 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006592 case Instruction::Trunc:
6593 if (ICI.isEquality() && LHSI->hasOneUse()) {
6594 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6595 // of the high bits truncated out of x are known.
6596 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6597 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6598 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6599 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6600 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6601
6602 // If all the high bits are known, we can do this xform.
6603 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6604 // Pull in the high bits from known-ones set.
6605 APInt NewRHS(RHS->getValue());
6606 NewRHS.zext(SrcBits);
6607 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006608 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006609 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006610 }
6611 }
6612 break;
6613
Duncan Sands0091bf22007-04-04 06:42:45 +00006614 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006615 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6616 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6617 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006618 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6619 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006620 Value *CompareVal = LHSI->getOperand(0);
6621
6622 // If the sign bit of the XorCST is not set, there is no change to
6623 // the operation, just stop using the Xor.
6624 if (!XorCST->getValue().isNegative()) {
6625 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006626 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006627 return &ICI;
6628 }
6629
6630 // Was the old condition true if the operand is positive?
6631 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6632
6633 // If so, the new one isn't.
6634 isTrueIfPositive ^= true;
6635
6636 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006637 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006638 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006639 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006640 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006641 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006642 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006643
6644 if (LHSI->hasOneUse()) {
6645 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6646 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6647 const APInt &SignBit = XorCST->getValue();
6648 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6649 ? ICI.getUnsignedPredicate()
6650 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006651 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006652 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006653 }
6654
6655 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006656 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006657 const APInt &NotSignBit = XorCST->getValue();
6658 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6659 ? ICI.getUnsignedPredicate()
6660 : ICI.getSignedPredicate();
6661 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006662 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006663 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006664 }
6665 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006666 }
6667 break;
6668 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6669 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6670 LHSI->getOperand(0)->hasOneUse()) {
6671 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6672
6673 // If the LHS is an AND of a truncating cast, we can widen the
6674 // and/compare to be the input width without changing the value
6675 // produced, eliminating a cast.
6676 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6677 // We can do this transformation if either the AND constant does not
6678 // have its sign bit set or if it is an equality comparison.
6679 // Extending a relational comparison when we're checking the sign
6680 // bit would not work.
6681 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006682 (ICI.isEquality() ||
6683 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006684 uint32_t BitWidth =
6685 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6686 APInt NewCST = AndCST->getValue();
6687 NewCST.zext(BitWidth);
6688 APInt NewCI = RHSV;
6689 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006690 Value *NewAnd =
6691 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006692 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006693 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006694 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006695 }
6696 }
6697
6698 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6699 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6700 // happens a LOT in code produced by the C front-end, for bitfield
6701 // access.
6702 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6703 if (Shift && !Shift->isShift())
6704 Shift = 0;
6705
6706 ConstantInt *ShAmt;
6707 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6708 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6709 const Type *AndTy = AndCST->getType(); // Type of the and.
6710
6711 // We can fold this as long as we can't shift unknown bits
6712 // into the mask. This can only happen with signed shift
6713 // rights, as they sign-extend.
6714 if (ShAmt) {
6715 bool CanFold = Shift->isLogicalShift();
6716 if (!CanFold) {
6717 // To test for the bad case of the signed shr, see if any
6718 // of the bits shifted in could be tested after the mask.
6719 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6720 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6721
6722 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6723 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6724 AndCST->getValue()) == 0)
6725 CanFold = true;
6726 }
6727
6728 if (CanFold) {
6729 Constant *NewCst;
6730 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006731 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006732 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006733 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006734
6735 // Check to see if we are shifting out any of the bits being
6736 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006737 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006738 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006739 // If we shifted bits out, the fold is not going to work out.
6740 // As a special case, check to see if this means that the
6741 // result is always true or false now.
6742 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006743 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006744 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006745 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006746 } else {
6747 ICI.setOperand(1, NewCst);
6748 Constant *NewAndCST;
6749 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006750 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006751 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006752 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006753 LHSI->setOperand(1, NewAndCST);
6754 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006755 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006756 return &ICI;
6757 }
6758 }
6759 }
6760
6761 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6762 // preferable because it allows the C<<Y expression to be hoisted out
6763 // of a loop if Y is invariant and X is not.
6764 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006765 ICI.isEquality() && !Shift->isArithmeticShift() &&
6766 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006767 // Compute C << Y.
6768 Value *NS;
6769 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006770 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006771 } else {
6772 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006773 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006774 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006775
6776 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006777 Value *NewAnd =
6778 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006779
6780 ICI.setOperand(0, NewAnd);
6781 return &ICI;
6782 }
6783 }
6784 break;
6785
Chris Lattnera0141b92007-07-15 20:42:37 +00006786 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6787 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6788 if (!ShAmt) break;
6789
6790 uint32_t TypeBits = RHSV.getBitWidth();
6791
6792 // Check that the shift amount is in range. If not, don't perform
6793 // undefined shifts. When the shift is visited it will be
6794 // simplified.
6795 if (ShAmt->uge(TypeBits))
6796 break;
6797
6798 if (ICI.isEquality()) {
6799 // If we are comparing against bits always shifted out, the
6800 // comparison cannot succeed.
6801 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006802 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006803 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006804 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6805 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006806 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006807 return ReplaceInstUsesWith(ICI, Cst);
6808 }
6809
6810 if (LHSI->hasOneUse()) {
6811 // Otherwise strength reduce the shift into an and.
6812 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6813 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006814 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006815 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006816
Chris Lattner74381062009-08-30 07:44:24 +00006817 Value *And =
6818 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006819 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006820 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006821 }
6822 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006823
6824 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6825 bool TrueIfSigned = false;
6826 if (LHSI->hasOneUse() &&
6827 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6828 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006829 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006830 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006831 Value *And =
6832 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006833 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006834 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006835 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006836 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006837 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006838
6839 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006840 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006841 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006842 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006843 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006844
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006845 // Check that the shift amount is in range. If not, don't perform
6846 // undefined shifts. When the shift is visited it will be
6847 // simplified.
6848 uint32_t TypeBits = RHSV.getBitWidth();
6849 if (ShAmt->uge(TypeBits))
6850 break;
6851
6852 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006853
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006854 // If we are comparing against bits always shifted out, the
6855 // comparison cannot succeed.
6856 APInt Comp = RHSV << ShAmtVal;
6857 if (LHSI->getOpcode() == Instruction::LShr)
6858 Comp = Comp.lshr(ShAmtVal);
6859 else
6860 Comp = Comp.ashr(ShAmtVal);
6861
6862 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6863 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006864 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006865 return ReplaceInstUsesWith(ICI, Cst);
6866 }
6867
6868 // Otherwise, check to see if the bits shifted out are known to be zero.
6869 // If so, we can compare against the unshifted value:
6870 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006871 if (LHSI->hasOneUse() &&
6872 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006873 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006874 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006875 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006876 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006877
Evan Chengf30752c2008-04-23 00:38:06 +00006878 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006879 // Otherwise strength reduce the shift into an and.
6880 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006881 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006882
Chris Lattner74381062009-08-30 07:44:24 +00006883 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6884 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006885 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006886 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006887 }
6888 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006889 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006890
6891 case Instruction::SDiv:
6892 case Instruction::UDiv:
6893 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6894 // Fold this div into the comparison, producing a range check.
6895 // Determine, based on the divide type, what the range is being
6896 // checked. If there is an overflow on the low or high side, remember
6897 // it, otherwise compute the range [low, hi) bounding the new value.
6898 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006899 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6900 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6901 DivRHS))
6902 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006903 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006904
6905 case Instruction::Add:
6906 // Fold: icmp pred (add, X, C1), C2
6907
6908 if (!ICI.isEquality()) {
6909 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6910 if (!LHSC) break;
6911 const APInt &LHSV = LHSC->getValue();
6912
6913 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6914 .subtract(LHSV);
6915
6916 if (ICI.isSignedPredicate()) {
6917 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006918 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006919 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006920 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006921 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006922 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006923 }
6924 } else {
6925 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006926 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006927 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006928 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006929 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006930 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006931 }
6932 }
6933 }
6934 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006935 }
6936
6937 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6938 if (ICI.isEquality()) {
6939 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6940
6941 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6942 // the second operand is a constant, simplify a bit.
6943 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6944 switch (BO->getOpcode()) {
6945 case Instruction::SRem:
6946 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6947 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6948 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6949 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00006950 Value *NewRem =
6951 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6952 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006953 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00006954 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006955 }
6956 }
6957 break;
6958 case Instruction::Add:
6959 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6960 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6961 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006962 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006963 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006964 } else if (RHSV == 0) {
6965 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6966 // efficiently invertible, or if the add has just this one use.
6967 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6968
Dan Gohman186a6362009-08-12 16:04:34 +00006969 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006970 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00006971 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006972 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006973 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00006974 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006975 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006976 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006977 }
6978 }
6979 break;
6980 case Instruction::Xor:
6981 // For the xor case, we can xor two constants together, eliminating
6982 // the explicit xor.
6983 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006984 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006985 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006986
6987 // FALLTHROUGH
6988 case Instruction::Sub:
6989 // Replace (([sub|xor] A, B) != 0) with (A != B)
6990 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006991 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006992 BO->getOperand(1));
6993 break;
6994
6995 case Instruction::Or:
6996 // If bits are being or'd in that are not present in the constant we
6997 // are comparing against, then the comparison could never succeed!
6998 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006999 Constant *NotCI = ConstantExpr::getNot(RHS);
7000 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007001 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007002 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007003 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007004 }
7005 break;
7006
7007 case Instruction::And:
7008 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7009 // If bits are being compared against that are and'd out, then the
7010 // comparison can never succeed!
7011 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007012 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007013 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007014 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007015
7016 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7017 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007018 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007019 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007020 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007021
7022 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007023 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007024 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007025 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007026 ICmpInst::Predicate pred = isICMP_NE ?
7027 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007028 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007029 }
7030
7031 // ((X & ~7) == 0) --> X < 8
7032 if (RHSV == 0 && isHighOnes(BOC)) {
7033 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007034 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007035 ICmpInst::Predicate pred = isICMP_NE ?
7036 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007037 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007038 }
7039 }
7040 default: break;
7041 }
7042 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7043 // Handle icmp {eq|ne} <intrinsic>, intcst.
7044 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007045 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007046 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007047 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007048 return &ICI;
7049 }
7050 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007051 }
7052 return 0;
7053}
7054
7055/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7056/// We only handle extending casts so far.
7057///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007058Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7059 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007060 Value *LHSCIOp = LHSCI->getOperand(0);
7061 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007062 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007063 Value *RHSCIOp;
7064
Chris Lattner8c756c12007-05-05 22:41:33 +00007065 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7066 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007067 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7068 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007069 cast<IntegerType>(DestTy)->getBitWidth()) {
7070 Value *RHSOp = 0;
7071 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007072 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007073 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7074 RHSOp = RHSC->getOperand(0);
7075 // If the pointer types don't match, insert a bitcast.
7076 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007077 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007078 }
7079
7080 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007081 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007082 }
7083
7084 // The code below only handles extension cast instructions, so far.
7085 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007086 if (LHSCI->getOpcode() != Instruction::ZExt &&
7087 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007088 return 0;
7089
Reid Spencere4d87aa2006-12-23 06:05:41 +00007090 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7091 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007092
Reid Spencere4d87aa2006-12-23 06:05:41 +00007093 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007094 // Not an extension from the same type?
7095 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007096 if (RHSCIOp->getType() != LHSCIOp->getType())
7097 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007098
Nick Lewycky4189a532008-01-28 03:48:02 +00007099 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007100 // and the other is a zext), then we can't handle this.
7101 if (CI->getOpcode() != LHSCI->getOpcode())
7102 return 0;
7103
Nick Lewycky4189a532008-01-28 03:48:02 +00007104 // Deal with equality cases early.
7105 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007106 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007107
7108 // A signed comparison of sign extended values simplifies into a
7109 // signed comparison.
7110 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007111 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007112
7113 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007114 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007115 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007116
Reid Spencere4d87aa2006-12-23 06:05:41 +00007117 // If we aren't dealing with a constant on the RHS, exit early
7118 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7119 if (!CI)
7120 return 0;
7121
7122 // Compute the constant that would happen if we truncated to SrcTy then
7123 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007124 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7125 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007126 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007127
7128 // If the re-extended constant didn't change...
7129 if (Res2 == CI) {
7130 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7131 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007132 // %A = sext i16 %X to i32
7133 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007134 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007135 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007136 // because %A may have negative value.
7137 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007138 // However, we allow this when the compare is EQ/NE, because they are
7139 // signless.
7140 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007141 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007142 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007143 }
7144
7145 // The re-extended constant changed so the constant cannot be represented
7146 // in the shorter type. Consequently, we cannot emit a simple comparison.
7147
7148 // First, handle some easy cases. We know the result cannot be equal at this
7149 // point so handle the ICI.isEquality() cases
7150 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007151 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007152 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007153 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007154
7155 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7156 // should have been folded away previously and not enter in here.
7157 Value *Result;
7158 if (isSignedCmp) {
7159 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007160 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007161 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007162 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007163 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007164 } else {
7165 // We're performing an unsigned comparison.
7166 if (isSignedExt) {
7167 // We're performing an unsigned comp with a sign extended value.
7168 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007169 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007170 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007171 } else {
7172 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007173 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007174 }
7175 }
7176
7177 // Finally, return the value computed.
7178 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007179 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007180 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007181
7182 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7183 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7184 "ICmp should be folded!");
7185 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007186 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007187 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007188}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007189
Reid Spencer832254e2007-02-02 02:16:23 +00007190Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7191 return commonShiftTransforms(I);
7192}
7193
7194Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7195 return commonShiftTransforms(I);
7196}
7197
7198Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007199 if (Instruction *R = commonShiftTransforms(I))
7200 return R;
7201
7202 Value *Op0 = I.getOperand(0);
7203
7204 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7205 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7206 if (CSI->isAllOnesValue())
7207 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007208
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007209 // See if we can turn a signed shr into an unsigned shr.
7210 if (MaskedValueIsZero(Op0,
7211 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7212 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7213
7214 // Arithmetic shifting an all-sign-bit value is a no-op.
7215 unsigned NumSignBits = ComputeNumSignBits(Op0);
7216 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7217 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007218
Chris Lattner348f6652007-12-06 01:59:46 +00007219 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007220}
7221
7222Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7223 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007224 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007225
7226 // shl X, 0 == X and shr X, 0 == X
7227 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007228 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7229 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007230 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007231
Reid Spencere4d87aa2006-12-23 06:05:41 +00007232 if (isa<UndefValue>(Op0)) {
7233 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007234 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007235 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007236 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007237 }
7238 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007239 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7240 return ReplaceInstUsesWith(I, Op0);
7241 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007242 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007243 }
7244
Dan Gohman9004c8a2009-05-21 02:28:33 +00007245 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007246 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007247 return &I;
7248
Chris Lattner2eefe512004-04-09 19:05:30 +00007249 // Try to fold constant and into select arguments.
7250 if (isa<Constant>(Op0))
7251 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007252 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007253 return R;
7254
Reid Spencerb83eb642006-10-20 07:07:24 +00007255 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007256 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7257 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007258 return 0;
7259}
7260
Reid Spencerb83eb642006-10-20 07:07:24 +00007261Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007262 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007263 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007264
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007265 // See if we can simplify any instructions used by the instruction whose sole
7266 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007267 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007268
Dan Gohmana119de82009-06-14 23:30:43 +00007269 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7270 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007271 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007272 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007273 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007274 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007275 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007276 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007277 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007278 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007279 }
7280
7281 // ((X*C1) << C2) == (X * (C1 << C2))
7282 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7283 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7284 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007285 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007286 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007287
7288 // Try to fold constant and into select arguments.
7289 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7290 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7291 return R;
7292 if (isa<PHINode>(Op0))
7293 if (Instruction *NV = FoldOpIntoPhi(I))
7294 return NV;
7295
Chris Lattner8999dd32007-12-22 09:07:47 +00007296 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7297 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7298 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7299 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7300 // place. Don't try to do this transformation in this case. Also, we
7301 // require that the input operand is a shift-by-constant so that we have
7302 // confidence that the shifts will get folded together. We could do this
7303 // xform in more cases, but it is unlikely to be profitable.
7304 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7305 isa<ConstantInt>(TrOp->getOperand(1))) {
7306 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007307 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007308 // (shift2 (shift1 & 0x00FF), c2)
7309 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007310
7311 // For logical shifts, the truncation has the effect of making the high
7312 // part of the register be zeros. Emulate this by inserting an AND to
7313 // clear the top bits as needed. This 'and' will usually be zapped by
7314 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007315 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7316 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007317 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7318
7319 // The mask we constructed says what the trunc would do if occurring
7320 // between the shifts. We want to know the effect *after* the second
7321 // shift. We know that it is a logical shift by a constant, so adjust the
7322 // mask as appropriate.
7323 if (I.getOpcode() == Instruction::Shl)
7324 MaskV <<= Op1->getZExtValue();
7325 else {
7326 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7327 MaskV = MaskV.lshr(Op1->getZExtValue());
7328 }
7329
Chris Lattner74381062009-08-30 07:44:24 +00007330 // shift1 & 0x00FF
7331 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7332 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007333
7334 // Return the value truncated to the interesting size.
7335 return new TruncInst(And, I.getType());
7336 }
7337 }
7338
Chris Lattner4d5542c2006-01-06 07:12:35 +00007339 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007340 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7341 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7342 Value *V1, *V2;
7343 ConstantInt *CC;
7344 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007345 default: break;
7346 case Instruction::Add:
7347 case Instruction::And:
7348 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007349 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007350 // These operators commute.
7351 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007352 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007353 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007354 m_Specific(Op1)))) {
7355 Value *YS = // (Y << C)
7356 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7357 // (X + (Y << C))
7358 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7359 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007360 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007361 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007362 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007363 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007364
Chris Lattner150f12a2005-09-18 06:30:59 +00007365 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007366 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007367 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007368 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007369 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007370 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007371 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007372 Value *YS = // (Y << C)
7373 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7374 Op0BO->getName());
7375 // X & (CC << C)
7376 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7377 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007378 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007379 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007380 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007381
Reid Spencera07cb7d2007-02-02 14:41:37 +00007382 // FALL THROUGH.
7383 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007384 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007385 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007386 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007387 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007388 Value *YS = // (Y << C)
7389 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7390 // (X + (Y << C))
7391 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7392 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007393 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007394 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007395 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007396 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007397
Chris Lattner13d4ab42006-05-31 21:14:00 +00007398 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007399 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7400 match(Op0BO->getOperand(0),
7401 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007402 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007403 cast<BinaryOperator>(Op0BO->getOperand(0))
7404 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007405 Value *YS = // (Y << C)
7406 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7407 // X & (CC << C)
7408 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7409 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007410
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007411 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007412 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007413
Chris Lattner11021cb2005-09-18 05:12:10 +00007414 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007415 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007416 }
7417
7418
7419 // If the operand is an bitwise operator with a constant RHS, and the
7420 // shift is the only use, we can pull it out of the shift.
7421 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7422 bool isValid = true; // Valid only for And, Or, Xor
7423 bool highBitSet = false; // Transform if high bit of constant set?
7424
7425 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007426 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007427 case Instruction::Add:
7428 isValid = isLeftShift;
7429 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007430 case Instruction::Or:
7431 case Instruction::Xor:
7432 highBitSet = false;
7433 break;
7434 case Instruction::And:
7435 highBitSet = true;
7436 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007437 }
7438
7439 // If this is a signed shift right, and the high bit is modified
7440 // by the logical operation, do not perform the transformation.
7441 // The highBitSet boolean indicates the value of the high bit of
7442 // the constant which would cause it to be modified for this
7443 // operation.
7444 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007445 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007446 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007447
7448 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007449 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007450
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007451 Value *NewShift =
7452 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007453 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007454
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007455 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007456 NewRHS);
7457 }
7458 }
7459 }
7460 }
7461
Chris Lattnerad0124c2006-01-06 07:52:12 +00007462 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007463 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7464 if (ShiftOp && !ShiftOp->isShift())
7465 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007466
Reid Spencerb83eb642006-10-20 07:07:24 +00007467 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007468 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007469 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7470 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007471 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7472 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7473 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007474
Zhou Sheng4351c642007-04-02 08:20:41 +00007475 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007476
7477 const IntegerType *Ty = cast<IntegerType>(I.getType());
7478
7479 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007480 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007481 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7482 // saturates.
7483 if (AmtSum >= TypeBits) {
7484 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007485 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007486 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7487 }
7488
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007489 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007490 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007491 }
7492
7493 if (ShiftOp->getOpcode() == Instruction::LShr &&
7494 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007495 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007496 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007497
Chris Lattnerb87056f2007-02-05 00:57:54 +00007498 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007499 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007500 }
7501
7502 if (ShiftOp->getOpcode() == Instruction::AShr &&
7503 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007504 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007505 if (AmtSum >= TypeBits)
7506 AmtSum = TypeBits-1;
7507
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007508 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007509
Zhou Shenge9e03f62007-03-28 15:02:20 +00007510 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007511 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007512 }
7513
Chris Lattnerb87056f2007-02-05 00:57:54 +00007514 // Okay, if we get here, one shift must be left, and the other shift must be
7515 // right. See if the amounts are equal.
7516 if (ShiftAmt1 == ShiftAmt2) {
7517 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7518 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007519 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007520 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007521 }
7522 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7523 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007524 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007525 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007526 }
7527 // We can simplify ((X << C) >>s C) into a trunc + sext.
7528 // NOTE: we could do this for any C, but that would make 'unusual' integer
7529 // types. For now, just stick to ones well-supported by the code
7530 // generators.
7531 const Type *SExtType = 0;
7532 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007533 case 1 :
7534 case 8 :
7535 case 16 :
7536 case 32 :
7537 case 64 :
7538 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007539 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007540 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007541 default: break;
7542 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007543 if (SExtType)
7544 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007545 // Otherwise, we can't handle it yet.
7546 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007547 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007548
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007549 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007550 if (I.getOpcode() == Instruction::Shl) {
7551 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7552 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007553 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007554
Reid Spencer55702aa2007-03-25 21:11:44 +00007555 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007556 return BinaryOperator::CreateAnd(Shift,
7557 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007558 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007559
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007560 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007561 if (I.getOpcode() == Instruction::LShr) {
7562 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007563 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007564
Reid Spencerd5e30f02007-03-26 17:18:58 +00007565 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007566 return BinaryOperator::CreateAnd(Shift,
7567 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007568 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007569
7570 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7571 } else {
7572 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007573 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007574
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007575 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007576 if (I.getOpcode() == Instruction::Shl) {
7577 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7578 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007579 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7580 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007581
Reid Spencer55702aa2007-03-25 21:11:44 +00007582 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007583 return BinaryOperator::CreateAnd(Shift,
7584 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007585 }
7586
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007587 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007588 if (I.getOpcode() == Instruction::LShr) {
7589 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007590 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007591
Reid Spencer68d27cf2007-03-26 23:45:51 +00007592 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007593 return BinaryOperator::CreateAnd(Shift,
7594 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007595 }
7596
7597 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007598 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007599 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007600 return 0;
7601}
7602
Chris Lattnera1be5662002-05-02 17:06:02 +00007603
Chris Lattnercfd65102005-10-29 04:36:15 +00007604/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7605/// expression. If so, decompose it, returning some value X, such that Val is
7606/// X*Scale+Offset.
7607///
7608static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007609 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007610 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7611 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007612 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007613 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007614 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007615 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007616 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7617 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7618 if (I->getOpcode() == Instruction::Shl) {
7619 // This is a value scaled by '1 << the shift amt'.
7620 Scale = 1U << RHS->getZExtValue();
7621 Offset = 0;
7622 return I->getOperand(0);
7623 } else if (I->getOpcode() == Instruction::Mul) {
7624 // This value is scaled by 'RHS'.
7625 Scale = RHS->getZExtValue();
7626 Offset = 0;
7627 return I->getOperand(0);
7628 } else if (I->getOpcode() == Instruction::Add) {
7629 // We have X+C. Check to see if we really have (X*C2)+C1,
7630 // where C1 is divisible by C2.
7631 unsigned SubScale;
7632 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007633 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7634 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007635 Offset += RHS->getZExtValue();
7636 Scale = SubScale;
7637 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007638 }
7639 }
7640 }
7641
7642 // Otherwise, we can't look past this.
7643 Scale = 1;
7644 Offset = 0;
7645 return Val;
7646}
7647
7648
Chris Lattnerb3f83972005-10-24 06:03:58 +00007649/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7650/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007651Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007652 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007653 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007654
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007655 BuilderTy AllocaBuilder(*Builder);
7656 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7657
Chris Lattnerb53c2382005-10-24 06:22:12 +00007658 // Remove any uses of AI that are dead.
7659 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007660
Chris Lattnerb53c2382005-10-24 06:22:12 +00007661 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7662 Instruction *User = cast<Instruction>(*UI++);
7663 if (isInstructionTriviallyDead(User)) {
7664 while (UI != E && *UI == User)
7665 ++UI; // If this instruction uses AI more than once, don't break UI.
7666
Chris Lattnerb53c2382005-10-24 06:22:12 +00007667 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007668 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007669 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007670 }
7671 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007672
7673 // This requires TargetData to get the alloca alignment and size information.
7674 if (!TD) return 0;
7675
Chris Lattnerb3f83972005-10-24 06:03:58 +00007676 // Get the type really allocated and the type casted to.
7677 const Type *AllocElTy = AI.getAllocatedType();
7678 const Type *CastElTy = PTy->getElementType();
7679 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007680
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007681 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7682 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007683 if (CastElTyAlign < AllocElTyAlign) return 0;
7684
Chris Lattner39387a52005-10-24 06:35:18 +00007685 // If the allocation has multiple uses, only promote it if we are strictly
7686 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007687 // same, we open the door to infinite loops of various kinds. (A reference
7688 // from a dbg.declare doesn't count as a use for this purpose.)
7689 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7690 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007691
Duncan Sands777d2302009-05-09 07:06:46 +00007692 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7693 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007694 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007695
Chris Lattner455fcc82005-10-29 03:19:53 +00007696 // See if we can satisfy the modulus by pulling a scale out of the array
7697 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007698 unsigned ArraySizeScale;
7699 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007700 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007701 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7702 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007703
Chris Lattner455fcc82005-10-29 03:19:53 +00007704 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7705 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007706 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7707 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007708
Chris Lattner455fcc82005-10-29 03:19:53 +00007709 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7710 Value *Amt = 0;
7711 if (Scale == 1) {
7712 Amt = NumElements;
7713 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007714 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007715 // Insert before the alloca, not before the cast.
7716 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007717 }
7718
Jeff Cohen86796be2007-04-04 16:58:57 +00007719 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007720 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007721 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007722 }
7723
Chris Lattnerb3f83972005-10-24 06:03:58 +00007724 AllocationInst *New;
7725 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007726 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Chris Lattnerb3f83972005-10-24 06:03:58 +00007727 else
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007728 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7729 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007730 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007731
Dale Johannesena0a66372009-03-05 00:39:02 +00007732 // If the allocation has one real use plus a dbg.declare, just remove the
7733 // declare.
7734 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7735 EraseInstFromFunction(*DI);
7736 }
7737 // If the allocation has multiple real uses, insert a cast and change all
7738 // things that used it to use the new cast. This will also hack on CI, but it
7739 // will die soon.
7740 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007741 // New is the allocation instruction, pointer typed. AI is the original
7742 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007743 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007744 AI.replaceAllUsesWith(NewCast);
7745 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007746 return ReplaceInstUsesWith(CI, New);
7747}
7748
Chris Lattner70074e02006-05-13 02:06:03 +00007749/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007750/// and return it as type Ty without inserting any new casts and without
7751/// changing the computed value. This is used by code that tries to decide
7752/// whether promoting or shrinking integer operations to wider or smaller types
7753/// will allow us to eliminate a truncate or extend.
7754///
7755/// This is a truncation operation if Ty is smaller than V->getType(), or an
7756/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007757///
7758/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7759/// should return true if trunc(V) can be computed by computing V in the smaller
7760/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7761/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7762/// efficiently truncated.
7763///
7764/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7765/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7766/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007767bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007768 unsigned CastOpc,
7769 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007770 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007771 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007772 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007773
7774 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007775 if (!I) return false;
7776
Dan Gohman6de29f82009-06-15 22:12:54 +00007777 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007778
Chris Lattner951626b2007-08-02 06:11:14 +00007779 // If this is an extension or truncate, we can often eliminate it.
7780 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7781 // If this is a cast from the destination type, we can trivially eliminate
7782 // it, and this will remove a cast overall.
7783 if (I->getOperand(0)->getType() == Ty) {
7784 // If the first operand is itself a cast, and is eliminable, do not count
7785 // this as an eliminable cast. We would prefer to eliminate those two
7786 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007787 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007788 ++NumCastsRemoved;
7789 return true;
7790 }
7791 }
7792
7793 // We can't extend or shrink something that has multiple uses: doing so would
7794 // require duplicating the instruction in general, which isn't profitable.
7795 if (!I->hasOneUse()) return false;
7796
Evan Chengf35fd542009-01-15 17:01:23 +00007797 unsigned Opc = I->getOpcode();
7798 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007799 case Instruction::Add:
7800 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007801 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007802 case Instruction::And:
7803 case Instruction::Or:
7804 case Instruction::Xor:
7805 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007806 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007807 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007808 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007809 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007810
Eli Friedman070a9812009-07-13 22:46:01 +00007811 case Instruction::UDiv:
7812 case Instruction::URem: {
7813 // UDiv and URem can be truncated if all the truncated bits are zero.
7814 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7815 uint32_t BitWidth = Ty->getScalarSizeInBits();
7816 if (BitWidth < OrigBitWidth) {
7817 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7818 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7819 MaskedValueIsZero(I->getOperand(1), Mask)) {
7820 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7821 NumCastsRemoved) &&
7822 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7823 NumCastsRemoved);
7824 }
7825 }
7826 break;
7827 }
Chris Lattner46b96052006-11-29 07:18:39 +00007828 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007829 // If we are truncating the result of this SHL, and if it's a shift of a
7830 // constant amount, we can always perform a SHL in a smaller type.
7831 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007832 uint32_t BitWidth = Ty->getScalarSizeInBits();
7833 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007834 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007835 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007836 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007837 }
7838 break;
7839 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007840 // If this is a truncate of a logical shr, we can truncate it to a smaller
7841 // lshr iff we know that the bits we would otherwise be shifting in are
7842 // already zeros.
7843 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007844 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7845 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007846 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007847 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007848 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7849 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007850 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007851 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007852 }
7853 }
Chris Lattner46b96052006-11-29 07:18:39 +00007854 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007855 case Instruction::ZExt:
7856 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007857 case Instruction::Trunc:
7858 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007859 // can safely replace it. Note that replacing it does not reduce the number
7860 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007861 if (Opc == CastOpc)
7862 return true;
7863
7864 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007865 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007866 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007867 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007868 case Instruction::Select: {
7869 SelectInst *SI = cast<SelectInst>(I);
7870 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007871 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007872 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007873 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007874 }
Chris Lattner8114b712008-06-18 04:00:49 +00007875 case Instruction::PHI: {
7876 // We can change a phi if we can change all operands.
7877 PHINode *PN = cast<PHINode>(I);
7878 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7879 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007880 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007881 return false;
7882 return true;
7883 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007884 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007885 // TODO: Can handle more cases here.
7886 break;
7887 }
7888
7889 return false;
7890}
7891
7892/// EvaluateInDifferentType - Given an expression that
7893/// CanEvaluateInDifferentType returns true for, actually insert the code to
7894/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007895Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007896 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007897 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007898 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007899 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007900
7901 // Otherwise, it must be an instruction.
7902 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007903 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007904 unsigned Opc = I->getOpcode();
7905 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007906 case Instruction::Add:
7907 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007908 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007909 case Instruction::And:
7910 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007911 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007912 case Instruction::AShr:
7913 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00007914 case Instruction::Shl:
7915 case Instruction::UDiv:
7916 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007917 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007918 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007919 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007920 break;
7921 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007922 case Instruction::Trunc:
7923 case Instruction::ZExt:
7924 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007925 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007926 // just return the source. There's no need to insert it because it is not
7927 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007928 if (I->getOperand(0)->getType() == Ty)
7929 return I->getOperand(0);
7930
Chris Lattner8114b712008-06-18 04:00:49 +00007931 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007932 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007933 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007934 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007935 case Instruction::Select: {
7936 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7937 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7938 Res = SelectInst::Create(I->getOperand(0), True, False);
7939 break;
7940 }
Chris Lattner8114b712008-06-18 04:00:49 +00007941 case Instruction::PHI: {
7942 PHINode *OPN = cast<PHINode>(I);
7943 PHINode *NPN = PHINode::Create(Ty);
7944 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7945 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7946 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7947 }
7948 Res = NPN;
7949 break;
7950 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007951 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007952 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00007953 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00007954 break;
7955 }
7956
Chris Lattner8114b712008-06-18 04:00:49 +00007957 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007958 return InsertNewInstBefore(Res, *I);
7959}
7960
Reid Spencer3da59db2006-11-27 01:05:10 +00007961/// @brief Implement the transforms common to all CastInst visitors.
7962Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007963 Value *Src = CI.getOperand(0);
7964
Dan Gohman23d9d272007-05-11 21:10:54 +00007965 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007966 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007967 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007968 if (Instruction::CastOps opc =
7969 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7970 // The first cast (CSrc) is eliminable so we need to fix up or replace
7971 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007972 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007973 }
7974 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007975
Reid Spencer3da59db2006-11-27 01:05:10 +00007976 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007977 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7978 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7979 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007980
7981 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007982 if (isa<PHINode>(Src))
7983 if (Instruction *NV = FoldOpIntoPhi(CI))
7984 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007985
Reid Spencer3da59db2006-11-27 01:05:10 +00007986 return 0;
7987}
7988
Chris Lattner46cd5a12009-01-09 05:44:56 +00007989/// FindElementAtOffset - Given a type and a constant offset, determine whether
7990/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00007991/// the specified offset. If so, fill them into NewIndices and return the
7992/// resultant element type, otherwise return null.
7993static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7994 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00007995 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007996 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007997 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00007998 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007999
8000 // Start with the index over the outer type. Note that the type size
8001 // might be zero (even if the offset isn't zero) if the indexed type
8002 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008003 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008004 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008005 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008006 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008007 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008008
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008009 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008010 if (Offset < 0) {
8011 --FirstIdx;
8012 Offset += TySize;
8013 assert(Offset >= 0);
8014 }
8015 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8016 }
8017
Owen Andersoneed707b2009-07-24 23:12:02 +00008018 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008019
8020 // Index into the types. If we fail, set OrigBase to null.
8021 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008022 // Indexing into tail padding between struct/array elements.
8023 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008024 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008025
Chris Lattner46cd5a12009-01-09 05:44:56 +00008026 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8027 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008028 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8029 "Offset must stay within the indexed type");
8030
Chris Lattner46cd5a12009-01-09 05:44:56 +00008031 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008032 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008033
8034 Offset -= SL->getElementOffset(Elt);
8035 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008036 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008037 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008038 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008039 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008040 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008041 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008042 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008043 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008044 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008045 }
8046 }
8047
Chris Lattner3914f722009-01-24 01:00:13 +00008048 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008049}
8050
Chris Lattnerd3e28342007-04-27 17:44:50 +00008051/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8052Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8053 Value *Src = CI.getOperand(0);
8054
Chris Lattnerd3e28342007-04-27 17:44:50 +00008055 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008056 // If casting the result of a getelementptr instruction with no offset, turn
8057 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008058 if (GEP->hasAllZeroIndices()) {
8059 // Changing the cast operand is usually not a good idea but it is safe
8060 // here because the pointer operand is being replaced with another
8061 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008062 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008063 CI.setOperand(0, GEP->getOperand(0));
8064 return &CI;
8065 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008066
8067 // If the GEP has a single use, and the base pointer is a bitcast, and the
8068 // GEP computes a constant offset, see if we can convert these three
8069 // instructions into fewer. This typically happens with unions and other
8070 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008071 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008072 if (GEP->hasAllConstantIndices()) {
8073 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008074 ConstantInt *OffsetV =
8075 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008076 int64_t Offset = OffsetV->getSExtValue();
8077
8078 // Get the base pointer input of the bitcast, and the type it points to.
8079 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8080 const Type *GEPIdxTy =
8081 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008082 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008083 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008084 // If we were able to index down into an element, create the GEP
8085 // and bitcast the result. This eliminates one bitcast, potentially
8086 // two.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008087 Value *NGEP = Builder->CreateGEP(OrigBase, NewIndices.begin(),
8088 NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008089 NGEP->takeName(GEP);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008090 if (isa<Instruction>(NGEP) && cast<GEPOperator>(GEP)->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008091 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner9bc14642007-04-28 00:57:34 +00008092
Chris Lattner46cd5a12009-01-09 05:44:56 +00008093 if (isa<BitCastInst>(CI))
8094 return new BitCastInst(NGEP, CI.getType());
8095 assert(isa<PtrToIntInst>(CI));
8096 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008097 }
8098 }
8099 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008100 }
8101
8102 return commonCastTransforms(CI);
8103}
8104
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008105/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8106/// type like i42. We don't want to introduce operations on random non-legal
8107/// integer types where they don't already exist in the code. In the future,
8108/// we should consider making this based off target-data, so that 32-bit targets
8109/// won't get i64 operations etc.
8110static bool isSafeIntegerType(const Type *Ty) {
8111 switch (Ty->getPrimitiveSizeInBits()) {
8112 case 8:
8113 case 16:
8114 case 32:
8115 case 64:
8116 return true;
8117 default:
8118 return false;
8119 }
8120}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008121
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008122/// commonIntCastTransforms - This function implements the common transforms
8123/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008124Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8125 if (Instruction *Result = commonCastTransforms(CI))
8126 return Result;
8127
8128 Value *Src = CI.getOperand(0);
8129 const Type *SrcTy = Src->getType();
8130 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008131 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8132 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008133
Reid Spencer3da59db2006-11-27 01:05:10 +00008134 // See if we can simplify any instructions used by the LHS whose sole
8135 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008136 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008137 return &CI;
8138
8139 // If the source isn't an instruction or has more than one use then we
8140 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008141 Instruction *SrcI = dyn_cast<Instruction>(Src);
8142 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008143 return 0;
8144
Chris Lattnerc739cd62007-03-03 05:27:34 +00008145 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008146 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008147 // Only do this if the dest type is a simple type, don't convert the
8148 // expression tree to something weird like i93 unless the source is also
8149 // strange.
8150 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008151 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8152 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008153 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008154 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008155 // eliminates the cast, so it is always a win. If this is a zero-extension,
8156 // we need to do an AND to maintain the clear top-part of the computation,
8157 // so we require that the input have eliminated at least one cast. If this
8158 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008159 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008160 bool DoXForm = false;
8161 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008162 switch (CI.getOpcode()) {
8163 default:
8164 // All the others use floating point so we shouldn't actually
8165 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008166 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008167 case Instruction::Trunc:
8168 DoXForm = true;
8169 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008170 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008171 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008172 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008173 // If it's unnecessary to issue an AND to clear the high bits, it's
8174 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008175 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008176 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8177 if (MaskedValueIsZero(TryRes, Mask))
8178 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008179
8180 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008181 if (TryI->use_empty())
8182 EraseInstFromFunction(*TryI);
8183 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008184 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008185 }
Evan Chengf35fd542009-01-15 17:01:23 +00008186 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008187 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008188 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008189 // If we do not have to emit the truncate + sext pair, then it's always
8190 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008191 //
8192 // It's not safe to eliminate the trunc + sext pair if one of the
8193 // eliminated cast is a truncate. e.g.
8194 // t2 = trunc i32 t1 to i16
8195 // t3 = sext i16 t2 to i32
8196 // !=
8197 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008198 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008199 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8200 if (NumSignBits > (DestBitSize - SrcBitSize))
8201 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008202
8203 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008204 if (TryI->use_empty())
8205 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008206 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008207 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008208 }
Evan Chengf35fd542009-01-15 17:01:23 +00008209 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008210
8211 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008212 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8213 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008214 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8215 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008216 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008217 // Just replace this cast with the result.
8218 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008219
Reid Spencer3da59db2006-11-27 01:05:10 +00008220 assert(Res->getType() == DestTy);
8221 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008222 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008223 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008224 // Just replace this cast with the result.
8225 return ReplaceInstUsesWith(CI, Res);
8226 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008227 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008228
8229 // If the high bits are already zero, just replace this cast with the
8230 // result.
8231 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8232 if (MaskedValueIsZero(Res, Mask))
8233 return ReplaceInstUsesWith(CI, Res);
8234
8235 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008236 Constant *C = ConstantInt::get(*Context,
8237 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008238 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008239 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008240 case Instruction::SExt: {
8241 // If the high bits are already filled with sign bit, just replace this
8242 // cast with the result.
8243 unsigned NumSignBits = ComputeNumSignBits(Res);
8244 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008245 return ReplaceInstUsesWith(CI, Res);
8246
Reid Spencer3da59db2006-11-27 01:05:10 +00008247 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008248 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008249 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008250 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008251 }
8252 }
8253
8254 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8255 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8256
8257 switch (SrcI->getOpcode()) {
8258 case Instruction::Add:
8259 case Instruction::Mul:
8260 case Instruction::And:
8261 case Instruction::Or:
8262 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008263 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008264 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8265 // Don't insert two casts unless at least one can be eliminated.
8266 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008267 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008268 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8269 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008270 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008271 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008272 }
8273 }
8274
8275 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8276 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8277 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008278 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008279 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008280 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008281 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008282 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008283 }
8284 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008285
Eli Friedman65445c52009-07-13 21:45:57 +00008286 case Instruction::Shl: {
8287 // Canonicalize trunc inside shl, if we can.
8288 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8289 if (CI && DestBitSize < SrcBitSize &&
8290 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008291 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8292 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008293 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008294 }
8295 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008296 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008297 }
8298 return 0;
8299}
8300
Chris Lattner8a9f5712007-04-11 06:57:46 +00008301Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008302 if (Instruction *Result = commonIntCastTransforms(CI))
8303 return Result;
8304
8305 Value *Src = CI.getOperand(0);
8306 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008307 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8308 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008309
8310 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008311 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008312 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008313 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008314 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008315 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008316 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008317
Chris Lattner4f9797d2009-03-24 18:15:30 +00008318 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8319 ConstantInt *ShAmtV = 0;
8320 Value *ShiftOp = 0;
8321 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008322 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008323 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8324
8325 // Get a mask for the bits shifting in.
8326 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8327 if (MaskedValueIsZero(ShiftOp, Mask)) {
8328 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008329 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008330
8331 // Okay, we can shrink this. Truncate the input, then return a new
8332 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008333 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008334 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008335 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008336 }
8337 }
8338
8339 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008340}
8341
Evan Chengb98a10e2008-03-24 00:21:34 +00008342/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8343/// in order to eliminate the icmp.
8344Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8345 bool DoXform) {
8346 // If we are just checking for a icmp eq of a single bit and zext'ing it
8347 // to an integer, then shift the bit to the appropriate place and then
8348 // cast to integer to avoid the comparison.
8349 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8350 const APInt &Op1CV = Op1C->getValue();
8351
8352 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8353 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8354 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8355 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8356 if (!DoXform) return ICI;
8357
8358 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008359 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008360 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008361 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008362 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008363 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008364
8365 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008366 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008367 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008368 }
8369
8370 return ReplaceInstUsesWith(CI, In);
8371 }
8372
8373
8374
8375 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8376 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8377 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8378 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8379 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8380 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8381 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8382 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8383 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8384 // This only works for EQ and NE
8385 ICI->isEquality()) {
8386 // If Op1C some other power of two, convert:
8387 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8388 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8389 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8390 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8391
8392 APInt KnownZeroMask(~KnownZero);
8393 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8394 if (!DoXform) return ICI;
8395
8396 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8397 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8398 // (X&4) == 2 --> false
8399 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008400 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008401 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008402 return ReplaceInstUsesWith(CI, Res);
8403 }
8404
8405 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8406 Value *In = ICI->getOperand(0);
8407 if (ShiftAmt) {
8408 // Perform a logical shr by shiftamt.
8409 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008410 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8411 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008412 }
8413
8414 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008415 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008416 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008417 }
8418
8419 if (CI.getType() == In->getType())
8420 return ReplaceInstUsesWith(CI, In);
8421 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008422 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008423 }
8424 }
8425 }
8426
8427 return 0;
8428}
8429
Chris Lattner8a9f5712007-04-11 06:57:46 +00008430Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008431 // If one of the common conversion will work ..
8432 if (Instruction *Result = commonIntCastTransforms(CI))
8433 return Result;
8434
8435 Value *Src = CI.getOperand(0);
8436
Chris Lattnera84f47c2009-02-17 20:47:23 +00008437 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8438 // types and if the sizes are just right we can convert this into a logical
8439 // 'and' which will be much cheaper than the pair of casts.
8440 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8441 // Get the sizes of the types involved. We know that the intermediate type
8442 // will be smaller than A or C, but don't know the relation between A and C.
8443 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008444 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8445 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8446 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008447 // If we're actually extending zero bits, then if
8448 // SrcSize < DstSize: zext(a & mask)
8449 // SrcSize == DstSize: a & mask
8450 // SrcSize > DstSize: trunc(a) & mask
8451 if (SrcSize < DstSize) {
8452 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008453 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008454 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008455 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008456 }
8457
8458 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008459 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008460 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008461 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008462 }
8463 if (SrcSize > DstSize) {
8464 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008465 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008466 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008467 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008468 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008469 }
8470 }
8471
Evan Chengb98a10e2008-03-24 00:21:34 +00008472 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8473 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008474
Evan Chengb98a10e2008-03-24 00:21:34 +00008475 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8476 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8477 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8478 // of the (zext icmp) will be transformed.
8479 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8480 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8481 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8482 (transformZExtICmp(LHS, CI, false) ||
8483 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008484 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8485 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008486 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008487 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008488 }
8489
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008490 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008491 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8492 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8493 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8494 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008495 if (TI0->getType() == CI.getType())
8496 return
8497 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008498 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008499 }
8500
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008501 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8502 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8503 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8504 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8505 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8506 And->getOperand(1) == C)
8507 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8508 Value *TI0 = TI->getOperand(0);
8509 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008510 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008511 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008512 return BinaryOperator::CreateXor(NewAnd, ZC);
8513 }
8514 }
8515
Reid Spencer3da59db2006-11-27 01:05:10 +00008516 return 0;
8517}
8518
Chris Lattner8a9f5712007-04-11 06:57:46 +00008519Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008520 if (Instruction *I = commonIntCastTransforms(CI))
8521 return I;
8522
Chris Lattner8a9f5712007-04-11 06:57:46 +00008523 Value *Src = CI.getOperand(0);
8524
Dan Gohman1975d032008-10-30 20:40:10 +00008525 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008526 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008527 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008528 Constant::getAllOnesValue(CI.getType()),
8529 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008530
8531 // See if the value being truncated is already sign extended. If so, just
8532 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008533 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008534 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008535 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8536 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8537 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008538 unsigned NumSignBits = ComputeNumSignBits(Op);
8539
8540 if (OpBits == DestBits) {
8541 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8542 // bits, it is already ready.
8543 if (NumSignBits > DestBits-MidBits)
8544 return ReplaceInstUsesWith(CI, Op);
8545 } else if (OpBits < DestBits) {
8546 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8547 // bits, just sext from i32.
8548 if (NumSignBits > OpBits-MidBits)
8549 return new SExtInst(Op, CI.getType(), "tmp");
8550 } else {
8551 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8552 // bits, just truncate to i32.
8553 if (NumSignBits > OpBits-MidBits)
8554 return new TruncInst(Op, CI.getType(), "tmp");
8555 }
8556 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008557
8558 // If the input is a shl/ashr pair of a same constant, then this is a sign
8559 // extension from a smaller value. If we could trust arbitrary bitwidth
8560 // integers, we could turn this into a truncate to the smaller bit and then
8561 // use a sext for the whole extension. Since we don't, look deeper and check
8562 // for a truncate. If the source and dest are the same type, eliminate the
8563 // trunc and extend and just do shifts. For example, turn:
8564 // %a = trunc i32 %i to i8
8565 // %b = shl i8 %a, 6
8566 // %c = ashr i8 %b, 6
8567 // %d = sext i8 %c to i32
8568 // into:
8569 // %a = shl i32 %i, 30
8570 // %d = ashr i32 %a, 30
8571 Value *A = 0;
8572 ConstantInt *BA = 0, *CA = 0;
8573 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008574 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008575 BA == CA && isa<TruncInst>(A)) {
8576 Value *I = cast<TruncInst>(A)->getOperand(0);
8577 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008578 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8579 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008580 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008581 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008582 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008583 return BinaryOperator::CreateAShr(I, ShAmtV);
8584 }
8585 }
8586
Chris Lattnerba417832007-04-11 06:12:58 +00008587 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008588}
8589
Chris Lattnerb7530652008-01-27 05:29:54 +00008590/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8591/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008592static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008593 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008594 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008595 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008596 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8597 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008598 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008599 return 0;
8600}
8601
8602/// LookThroughFPExtensions - If this is an fp extension instruction, look
8603/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008604static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008605 if (Instruction *I = dyn_cast<Instruction>(V))
8606 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008607 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008608
8609 // If this value is a constant, return the constant in the smallest FP type
8610 // that can accurately represent it. This allows us to turn
8611 // (float)((double)X+2.0) into x+2.0f.
8612 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008613 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008614 return V; // No constant folding of this.
8615 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008616 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008617 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008618 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008619 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008620 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008621 return V;
8622 // Don't try to shrink to various long double types.
8623 }
8624
8625 return V;
8626}
8627
8628Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8629 if (Instruction *I = commonCastTransforms(CI))
8630 return I;
8631
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008632 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008633 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008634 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008635 // many builtins (sqrt, etc).
8636 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8637 if (OpI && OpI->hasOneUse()) {
8638 switch (OpI->getOpcode()) {
8639 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008640 case Instruction::FAdd:
8641 case Instruction::FSub:
8642 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008643 case Instruction::FDiv:
8644 case Instruction::FRem:
8645 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008646 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8647 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008648 if (LHSTrunc->getType() != SrcTy &&
8649 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008650 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008651 // If the source types were both smaller than the destination type of
8652 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008653 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8654 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008655 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8656 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008657 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008658 }
8659 }
8660 break;
8661 }
8662 }
8663 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008664}
8665
8666Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8667 return commonCastTransforms(CI);
8668}
8669
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008670Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008671 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8672 if (OpI == 0)
8673 return commonCastTransforms(FI);
8674
8675 // fptoui(uitofp(X)) --> X
8676 // fptoui(sitofp(X)) --> X
8677 // This is safe if the intermediate type has enough bits in its mantissa to
8678 // accurately represent all values of X. For example, do not do this with
8679 // i64->float->i64. This is also safe for sitofp case, because any negative
8680 // 'X' value would cause an undefined result for the fptoui.
8681 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8682 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008683 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008684 OpI->getType()->getFPMantissaWidth())
8685 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008686
8687 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008688}
8689
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008690Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008691 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8692 if (OpI == 0)
8693 return commonCastTransforms(FI);
8694
8695 // fptosi(sitofp(X)) --> X
8696 // fptosi(uitofp(X)) --> X
8697 // This is safe if the intermediate type has enough bits in its mantissa to
8698 // accurately represent all values of X. For example, do not do this with
8699 // i64->float->i64. This is also safe for sitofp case, because any negative
8700 // 'X' value would cause an undefined result for the fptoui.
8701 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8702 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008703 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008704 OpI->getType()->getFPMantissaWidth())
8705 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008706
8707 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008708}
8709
8710Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8711 return commonCastTransforms(CI);
8712}
8713
8714Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8715 return commonCastTransforms(CI);
8716}
8717
Chris Lattnera0e69692009-03-24 18:35:40 +00008718Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8719 // If the destination integer type is smaller than the intptr_t type for
8720 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8721 // trunc to be exposed to other transforms. Don't do this for extending
8722 // ptrtoint's, because we don't know if the target sign or zero extends its
8723 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008724 if (TD &&
8725 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008726 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8727 TD->getIntPtrType(CI.getContext()),
8728 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008729 return new TruncInst(P, CI.getType());
8730 }
8731
Chris Lattnerd3e28342007-04-27 17:44:50 +00008732 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008733}
8734
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008735Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008736 // If the source integer type is larger than the intptr_t type for
8737 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8738 // allows the trunc to be exposed to other transforms. Don't do this for
8739 // extending inttoptr's, because we don't know if the target sign or zero
8740 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008741 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008742 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008743 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8744 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008745 return new IntToPtrInst(P, CI.getType());
8746 }
8747
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008748 if (Instruction *I = commonCastTransforms(CI))
8749 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008750
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008751 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008752}
8753
Chris Lattnerd3e28342007-04-27 17:44:50 +00008754Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008755 // If the operands are integer typed then apply the integer transforms,
8756 // otherwise just apply the common ones.
8757 Value *Src = CI.getOperand(0);
8758 const Type *SrcTy = Src->getType();
8759 const Type *DestTy = CI.getType();
8760
Eli Friedman7e25d452009-07-13 20:53:00 +00008761 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008762 if (Instruction *I = commonPointerCastTransforms(CI))
8763 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008764 } else {
8765 if (Instruction *Result = commonCastTransforms(CI))
8766 return Result;
8767 }
8768
8769
8770 // Get rid of casts from one type to the same type. These are useless and can
8771 // be replaced by the operand.
8772 if (DestTy == Src->getType())
8773 return ReplaceInstUsesWith(CI, Src);
8774
Reid Spencer3da59db2006-11-27 01:05:10 +00008775 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008776 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8777 const Type *DstElTy = DstPTy->getElementType();
8778 const Type *SrcElTy = SrcPTy->getElementType();
8779
Nate Begeman83ad90a2008-03-31 00:22:16 +00008780 // If the address spaces don't match, don't eliminate the bitcast, which is
8781 // required for changing types.
8782 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8783 return 0;
8784
Chris Lattnerd3e28342007-04-27 17:44:50 +00008785 // If we are casting a malloc or alloca to a pointer to a type of the same
8786 // size, rewrite the allocation instruction to allocate the "right" type.
8787 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8788 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8789 return V;
8790
Chris Lattnerd717c182007-05-05 22:32:24 +00008791 // If the source and destination are pointers, and this cast is equivalent
8792 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008793 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008794 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008795 unsigned NumZeros = 0;
8796 while (SrcElTy != DstElTy &&
8797 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8798 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8799 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8800 ++NumZeros;
8801 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008802
Chris Lattnerd3e28342007-04-27 17:44:50 +00008803 // If we found a path from the src to dest, create the getelementptr now.
8804 if (SrcElTy == DstElTy) {
8805 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008806 Instruction *GEP = GetElementPtrInst::Create(Src,
8807 Idxs.begin(), Idxs.end(), "",
8808 ((Instruction*) NULL));
8809 cast<GEPOperator>(GEP)->setIsInBounds(true);
8810 return GEP;
Chris Lattner9fb92132006-04-12 18:09:35 +00008811 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008812 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008813
Eli Friedman2451a642009-07-18 23:06:53 +00008814 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8815 if (DestVTy->getNumElements() == 1) {
8816 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008817 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008818 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008819 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008820 }
8821 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8822 }
8823 }
8824
8825 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8826 if (SrcVTy->getNumElements() == 1) {
8827 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008828 Value *Elem =
8829 Builder->CreateExtractElement(Src,
8830 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008831 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8832 }
8833 }
8834 }
8835
Reid Spencer3da59db2006-11-27 01:05:10 +00008836 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8837 if (SVI->hasOneUse()) {
8838 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8839 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008840 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008841 cast<VectorType>(DestTy)->getNumElements() ==
8842 SVI->getType()->getNumElements() &&
8843 SVI->getType()->getNumElements() ==
8844 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008845 CastInst *Tmp;
8846 // If either of the operands is a cast from CI.getType(), then
8847 // evaluating the shuffle in the casted destination's type will allow
8848 // us to eliminate at least one cast.
8849 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8850 Tmp->getOperand(0)->getType() == DestTy) ||
8851 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8852 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008853 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8854 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008855 // Return a new shuffle vector. Use the same element ID's, as we
8856 // know the vector types match #elts.
8857 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008858 }
8859 }
8860 }
8861 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008862 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008863}
8864
Chris Lattnere576b912004-04-09 23:46:01 +00008865/// GetSelectFoldableOperands - We want to turn code that looks like this:
8866/// %C = or %A, %B
8867/// %D = select %cond, %C, %A
8868/// into:
8869/// %C = select %cond, %B, 0
8870/// %D = or %A, %C
8871///
8872/// Assuming that the specified instruction is an operand to the select, return
8873/// a bitmask indicating which operands of this instruction are foldable if they
8874/// equal the other incoming value of the select.
8875///
8876static unsigned GetSelectFoldableOperands(Instruction *I) {
8877 switch (I->getOpcode()) {
8878 case Instruction::Add:
8879 case Instruction::Mul:
8880 case Instruction::And:
8881 case Instruction::Or:
8882 case Instruction::Xor:
8883 return 3; // Can fold through either operand.
8884 case Instruction::Sub: // Can only fold on the amount subtracted.
8885 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008886 case Instruction::LShr:
8887 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008888 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008889 default:
8890 return 0; // Cannot fold
8891 }
8892}
8893
8894/// GetSelectFoldableConstant - For the same transformation as the previous
8895/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008896static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008897 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008898 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008899 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008900 case Instruction::Add:
8901 case Instruction::Sub:
8902 case Instruction::Or:
8903 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008904 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008905 case Instruction::LShr:
8906 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008907 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008908 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008909 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008910 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008911 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008912 }
8913}
8914
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008915/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8916/// have the same opcode and only one use each. Try to simplify this.
8917Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8918 Instruction *FI) {
8919 if (TI->getNumOperands() == 1) {
8920 // If this is a non-volatile load or a cast from the same type,
8921 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008922 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008923 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8924 return 0;
8925 } else {
8926 return 0; // unknown unary op.
8927 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008928
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008929 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008930 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00008931 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008932 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008933 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008934 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008935 }
8936
Reid Spencer832254e2007-02-02 02:16:23 +00008937 // Only handle binary operators here.
8938 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008939 return 0;
8940
8941 // Figure out if the operations have any operands in common.
8942 Value *MatchOp, *OtherOpT, *OtherOpF;
8943 bool MatchIsOpZero;
8944 if (TI->getOperand(0) == FI->getOperand(0)) {
8945 MatchOp = TI->getOperand(0);
8946 OtherOpT = TI->getOperand(1);
8947 OtherOpF = FI->getOperand(1);
8948 MatchIsOpZero = true;
8949 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8950 MatchOp = TI->getOperand(1);
8951 OtherOpT = TI->getOperand(0);
8952 OtherOpF = FI->getOperand(0);
8953 MatchIsOpZero = false;
8954 } else if (!TI->isCommutative()) {
8955 return 0;
8956 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8957 MatchOp = TI->getOperand(0);
8958 OtherOpT = TI->getOperand(1);
8959 OtherOpF = FI->getOperand(0);
8960 MatchIsOpZero = true;
8961 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8962 MatchOp = TI->getOperand(1);
8963 OtherOpT = TI->getOperand(0);
8964 OtherOpF = FI->getOperand(1);
8965 MatchIsOpZero = true;
8966 } else {
8967 return 0;
8968 }
8969
8970 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008971 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8972 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008973 InsertNewInstBefore(NewSI, SI);
8974
8975 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8976 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008977 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008978 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008979 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008980 }
Torok Edwinc23197a2009-07-14 16:55:14 +00008981 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00008982 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008983}
8984
Evan Chengde621922009-03-31 20:42:45 +00008985static bool isSelect01(Constant *C1, Constant *C2) {
8986 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8987 if (!C1I)
8988 return false;
8989 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8990 if (!C2I)
8991 return false;
8992 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8993}
8994
8995/// FoldSelectIntoOp - Try fold the select into one of the operands to
8996/// facilitate further optimization.
8997Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
8998 Value *FalseVal) {
8999 // See the comment above GetSelectFoldableOperands for a description of the
9000 // transformation we are doing here.
9001 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9002 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9003 !isa<Constant>(FalseVal)) {
9004 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9005 unsigned OpToFold = 0;
9006 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9007 OpToFold = 1;
9008 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9009 OpToFold = 2;
9010 }
9011
9012 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009013 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009014 Value *OOp = TVI->getOperand(2-OpToFold);
9015 // Avoid creating select between 2 constants unless it's selecting
9016 // between 0 and 1.
9017 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9018 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9019 InsertNewInstBefore(NewSel, SI);
9020 NewSel->takeName(TVI);
9021 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9022 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009023 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009024 }
9025 }
9026 }
9027 }
9028 }
9029
9030 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9031 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9032 !isa<Constant>(TrueVal)) {
9033 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9034 unsigned OpToFold = 0;
9035 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9036 OpToFold = 1;
9037 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9038 OpToFold = 2;
9039 }
9040
9041 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009042 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009043 Value *OOp = FVI->getOperand(2-OpToFold);
9044 // Avoid creating select between 2 constants unless it's selecting
9045 // between 0 and 1.
9046 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9047 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9048 InsertNewInstBefore(NewSel, SI);
9049 NewSel->takeName(FVI);
9050 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9051 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009052 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009053 }
9054 }
9055 }
9056 }
9057 }
9058
9059 return 0;
9060}
9061
Dan Gohman81b28ce2008-09-16 18:46:06 +00009062/// visitSelectInstWithICmp - Visit a SelectInst that has an
9063/// ICmpInst as its first operand.
9064///
9065Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9066 ICmpInst *ICI) {
9067 bool Changed = false;
9068 ICmpInst::Predicate Pred = ICI->getPredicate();
9069 Value *CmpLHS = ICI->getOperand(0);
9070 Value *CmpRHS = ICI->getOperand(1);
9071 Value *TrueVal = SI.getTrueValue();
9072 Value *FalseVal = SI.getFalseValue();
9073
9074 // Check cases where the comparison is with a constant that
9075 // can be adjusted to fit the min/max idiom. We may edit ICI in
9076 // place here, so make sure the select is the only user.
9077 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009078 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009079 switch (Pred) {
9080 default: break;
9081 case ICmpInst::ICMP_ULT:
9082 case ICmpInst::ICMP_SLT: {
9083 // X < MIN ? T : F --> F
9084 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9085 return ReplaceInstUsesWith(SI, FalseVal);
9086 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009087 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009088 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9089 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9090 Pred = ICmpInst::getSwappedPredicate(Pred);
9091 CmpRHS = AdjustedRHS;
9092 std::swap(FalseVal, TrueVal);
9093 ICI->setPredicate(Pred);
9094 ICI->setOperand(1, CmpRHS);
9095 SI.setOperand(1, TrueVal);
9096 SI.setOperand(2, FalseVal);
9097 Changed = true;
9098 }
9099 break;
9100 }
9101 case ICmpInst::ICMP_UGT:
9102 case ICmpInst::ICMP_SGT: {
9103 // X > MAX ? T : F --> F
9104 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9105 return ReplaceInstUsesWith(SI, FalseVal);
9106 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009107 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009108 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9109 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9110 Pred = ICmpInst::getSwappedPredicate(Pred);
9111 CmpRHS = AdjustedRHS;
9112 std::swap(FalseVal, TrueVal);
9113 ICI->setPredicate(Pred);
9114 ICI->setOperand(1, CmpRHS);
9115 SI.setOperand(1, TrueVal);
9116 SI.setOperand(2, FalseVal);
9117 Changed = true;
9118 }
9119 break;
9120 }
9121 }
9122
Dan Gohman1975d032008-10-30 20:40:10 +00009123 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9124 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009125 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009126 if (match(TrueVal, m_ConstantInt<-1>()) &&
9127 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009128 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009129 else if (match(TrueVal, m_ConstantInt<0>()) &&
9130 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009131 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9132
Dan Gohman1975d032008-10-30 20:40:10 +00009133 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9134 // If we are just checking for a icmp eq of a single bit and zext'ing it
9135 // to an integer, then shift the bit to the appropriate place and then
9136 // cast to integer to avoid the comparison.
9137 const APInt &Op1CV = CI->getValue();
9138
9139 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9140 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9141 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009142 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009143 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009144 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009145 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009146 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009147 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009148 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009149 if (In->getType() != SI.getType())
9150 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009151 true/*SExt*/, "tmp", ICI);
9152
9153 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009154 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009155 In->getName()+".not"), *ICI);
9156
9157 return ReplaceInstUsesWith(SI, In);
9158 }
9159 }
9160 }
9161
Dan Gohman81b28ce2008-09-16 18:46:06 +00009162 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9163 // Transform (X == Y) ? X : Y -> Y
9164 if (Pred == ICmpInst::ICMP_EQ)
9165 return ReplaceInstUsesWith(SI, FalseVal);
9166 // Transform (X != Y) ? X : Y -> X
9167 if (Pred == ICmpInst::ICMP_NE)
9168 return ReplaceInstUsesWith(SI, TrueVal);
9169 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9170
9171 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9172 // Transform (X == Y) ? Y : X -> X
9173 if (Pred == ICmpInst::ICMP_EQ)
9174 return ReplaceInstUsesWith(SI, FalseVal);
9175 // Transform (X != Y) ? Y : X -> Y
9176 if (Pred == ICmpInst::ICMP_NE)
9177 return ReplaceInstUsesWith(SI, TrueVal);
9178 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9179 }
9180
9181 /// NOTE: if we wanted to, this is where to detect integer ABS
9182
9183 return Changed ? &SI : 0;
9184}
9185
Chris Lattner3d69f462004-03-12 05:52:32 +00009186Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009187 Value *CondVal = SI.getCondition();
9188 Value *TrueVal = SI.getTrueValue();
9189 Value *FalseVal = SI.getFalseValue();
9190
9191 // select true, X, Y -> X
9192 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009193 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009194 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009195
9196 // select C, X, X -> X
9197 if (TrueVal == FalseVal)
9198 return ReplaceInstUsesWith(SI, TrueVal);
9199
Chris Lattnere87597f2004-10-16 18:11:37 +00009200 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9201 return ReplaceInstUsesWith(SI, FalseVal);
9202 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9203 return ReplaceInstUsesWith(SI, TrueVal);
9204 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9205 if (isa<Constant>(TrueVal))
9206 return ReplaceInstUsesWith(SI, TrueVal);
9207 else
9208 return ReplaceInstUsesWith(SI, FalseVal);
9209 }
9210
Owen Anderson1d0be152009-08-13 21:58:54 +00009211 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009212 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009213 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009214 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009215 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009216 } else {
9217 // Change: A = select B, false, C --> A = and !B, C
9218 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009219 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009220 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009221 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009222 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009223 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009224 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009225 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009226 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009227 } else {
9228 // Change: A = select B, C, true --> A = or !B, C
9229 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009230 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009231 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009232 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009233 }
9234 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009235
9236 // select a, b, a -> a&b
9237 // select a, a, b -> a|b
9238 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009239 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009240 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009241 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009242 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009243
Chris Lattner2eefe512004-04-09 19:05:30 +00009244 // Selecting between two integer constants?
9245 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9246 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009247 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009248 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009249 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009250 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009251 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009252 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009253 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009254 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009255 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009256 }
Chris Lattner457dd822004-06-09 07:59:58 +00009257
Reid Spencere4d87aa2006-12-23 06:05:41 +00009258 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009259 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009260 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009261 // non-constant value, eliminate this whole mess. This corresponds to
9262 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009263 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009264 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009265 cast<Constant>(IC->getOperand(1))->isNullValue())
9266 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9267 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009268 isa<ConstantInt>(ICA->getOperand(1)) &&
9269 (ICA->getOperand(1) == TrueValC ||
9270 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009271 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9272 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009273 // know whether we have a icmp_ne or icmp_eq and whether the
9274 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009275 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009276 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009277 Value *V = ICA;
9278 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009279 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009280 Instruction::Xor, V, ICA->getOperand(1)), SI);
9281 return ReplaceInstUsesWith(SI, V);
9282 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009283 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009284 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009285
9286 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009287 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9288 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009289 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009290 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9291 // This is not safe in general for floating point:
9292 // consider X== -0, Y== +0.
9293 // It becomes safe if either operand is a nonzero constant.
9294 ConstantFP *CFPt, *CFPf;
9295 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9296 !CFPt->getValueAPF().isZero()) ||
9297 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9298 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009299 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009300 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009301 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009302 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009303 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009304 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009305
Reid Spencere4d87aa2006-12-23 06:05:41 +00009306 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009307 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009308 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9309 // This is not safe in general for floating point:
9310 // consider X== -0, Y== +0.
9311 // It becomes safe if either operand is a nonzero constant.
9312 ConstantFP *CFPt, *CFPf;
9313 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9314 !CFPt->getValueAPF().isZero()) ||
9315 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9316 !CFPf->getValueAPF().isZero()))
9317 return ReplaceInstUsesWith(SI, FalseVal);
9318 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009319 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009320 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9321 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009322 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009323 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009324 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009325 }
9326
9327 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009328 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9329 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9330 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009331
Chris Lattner87875da2005-01-13 22:52:24 +00009332 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9333 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9334 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009335 Instruction *AddOp = 0, *SubOp = 0;
9336
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009337 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9338 if (TI->getOpcode() == FI->getOpcode())
9339 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9340 return IV;
9341
9342 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9343 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009344 if ((TI->getOpcode() == Instruction::Sub &&
9345 FI->getOpcode() == Instruction::Add) ||
9346 (TI->getOpcode() == Instruction::FSub &&
9347 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009348 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009349 } else if ((FI->getOpcode() == Instruction::Sub &&
9350 TI->getOpcode() == Instruction::Add) ||
9351 (FI->getOpcode() == Instruction::FSub &&
9352 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009353 AddOp = TI; SubOp = FI;
9354 }
9355
9356 if (AddOp) {
9357 Value *OtherAddOp = 0;
9358 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9359 OtherAddOp = AddOp->getOperand(1);
9360 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9361 OtherAddOp = AddOp->getOperand(0);
9362 }
9363
9364 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009365 // So at this point we know we have (Y -> OtherAddOp):
9366 // select C, (add X, Y), (sub X, Z)
9367 Value *NegVal; // Compute -Z
9368 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009369 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009370 } else {
9371 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009372 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009373 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009374 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009375
9376 Value *NewTrueOp = OtherAddOp;
9377 Value *NewFalseOp = NegVal;
9378 if (AddOp != TI)
9379 std::swap(NewTrueOp, NewFalseOp);
9380 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009381 SelectInst::Create(CondVal, NewTrueOp,
9382 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009383
9384 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009385 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009386 }
9387 }
9388 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009389
Chris Lattnere576b912004-04-09 23:46:01 +00009390 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009391 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009392 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9393 if (FoldI)
9394 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009395 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009396
9397 if (BinaryOperator::isNot(CondVal)) {
9398 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9399 SI.setOperand(1, FalseVal);
9400 SI.setOperand(2, TrueVal);
9401 return &SI;
9402 }
9403
Chris Lattner3d69f462004-03-12 05:52:32 +00009404 return 0;
9405}
9406
Dan Gohmaneee962e2008-04-10 18:43:06 +00009407/// EnforceKnownAlignment - If the specified pointer points to an object that
9408/// we control, modify the object's alignment to PrefAlign. This isn't
9409/// often possible though. If alignment is important, a more reliable approach
9410/// is to simply align all global variables and allocation instructions to
9411/// their preferred alignment from the beginning.
9412///
9413static unsigned EnforceKnownAlignment(Value *V,
9414 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009415
Dan Gohmaneee962e2008-04-10 18:43:06 +00009416 User *U = dyn_cast<User>(V);
9417 if (!U) return Align;
9418
Dan Gohmanca178902009-07-17 20:47:02 +00009419 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009420 default: break;
9421 case Instruction::BitCast:
9422 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9423 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009424 // If all indexes are zero, it is just the alignment of the base pointer.
9425 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009426 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009427 if (!isa<Constant>(*i) ||
9428 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009429 AllZeroOperands = false;
9430 break;
9431 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009432
9433 if (AllZeroOperands) {
9434 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009435 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009436 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009437 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009438 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009439 }
9440
9441 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9442 // If there is a large requested alignment and we can, bump up the alignment
9443 // of the global.
9444 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009445 if (GV->getAlignment() >= PrefAlign)
9446 Align = GV->getAlignment();
9447 else {
9448 GV->setAlignment(PrefAlign);
9449 Align = PrefAlign;
9450 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009451 }
9452 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9453 // If there is a requested alignment and if this is an alloca, round up. We
9454 // don't do this for malloc, because some systems can't respect the request.
9455 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009456 if (AI->getAlignment() >= PrefAlign)
9457 Align = AI->getAlignment();
9458 else {
9459 AI->setAlignment(PrefAlign);
9460 Align = PrefAlign;
9461 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009462 }
9463 }
9464
9465 return Align;
9466}
9467
9468/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9469/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9470/// and it is more than the alignment of the ultimate object, see if we can
9471/// increase the alignment of the ultimate object, making this check succeed.
9472unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9473 unsigned PrefAlign) {
9474 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9475 sizeof(PrefAlign) * CHAR_BIT;
9476 APInt Mask = APInt::getAllOnesValue(BitWidth);
9477 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9478 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9479 unsigned TrailZ = KnownZero.countTrailingOnes();
9480 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9481
9482 if (PrefAlign > Align)
9483 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9484
9485 // We don't need to make any adjustment.
9486 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009487}
9488
Chris Lattnerf497b022008-01-13 23:50:23 +00009489Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009490 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009491 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009492 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009493 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009494
9495 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009496 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009497 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009498 return MI;
9499 }
9500
9501 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9502 // load/store.
9503 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9504 if (MemOpLength == 0) return 0;
9505
Chris Lattner37ac6082008-01-14 00:28:35 +00009506 // Source and destination pointer types are always "i8*" for intrinsic. See
9507 // if the size is something we can handle with a single primitive load/store.
9508 // A single load+store correctly handles overlapping memory in the memmove
9509 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009510 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009511 if (Size == 0) return MI; // Delete this mem transfer.
9512
9513 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009514 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009515
Chris Lattner37ac6082008-01-14 00:28:35 +00009516 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009517 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009518 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009519
9520 // Memcpy forces the use of i8* for the source and destination. That means
9521 // that if you're using memcpy to move one double around, you'll get a cast
9522 // from double* to i8*. We'd much rather use a double load+store rather than
9523 // an i64 load+store, here because this improves the odds that the source or
9524 // dest address will be promotable. See if we can find a better type than the
9525 // integer datatype.
9526 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9527 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009528 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009529 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9530 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009531 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009532 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9533 if (STy->getNumElements() == 1)
9534 SrcETy = STy->getElementType(0);
9535 else
9536 break;
9537 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9538 if (ATy->getNumElements() == 1)
9539 SrcETy = ATy->getElementType();
9540 else
9541 break;
9542 } else
9543 break;
9544 }
9545
Dan Gohman8f8e2692008-05-23 01:52:21 +00009546 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009547 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009548 }
9549 }
9550
9551
Chris Lattnerf497b022008-01-13 23:50:23 +00009552 // If the memcpy/memmove provides better alignment info than we can
9553 // infer, use it.
9554 SrcAlign = std::max(SrcAlign, CopyAlign);
9555 DstAlign = std::max(DstAlign, CopyAlign);
9556
Chris Lattner08142f22009-08-30 19:47:22 +00009557 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9558 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009559 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9560 InsertNewInstBefore(L, *MI);
9561 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9562
9563 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009564 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009565 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009566}
Chris Lattner3d69f462004-03-12 05:52:32 +00009567
Chris Lattner69ea9d22008-04-30 06:39:11 +00009568Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9569 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009570 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009571 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009572 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009573 return MI;
9574 }
9575
9576 // Extract the length and alignment and fill if they are constant.
9577 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9578 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009579 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009580 return 0;
9581 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009582 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009583
9584 // If the length is zero, this is a no-op
9585 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9586
9587 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9588 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009589 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009590
9591 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009592 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009593
9594 // Alignment 0 is identity for alignment 1 for memset, but not store.
9595 if (Alignment == 0) Alignment = 1;
9596
9597 // Extract the fill value and store.
9598 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009599 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009600 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009601
9602 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009603 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009604 return MI;
9605 }
9606
9607 return 0;
9608}
9609
9610
Chris Lattner8b0ea312006-01-13 20:11:04 +00009611/// visitCallInst - CallInst simplification. This mostly only handles folding
9612/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9613/// the heavy lifting.
9614///
Chris Lattner9fe38862003-06-19 17:00:31 +00009615Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009616 // If the caller function is nounwind, mark the call as nounwind, even if the
9617 // callee isn't.
9618 if (CI.getParent()->getParent()->doesNotThrow() &&
9619 !CI.doesNotThrow()) {
9620 CI.setDoesNotThrow();
9621 return &CI;
9622 }
9623
Chris Lattner8b0ea312006-01-13 20:11:04 +00009624 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9625 if (!II) return visitCallSite(&CI);
9626
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009627 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9628 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009629 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009630 bool Changed = false;
9631
9632 // memmove/cpy/set of zero bytes is a noop.
9633 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9634 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9635
Chris Lattner35b9e482004-10-12 04:52:52 +00009636 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009637 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009638 // Replace the instruction with just byte operations. We would
9639 // transform other cases to loads/stores, but we don't know if
9640 // alignment is sufficient.
9641 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009642 }
9643
Chris Lattner35b9e482004-10-12 04:52:52 +00009644 // If we have a memmove and the source operation is a constant global,
9645 // then the source and dest pointers can't alias, so we can change this
9646 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009647 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009648 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9649 if (GVSrc->isConstant()) {
9650 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009651 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9652 const Type *Tys[1];
9653 Tys[0] = CI.getOperand(3)->getType();
9654 CI.setOperand(0,
9655 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009656 Changed = true;
9657 }
Chris Lattnera935db82008-05-28 05:30:41 +00009658
9659 // memmove(x,x,size) -> noop.
9660 if (MMI->getSource() == MMI->getDest())
9661 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009662 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009663
Chris Lattner95a959d2006-03-06 20:18:44 +00009664 // If we can determine a pointer alignment that is bigger than currently
9665 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009666 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009667 if (Instruction *I = SimplifyMemTransfer(MI))
9668 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009669 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9670 if (Instruction *I = SimplifyMemSet(MSI))
9671 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009672 }
9673
Chris Lattner8b0ea312006-01-13 20:11:04 +00009674 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009675 }
9676
9677 switch (II->getIntrinsicID()) {
9678 default: break;
9679 case Intrinsic::bswap:
9680 // bswap(bswap(x)) -> x
9681 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9682 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9683 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9684 break;
9685 case Intrinsic::ppc_altivec_lvx:
9686 case Intrinsic::ppc_altivec_lvxl:
9687 case Intrinsic::x86_sse_loadu_ps:
9688 case Intrinsic::x86_sse2_loadu_pd:
9689 case Intrinsic::x86_sse2_loadu_dq:
9690 // Turn PPC lvx -> load if the pointer is known aligned.
9691 // Turn X86 loadups -> load if the pointer is known aligned.
9692 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009693 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9694 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009695 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009696 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009697 break;
9698 case Intrinsic::ppc_altivec_stvx:
9699 case Intrinsic::ppc_altivec_stvxl:
9700 // Turn stvx -> store if the pointer is known aligned.
9701 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9702 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009703 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009704 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009705 return new StoreInst(II->getOperand(1), Ptr);
9706 }
9707 break;
9708 case Intrinsic::x86_sse_storeu_ps:
9709 case Intrinsic::x86_sse2_storeu_pd:
9710 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009711 // Turn X86 storeu -> store if the pointer is known aligned.
9712 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9713 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009714 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009715 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009716 return new StoreInst(II->getOperand(2), Ptr);
9717 }
9718 break;
9719
9720 case Intrinsic::x86_sse_cvttss2si: {
9721 // These intrinsics only demands the 0th element of its input vector. If
9722 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009723 unsigned VWidth =
9724 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9725 APInt DemandedElts(VWidth, 1);
9726 APInt UndefElts(VWidth, 0);
9727 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009728 UndefElts)) {
9729 II->setOperand(1, V);
9730 return II;
9731 }
9732 break;
9733 }
9734
9735 case Intrinsic::ppc_altivec_vperm:
9736 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9737 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9738 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009739
Chris Lattner0521e3c2008-06-18 04:33:20 +00009740 // Check that all of the elements are integer constants or undefs.
9741 bool AllEltsOk = true;
9742 for (unsigned i = 0; i != 16; ++i) {
9743 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9744 !isa<UndefValue>(Mask->getOperand(i))) {
9745 AllEltsOk = false;
9746 break;
9747 }
9748 }
9749
9750 if (AllEltsOk) {
9751 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009752 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9753 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009754 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009755
Chris Lattner0521e3c2008-06-18 04:33:20 +00009756 // Only extract each element once.
9757 Value *ExtractedElts[32];
9758 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9759
Chris Lattnere2ed0572006-04-06 19:19:17 +00009760 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009761 if (isa<UndefValue>(Mask->getOperand(i)))
9762 continue;
9763 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9764 Idx &= 31; // Match the hardware behavior.
9765
9766 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009767 ExtractedElts[Idx] =
9768 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9769 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9770 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009771 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009772
Chris Lattner0521e3c2008-06-18 04:33:20 +00009773 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009774 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9775 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9776 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009777 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009778 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009779 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009780 }
9781 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009782
Chris Lattner0521e3c2008-06-18 04:33:20 +00009783 case Intrinsic::stackrestore: {
9784 // If the save is right next to the restore, remove the restore. This can
9785 // happen when variable allocas are DCE'd.
9786 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9787 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9788 BasicBlock::iterator BI = SS;
9789 if (&*++BI == II)
9790 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009791 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009792 }
9793
9794 // Scan down this block to see if there is another stack restore in the
9795 // same block without an intervening call/alloca.
9796 BasicBlock::iterator BI = II;
9797 TerminatorInst *TI = II->getParent()->getTerminator();
9798 bool CannotRemove = false;
9799 for (++BI; &*BI != TI; ++BI) {
9800 if (isa<AllocaInst>(BI)) {
9801 CannotRemove = true;
9802 break;
9803 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009804 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9805 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9806 // If there is a stackrestore below this one, remove this one.
9807 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9808 return EraseInstFromFunction(CI);
9809 // Otherwise, ignore the intrinsic.
9810 } else {
9811 // If we found a non-intrinsic call, we can't remove the stack
9812 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009813 CannotRemove = true;
9814 break;
9815 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009816 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009817 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009818
9819 // If the stack restore is in a return/unwind block and if there are no
9820 // allocas or calls between the restore and the return, nuke the restore.
9821 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9822 return EraseInstFromFunction(CI);
9823 break;
9824 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009825 }
9826
Chris Lattner8b0ea312006-01-13 20:11:04 +00009827 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009828}
9829
9830// InvokeInst simplification
9831//
9832Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009833 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009834}
9835
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009836/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9837/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009838static bool isSafeToEliminateVarargsCast(const CallSite CS,
9839 const CastInst * const CI,
9840 const TargetData * const TD,
9841 const int ix) {
9842 if (!CI->isLosslessCast())
9843 return false;
9844
9845 // The size of ByVal arguments is derived from the type, so we
9846 // can't change to a type with a different size. If the size were
9847 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009848 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009849 return true;
9850
9851 const Type* SrcTy =
9852 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9853 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9854 if (!SrcTy->isSized() || !DstTy->isSized())
9855 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009856 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009857 return false;
9858 return true;
9859}
9860
Chris Lattnera44d8a22003-10-07 22:32:43 +00009861// visitCallSite - Improvements for call and invoke instructions.
9862//
9863Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009864 bool Changed = false;
9865
9866 // If the callee is a constexpr cast of a function, attempt to move the cast
9867 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009868 if (transformConstExprCastCall(CS)) return 0;
9869
Chris Lattner6c266db2003-10-07 22:54:13 +00009870 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009871
Chris Lattner08b22ec2005-05-13 07:09:09 +00009872 if (Function *CalleeF = dyn_cast<Function>(Callee))
9873 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9874 Instruction *OldCall = CS.getInstruction();
9875 // If the call and callee calling conventions don't match, this call must
9876 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +00009877 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009878 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Andersond672ecb2009-07-03 00:17:18 +00009879 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009880 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009881 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009882 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9883 return EraseInstFromFunction(*OldCall);
9884 return 0;
9885 }
9886
Chris Lattner17be6352004-10-18 02:59:09 +00009887 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9888 // This instruction is not reachable, just remove it. We insert a store to
9889 // undef so that we know that this code is not reachable, despite the fact
9890 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +00009891 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009892 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Chris Lattner17be6352004-10-18 02:59:09 +00009893 CS.getInstruction());
9894
9895 if (!CS.getInstruction()->use_empty())
9896 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009897 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009898
9899 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9900 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009901 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +00009902 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009903 }
Chris Lattner17be6352004-10-18 02:59:09 +00009904 return EraseInstFromFunction(*CS.getInstruction());
9905 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009906
Duncan Sandscdb6d922007-09-17 10:26:40 +00009907 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9908 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9909 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9910 return transformCallThroughTrampoline(CS);
9911
Chris Lattner6c266db2003-10-07 22:54:13 +00009912 const PointerType *PTy = cast<PointerType>(Callee->getType());
9913 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9914 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009915 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009916 // See if we can optimize any arguments passed through the varargs area of
9917 // the call.
9918 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009919 E = CS.arg_end(); I != E; ++I, ++ix) {
9920 CastInst *CI = dyn_cast<CastInst>(*I);
9921 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9922 *I = CI->getOperand(0);
9923 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009924 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009925 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009926 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009927
Duncan Sandsf0c33542007-12-19 21:13:37 +00009928 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009929 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009930 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009931 Changed = true;
9932 }
9933
Chris Lattner6c266db2003-10-07 22:54:13 +00009934 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009935}
9936
Chris Lattner9fe38862003-06-19 17:00:31 +00009937// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9938// attempt to move the cast to the arguments of the call/invoke.
9939//
9940bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9941 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9942 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009943 if (CE->getOpcode() != Instruction::BitCast ||
9944 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009945 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009946 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009947 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009948 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009949
9950 // Okay, this is a cast from a function to a different type. Unless doing so
9951 // would cause a type conversion of one of our arguments, change this call to
9952 // be a direct call with arguments casted to the appropriate types.
9953 //
9954 const FunctionType *FT = Callee->getFunctionType();
9955 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009956 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009957
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009958 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009959 return false; // TODO: Handle multiple return values.
9960
Chris Lattnerf78616b2004-01-14 06:06:08 +00009961 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009962 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009963 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009964 // Conversion is ok if changing from one pointer type to another or from
9965 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009966 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00009967 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009968 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00009969 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +00009970 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009971
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009972 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009973 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +00009974 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009975 return false; // Cannot transform this return value.
9976
Chris Lattner58d74912008-03-12 17:45:29 +00009977 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009978 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009979 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009980 return false; // Attribute not compatible with transformed value.
9981 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009982
Chris Lattnerf78616b2004-01-14 06:06:08 +00009983 // If the callsite is an invoke instruction, and the return value is used by
9984 // a PHI node in a successor, we cannot change the return type of the call
9985 // because there is no place to put the cast instruction (without breaking
9986 // the critical edge). Bail out in this case.
9987 if (!Caller->use_empty())
9988 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9989 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9990 UI != E; ++UI)
9991 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9992 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009993 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009994 return false;
9995 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009996
9997 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9998 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009999
Chris Lattner9fe38862003-06-19 17:00:31 +000010000 CallSite::arg_iterator AI = CS.arg_begin();
10001 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10002 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010003 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010004
10005 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010006 return false; // Cannot transform this parameter value.
10007
Devang Patel19c87462008-09-26 22:53:05 +000010008 if (CallerPAL.getParamAttributes(i + 1)
10009 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010010 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010011
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010012 // Converting from one pointer type to another or between a pointer and an
10013 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010014 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010015 (TD && ((isa<PointerType>(ParamTy) ||
10016 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10017 (isa<PointerType>(ActTy) ||
10018 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010019 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010020 }
10021
10022 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010023 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010024 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010025
Chris Lattner58d74912008-03-12 17:45:29 +000010026 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10027 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010028 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010029 // won't be dropping them. Check that these extra arguments have attributes
10030 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010031 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10032 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010033 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010034 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010035 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010036 return false;
10037 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010038
Chris Lattner9fe38862003-06-19 17:00:31 +000010039 // Okay, we decided that this is a safe thing to do: go ahead and start
10040 // inserting cast instructions as necessary...
10041 std::vector<Value*> Args;
10042 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010043 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010044 attrVec.reserve(NumCommonArgs);
10045
10046 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010047 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010048
10049 // If the return value is not being used, the type may not be compatible
10050 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010051 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010052
10053 // Add the new return attributes.
10054 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010055 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010056
10057 AI = CS.arg_begin();
10058 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10059 const Type *ParamTy = FT->getParamType(i);
10060 if ((*AI)->getType() == ParamTy) {
10061 Args.push_back(*AI);
10062 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010063 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010064 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010065 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010066 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010067
10068 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010069 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010070 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010071 }
10072
10073 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010074 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010075 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010076 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010077
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010078 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010079 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010080 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010081 errs() << "WARNING: While resolving call to function '"
10082 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010083 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010084 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010085 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10086 const Type *PTy = getPromotedType((*AI)->getType());
10087 if (PTy != (*AI)->getType()) {
10088 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010089 Instruction::CastOps opcode =
10090 CastInst::getCastOpcode(*AI, false, PTy, false);
10091 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010092 } else {
10093 Args.push_back(*AI);
10094 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010095
Duncan Sandse1e520f2008-01-13 08:02:44 +000010096 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010097 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010098 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010099 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010100 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010101 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010102
Devang Patel19c87462008-09-26 22:53:05 +000010103 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10104 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10105
Owen Anderson1d0be152009-08-13 21:58:54 +000010106 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010107 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010108
Eric Christophera66297a2009-07-25 02:45:27 +000010109 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10110 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010111
Chris Lattner9fe38862003-06-19 17:00:31 +000010112 Instruction *NC;
10113 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010114 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010115 Args.begin(), Args.end(),
10116 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010117 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010118 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010119 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010120 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10121 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010122 CallInst *CI = cast<CallInst>(Caller);
10123 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010124 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010125 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010126 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010127 }
10128
Chris Lattner6934a042007-02-11 01:23:03 +000010129 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010130 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010131 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010132 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010133 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010134 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010135 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010136
10137 // If this is an invoke instruction, we should insert it after the first
10138 // non-phi, instruction in the normal successor block.
10139 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010140 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010141 InsertNewInstBefore(NC, *I);
10142 } else {
10143 // Otherwise, it's a call, just insert cast right after the call instr
10144 InsertNewInstBefore(NC, *Caller);
10145 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010146 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010147 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010148 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010149 }
10150 }
10151
Owen Anderson1d0be152009-08-13 21:58:54 +000010152 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010153 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010154 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010155 Worklist.Remove(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010156 return true;
10157}
10158
Duncan Sandscdb6d922007-09-17 10:26:40 +000010159// transformCallThroughTrampoline - Turn a call to a function created by the
10160// init_trampoline intrinsic into a direct call to the underlying function.
10161//
10162Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10163 Value *Callee = CS.getCalledValue();
10164 const PointerType *PTy = cast<PointerType>(Callee->getType());
10165 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010166 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010167
10168 // If the call already has the 'nest' attribute somewhere then give up -
10169 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010170 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010171 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010172
10173 IntrinsicInst *Tramp =
10174 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10175
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010176 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010177 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10178 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10179
Devang Patel05988662008-09-25 21:00:45 +000010180 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010181 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010182 unsigned NestIdx = 1;
10183 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010184 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010185
10186 // Look for a parameter marked with the 'nest' attribute.
10187 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10188 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010189 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010190 // Record the parameter type and any other attributes.
10191 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010192 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010193 break;
10194 }
10195
10196 if (NestTy) {
10197 Instruction *Caller = CS.getInstruction();
10198 std::vector<Value*> NewArgs;
10199 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10200
Devang Patel05988662008-09-25 21:00:45 +000010201 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010202 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010203
Duncan Sandscdb6d922007-09-17 10:26:40 +000010204 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010205 // mean appending it. Likewise for attributes.
10206
Devang Patel19c87462008-09-26 22:53:05 +000010207 // Add any result attributes.
10208 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010209 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010210
Duncan Sandscdb6d922007-09-17 10:26:40 +000010211 {
10212 unsigned Idx = 1;
10213 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10214 do {
10215 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010216 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010217 Value *NestVal = Tramp->getOperand(3);
10218 if (NestVal->getType() != NestTy)
10219 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10220 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010221 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010222 }
10223
10224 if (I == E)
10225 break;
10226
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010227 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010228 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010229 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010230 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010231 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010232
10233 ++Idx, ++I;
10234 } while (1);
10235 }
10236
Devang Patel19c87462008-09-26 22:53:05 +000010237 // Add any function attributes.
10238 if (Attributes Attr = Attrs.getFnAttributes())
10239 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10240
Duncan Sandscdb6d922007-09-17 10:26:40 +000010241 // The trampoline may have been bitcast to a bogus type (FTy).
10242 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010243 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010244
Duncan Sandscdb6d922007-09-17 10:26:40 +000010245 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010246 NewTypes.reserve(FTy->getNumParams()+1);
10247
Duncan Sandscdb6d922007-09-17 10:26:40 +000010248 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010249 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010250 {
10251 unsigned Idx = 1;
10252 FunctionType::param_iterator I = FTy->param_begin(),
10253 E = FTy->param_end();
10254
10255 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010256 if (Idx == NestIdx)
10257 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010258 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010259
10260 if (I == E)
10261 break;
10262
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010263 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010264 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010265
10266 ++Idx, ++I;
10267 } while (1);
10268 }
10269
10270 // Replace the trampoline call with a direct call. Let the generic
10271 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010272 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010273 FTy->isVarArg());
10274 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010275 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010276 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010277 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010278 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10279 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010280
10281 Instruction *NewCaller;
10282 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010283 NewCaller = InvokeInst::Create(NewCallee,
10284 II->getNormalDest(), II->getUnwindDest(),
10285 NewArgs.begin(), NewArgs.end(),
10286 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010287 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010288 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010289 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010290 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10291 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010292 if (cast<CallInst>(Caller)->isTailCall())
10293 cast<CallInst>(NewCaller)->setTailCall();
10294 cast<CallInst>(NewCaller)->
10295 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010296 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010297 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010298 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010299 Caller->replaceAllUsesWith(NewCaller);
10300 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010301 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010302 return 0;
10303 }
10304 }
10305
10306 // Replace the trampoline call with a direct call. Since there is no 'nest'
10307 // parameter, there is no need to adjust the argument list. Let the generic
10308 // code sort out any function type mismatches.
10309 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010310 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010311 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010312 CS.setCalledFunction(NewCallee);
10313 return CS.getInstruction();
10314}
10315
Chris Lattner7da52b22006-11-01 04:51:18 +000010316/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10317/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10318/// and a single binop.
10319Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10320 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010321 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010322 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010323 Value *LHSVal = FirstInst->getOperand(0);
10324 Value *RHSVal = FirstInst->getOperand(1);
10325
10326 const Type *LHSType = LHSVal->getType();
10327 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010328
10329 // Scan to see if all operands are the same opcode, all have one use, and all
10330 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010331 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010332 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010333 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010334 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010335 // types or GEP's with different index types.
10336 I->getOperand(0)->getType() != LHSType ||
10337 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010338 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010339
10340 // If they are CmpInst instructions, check their predicates
10341 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10342 if (cast<CmpInst>(I)->getPredicate() !=
10343 cast<CmpInst>(FirstInst)->getPredicate())
10344 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010345
10346 // Keep track of which operand needs a phi node.
10347 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10348 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010349 }
10350
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010351 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010352
Chris Lattner7da52b22006-11-01 04:51:18 +000010353 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010354 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010355 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010356 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010357 NewLHS = PHINode::Create(LHSType,
10358 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010359 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10360 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010361 InsertNewInstBefore(NewLHS, PN);
10362 LHSVal = NewLHS;
10363 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010364
10365 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010366 NewRHS = PHINode::Create(RHSType,
10367 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010368 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10369 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010370 InsertNewInstBefore(NewRHS, PN);
10371 RHSVal = NewRHS;
10372 }
10373
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010374 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010375 if (NewLHS || NewRHS) {
10376 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10377 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10378 if (NewLHS) {
10379 Value *NewInLHS = InInst->getOperand(0);
10380 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10381 }
10382 if (NewRHS) {
10383 Value *NewInRHS = InInst->getOperand(1);
10384 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10385 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010386 }
10387 }
10388
Chris Lattner7da52b22006-11-01 04:51:18 +000010389 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010390 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010391 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010392 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010393 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010394}
10395
Chris Lattner05f18922008-12-01 02:34:36 +000010396Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10397 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10398
10399 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10400 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010401 // This is true if all GEP bases are allocas and if all indices into them are
10402 // constants.
10403 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010404
10405 // Scan to see if all operands are the same opcode, all have one use, and all
10406 // kill their operands (i.e. the operands have one use).
10407 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10408 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10409 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10410 GEP->getNumOperands() != FirstInst->getNumOperands())
10411 return 0;
10412
Chris Lattner36d3e322009-02-21 00:46:50 +000010413 // Keep track of whether or not all GEPs are of alloca pointers.
10414 if (AllBasePointersAreAllocas &&
10415 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10416 !GEP->hasAllConstantIndices()))
10417 AllBasePointersAreAllocas = false;
10418
Chris Lattner05f18922008-12-01 02:34:36 +000010419 // Compare the operand lists.
10420 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10421 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10422 continue;
10423
10424 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10425 // if one of the PHIs has a constant for the index. The index may be
10426 // substantially cheaper to compute for the constants, so making it a
10427 // variable index could pessimize the path. This also handles the case
10428 // for struct indices, which must always be constant.
10429 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10430 isa<ConstantInt>(GEP->getOperand(op)))
10431 return 0;
10432
10433 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10434 return 0;
10435 FixedOperands[op] = 0; // Needs a PHI.
10436 }
10437 }
10438
Chris Lattner36d3e322009-02-21 00:46:50 +000010439 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010440 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010441 // offset calculation, but all the predecessors will have to materialize the
10442 // stack address into a register anyway. We'd actually rather *clone* the
10443 // load up into the predecessors so that we have a load of a gep of an alloca,
10444 // which can usually all be folded into the load.
10445 if (AllBasePointersAreAllocas)
10446 return 0;
10447
Chris Lattner05f18922008-12-01 02:34:36 +000010448 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10449 // that is variable.
10450 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10451
10452 bool HasAnyPHIs = false;
10453 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10454 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10455 Value *FirstOp = FirstInst->getOperand(i);
10456 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10457 FirstOp->getName()+".pn");
10458 InsertNewInstBefore(NewPN, PN);
10459
10460 NewPN->reserveOperandSpace(e);
10461 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10462 OperandPhis[i] = NewPN;
10463 FixedOperands[i] = NewPN;
10464 HasAnyPHIs = true;
10465 }
10466
10467
10468 // Add all operands to the new PHIs.
10469 if (HasAnyPHIs) {
10470 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10471 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10472 BasicBlock *InBB = PN.getIncomingBlock(i);
10473
10474 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10475 if (PHINode *OpPhi = OperandPhis[op])
10476 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10477 }
10478 }
10479
10480 Value *Base = FixedOperands[0];
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010481 GetElementPtrInst *GEP =
10482 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10483 FixedOperands.end());
10484 if (cast<GEPOperator>(FirstInst)->isInBounds())
10485 cast<GEPOperator>(GEP)->setIsInBounds(true);
10486 return GEP;
Chris Lattner05f18922008-12-01 02:34:36 +000010487}
10488
10489
Chris Lattner21550882009-02-23 05:56:17 +000010490/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10491/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010492/// obvious the value of the load is not changed from the point of the load to
10493/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010494///
10495/// Finally, it is safe, but not profitable, to sink a load targetting a
10496/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10497/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010498static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010499 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10500
10501 for (++BBI; BBI != E; ++BBI)
10502 if (BBI->mayWriteToMemory())
10503 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010504
10505 // Check for non-address taken alloca. If not address-taken already, it isn't
10506 // profitable to do this xform.
10507 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10508 bool isAddressTaken = false;
10509 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10510 UI != E; ++UI) {
10511 if (isa<LoadInst>(UI)) continue;
10512 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10513 // If storing TO the alloca, then the address isn't taken.
10514 if (SI->getOperand(1) == AI) continue;
10515 }
10516 isAddressTaken = true;
10517 break;
10518 }
10519
Chris Lattner36d3e322009-02-21 00:46:50 +000010520 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010521 return false;
10522 }
10523
Chris Lattner36d3e322009-02-21 00:46:50 +000010524 // If this load is a load from a GEP with a constant offset from an alloca,
10525 // then we don't want to sink it. In its present form, it will be
10526 // load [constant stack offset]. Sinking it will cause us to have to
10527 // materialize the stack addresses in each predecessor in a register only to
10528 // do a shared load from register in the successor.
10529 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10530 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10531 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10532 return false;
10533
Chris Lattner76c73142006-11-01 07:13:54 +000010534 return true;
10535}
10536
Chris Lattner9fe38862003-06-19 17:00:31 +000010537
Chris Lattnerbac32862004-11-14 19:13:23 +000010538// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10539// operator and they all are only used by the PHI, PHI together their
10540// inputs, and do the operation once, to the result of the PHI.
10541Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10542 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10543
10544 // Scan the instruction, looking for input operations that can be folded away.
10545 // If all input operands to the phi are the same instruction (e.g. a cast from
10546 // the same type or "+42") we can pull the operation through the PHI, reducing
10547 // code size and simplifying code.
10548 Constant *ConstantOp = 0;
10549 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010550 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010551 if (isa<CastInst>(FirstInst)) {
10552 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010553 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010554 // Can fold binop, compare or shift here if the RHS is a constant,
10555 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010556 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010557 if (ConstantOp == 0)
10558 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010559 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10560 isVolatile = LI->isVolatile();
10561 // We can't sink the load if the loaded value could be modified between the
10562 // load and the PHI.
10563 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010564 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010565 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010566
10567 // If the PHI is of volatile loads and the load block has multiple
10568 // successors, sinking it would remove a load of the volatile value from
10569 // the path through the other successor.
10570 if (isVolatile &&
10571 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10572 return 0;
10573
Chris Lattner9c080502006-11-01 07:43:41 +000010574 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010575 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010576 } else {
10577 return 0; // Cannot fold this operation.
10578 }
10579
10580 // Check to see if all arguments are the same operation.
10581 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10582 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10583 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010584 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010585 return 0;
10586 if (CastSrcTy) {
10587 if (I->getOperand(0)->getType() != CastSrcTy)
10588 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010589 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010590 // We can't sink the load if the loaded value could be modified between
10591 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010592 if (LI->isVolatile() != isVolatile ||
10593 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010594 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010595 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010596
Chris Lattner71042962008-07-08 17:18:32 +000010597 // If the PHI is of volatile loads and the load block has multiple
10598 // successors, sinking it would remove a load of the volatile value from
10599 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010600 if (isVolatile &&
10601 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10602 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010603
Chris Lattnerbac32862004-11-14 19:13:23 +000010604 } else if (I->getOperand(1) != ConstantOp) {
10605 return 0;
10606 }
10607 }
10608
10609 // Okay, they are all the same operation. Create a new PHI node of the
10610 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010611 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10612 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010613 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010614
10615 Value *InVal = FirstInst->getOperand(0);
10616 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010617
10618 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010619 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10620 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10621 if (NewInVal != InVal)
10622 InVal = 0;
10623 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10624 }
10625
10626 Value *PhiVal;
10627 if (InVal) {
10628 // The new PHI unions all of the same values together. This is really
10629 // common, so we handle it intelligently here for compile-time speed.
10630 PhiVal = InVal;
10631 delete NewPN;
10632 } else {
10633 InsertNewInstBefore(NewPN, PN);
10634 PhiVal = NewPN;
10635 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010636
Chris Lattnerbac32862004-11-14 19:13:23 +000010637 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010638 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010639 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010640 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010641 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010642 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010643 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010644 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010645 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10646
10647 // If this was a volatile load that we are merging, make sure to loop through
10648 // and mark all the input loads as non-volatile. If we don't do this, we will
10649 // insert a new volatile load and the old ones will not be deletable.
10650 if (isVolatile)
10651 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10652 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10653
10654 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010655}
Chris Lattnera1be5662002-05-02 17:06:02 +000010656
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010657/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10658/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010659static bool DeadPHICycle(PHINode *PN,
10660 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010661 if (PN->use_empty()) return true;
10662 if (!PN->hasOneUse()) return false;
10663
10664 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010665 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010666 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010667
10668 // Don't scan crazily complex things.
10669 if (PotentiallyDeadPHIs.size() == 16)
10670 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010671
10672 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10673 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010674
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010675 return false;
10676}
10677
Chris Lattnercf5008a2007-11-06 21:52:06 +000010678/// PHIsEqualValue - Return true if this phi node is always equal to
10679/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10680/// z = some value; x = phi (y, z); y = phi (x, z)
10681static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10682 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10683 // See if we already saw this PHI node.
10684 if (!ValueEqualPHIs.insert(PN))
10685 return true;
10686
10687 // Don't scan crazily complex things.
10688 if (ValueEqualPHIs.size() == 16)
10689 return false;
10690
10691 // Scan the operands to see if they are either phi nodes or are equal to
10692 // the value.
10693 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10694 Value *Op = PN->getIncomingValue(i);
10695 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10696 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10697 return false;
10698 } else if (Op != NonPhiInVal)
10699 return false;
10700 }
10701
10702 return true;
10703}
10704
10705
Chris Lattner473945d2002-05-06 18:06:38 +000010706// PHINode simplification
10707//
Chris Lattner7e708292002-06-25 16:13:24 +000010708Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010709 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010710 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010711
Owen Anderson7e057142006-07-10 22:03:18 +000010712 if (Value *V = PN.hasConstantValue())
10713 return ReplaceInstUsesWith(PN, V);
10714
Owen Anderson7e057142006-07-10 22:03:18 +000010715 // If all PHI operands are the same operation, pull them through the PHI,
10716 // reducing code size.
10717 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010718 isa<Instruction>(PN.getIncomingValue(1)) &&
10719 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10720 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10721 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10722 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010723 PN.getIncomingValue(0)->hasOneUse())
10724 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10725 return Result;
10726
10727 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10728 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10729 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010730 if (PN.hasOneUse()) {
10731 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10732 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010733 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010734 PotentiallyDeadPHIs.insert(&PN);
10735 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010736 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010737 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010738
10739 // If this phi has a single use, and if that use just computes a value for
10740 // the next iteration of a loop, delete the phi. This occurs with unused
10741 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10742 // common case here is good because the only other things that catch this
10743 // are induction variable analysis (sometimes) and ADCE, which is only run
10744 // late.
10745 if (PHIUser->hasOneUse() &&
10746 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10747 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010748 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010749 }
10750 }
Owen Anderson7e057142006-07-10 22:03:18 +000010751
Chris Lattnercf5008a2007-11-06 21:52:06 +000010752 // We sometimes end up with phi cycles that non-obviously end up being the
10753 // same value, for example:
10754 // z = some value; x = phi (y, z); y = phi (x, z)
10755 // where the phi nodes don't necessarily need to be in the same block. Do a
10756 // quick check to see if the PHI node only contains a single non-phi value, if
10757 // so, scan to see if the phi cycle is actually equal to that value.
10758 {
10759 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10760 // Scan for the first non-phi operand.
10761 while (InValNo != NumOperandVals &&
10762 isa<PHINode>(PN.getIncomingValue(InValNo)))
10763 ++InValNo;
10764
10765 if (InValNo != NumOperandVals) {
10766 Value *NonPhiInVal = PN.getOperand(InValNo);
10767
10768 // Scan the rest of the operands to see if there are any conflicts, if so
10769 // there is no need to recursively scan other phis.
10770 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10771 Value *OpVal = PN.getIncomingValue(InValNo);
10772 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10773 break;
10774 }
10775
10776 // If we scanned over all operands, then we have one unique value plus
10777 // phi values. Scan PHI nodes to see if they all merge in each other or
10778 // the value.
10779 if (InValNo == NumOperandVals) {
10780 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10781 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10782 return ReplaceInstUsesWith(PN, NonPhiInVal);
10783 }
10784 }
10785 }
Chris Lattner60921c92003-12-19 05:58:40 +000010786 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010787}
10788
Chris Lattner7e708292002-06-25 16:13:24 +000010789Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010790 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000010791 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010792 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010793 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010794
Chris Lattnere87597f2004-10-16 18:11:37 +000010795 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010796 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010797
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010798 bool HasZeroPointerIndex = false;
10799 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10800 HasZeroPointerIndex = C->isNullValue();
10801
10802 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010803 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010804
Chris Lattner28977af2004-04-05 01:30:19 +000010805 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010806 if (TD) {
10807 bool MadeChange = false;
10808 unsigned PtrSize = TD->getPointerSizeInBits();
10809
10810 gep_type_iterator GTI = gep_type_begin(GEP);
10811 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10812 I != E; ++I, ++GTI) {
10813 if (!isa<SequentialType>(*GTI)) continue;
10814
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010815 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010816 // to what we need. If narrower, sign-extend it to what we need. This
10817 // explicit cast can make subsequent optimizations more obvious.
10818 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000010819 if (OpBits == PtrSize)
10820 continue;
10821
Chris Lattner2345d1d2009-08-30 20:01:10 +000010822 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010823 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010824 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010825 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010826 }
Chris Lattner28977af2004-04-05 01:30:19 +000010827
Chris Lattner90ac28c2002-08-02 19:29:35 +000010828 // Combine Indices - If the source pointer to this getelementptr instruction
10829 // is a getelementptr instruction, combine the indices of the two
10830 // getelementptr instructions into a single instruction.
10831 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010832 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010833 // Note that if our source is a gep chain itself that we wait for that
10834 // chain to be resolved before we perform this transformation. This
10835 // avoids us creating a TON of code in some cases.
10836 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010837 if (GetElementPtrInst *SrcGEP =
10838 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10839 if (SrcGEP->getNumOperands() == 2)
10840 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010841
Chris Lattner72588fc2007-02-15 22:48:32 +000010842 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010843
10844 // Find out whether the last index in the source GEP is a sequential idx.
10845 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010846 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10847 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010848 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010849
Chris Lattner90ac28c2002-08-02 19:29:35 +000010850 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010851 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010852 // Replace: gep (gep %P, long B), long A, ...
10853 // With: T = long A+B; gep %P, T, ...
10854 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010855 Value *Sum;
10856 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10857 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010858 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010859 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010860 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010861 Sum = SO1;
10862 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010863 // If they aren't the same type, then the input hasn't been processed
10864 // by the loop above yet (which canonicalizes sequential index types to
10865 // intptr_t). Just avoid transforming this until the input has been
10866 // normalized.
10867 if (SO1->getType() != GO1->getType())
10868 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010869 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000010870 }
Chris Lattner620ce142004-05-07 22:09:22 +000010871
Chris Lattnerab984842009-08-30 05:30:55 +000010872 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010873 if (Src->getNumOperands() == 2) {
10874 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000010875 GEP.setOperand(1, Sum);
10876 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000010877 }
Chris Lattnerab984842009-08-30 05:30:55 +000010878 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010879 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000010880 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000010881 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010882 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010883 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010884 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000010885 Indices.append(Src->op_begin()+1, Src->op_end());
10886 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010887 }
10888
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010889 if (!Indices.empty()) {
Chris Lattnerccf4b342009-08-30 04:49:01 +000010890 GetElementPtrInst *NewGEP =
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010891 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000010892 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000010893 if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010894 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10895 return NewGEP;
10896 }
Chris Lattner6e24d832009-08-30 05:00:50 +000010897 }
10898
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010899 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10900 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000010901 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000010902
Chris Lattner2de23192009-08-30 20:38:21 +000010903 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10904 // want to change the gep until the bitcasts are eliminated.
10905 if (getBitCastOperand(X)) {
10906 Worklist.AddValue(PtrOp);
10907 return 0;
10908 }
10909
Chris Lattner963f4ba2009-08-30 20:36:46 +000010910 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10911 // into : GEP [10 x i8]* X, i32 0, ...
10912 //
10913 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10914 // into : GEP i8* X, ...
10915 //
10916 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000010917 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000010918 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10919 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010920 if (const ArrayType *CATy =
10921 dyn_cast<ArrayType>(CPTy->getElementType())) {
10922 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10923 if (CATy->getElementType() == XTy->getElementType()) {
10924 // -> GEP i8* X, ...
10925 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010926 GetElementPtrInst *NewGEP =
10927 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10928 GEP.getName());
10929 if (cast<GEPOperator>(&GEP)->isInBounds())
10930 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10931 return NewGEP;
Chris Lattner963f4ba2009-08-30 20:36:46 +000010932 }
10933
10934 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010935 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000010936 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010937 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010938 // At this point, we know that the cast source type is a pointer
10939 // to an array of the same type as the destination pointer
10940 // array. Because the array type is never stepped over (there
10941 // is a leading zero) we can fold the cast into this GEP.
10942 GEP.setOperand(0, X);
10943 return &GEP;
10944 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010945 }
10946 }
Chris Lattnereed48272005-09-13 00:40:14 +000010947 } else if (GEP.getNumOperands() == 2) {
10948 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010949 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10950 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010951 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10952 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010953 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000010954 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10955 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010956 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000010957 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000010958 Idx[1] = GEP.getOperand(1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010959 Value *NewGEP =
10960 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010961 if (cast<GEPOperator>(&GEP)->isInBounds())
10962 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000010963 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010964 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010965 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010966
10967 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010968 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010969 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010970 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010971
Owen Anderson1d0be152009-08-13 21:58:54 +000010972 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010973 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000010974 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010975
10976 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10977 // allow either a mul, shift, or constant here.
10978 Value *NewIdx = 0;
10979 ConstantInt *Scale = 0;
10980 if (ArrayEltSize == 1) {
10981 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000010982 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010983 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010984 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010985 Scale = CI;
10986 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10987 if (Inst->getOpcode() == Instruction::Shl &&
10988 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010989 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10990 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000010991 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000010992 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010993 NewIdx = Inst->getOperand(0);
10994 } else if (Inst->getOpcode() == Instruction::Mul &&
10995 isa<ConstantInt>(Inst->getOperand(1))) {
10996 Scale = cast<ConstantInt>(Inst->getOperand(1));
10997 NewIdx = Inst->getOperand(0);
10998 }
10999 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011000
Chris Lattner7835cdd2005-09-13 18:36:04 +000011001 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011002 // out, perform the transformation. Note, we don't know whether Scale is
11003 // signed or not. We'll use unsigned version of division/modulo
11004 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011005 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011006 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011007 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011008 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011009 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011010 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11011 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011012 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011013 }
11014
11015 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011016 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011017 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011018 Idx[1] = NewIdx;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011019 Value *NewGEP = Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011020 if (cast<GEPOperator>(&GEP)->isInBounds())
11021 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000011022 // The NewGEP must be pointer typed, so must the old one -> BitCast
11023 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011024 }
11025 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011026 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011027 }
Chris Lattner58407792009-01-09 04:53:57 +000011028
Chris Lattner46cd5a12009-01-09 05:44:56 +000011029 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011030 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011031 /// Y = gep X, <...constant indices...>
11032 /// into a gep of the original struct. This is important for SROA and alias
11033 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011034 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011035 if (TD &&
11036 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011037 // Determine how much the GEP moves the pointer. We are guaranteed to get
11038 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011039 ConstantInt *OffsetV =
11040 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011041 int64_t Offset = OffsetV->getSExtValue();
11042
11043 // If this GEP instruction doesn't move the pointer, just replace the GEP
11044 // with a bitcast of the real input to the dest type.
11045 if (Offset == 0) {
11046 // If the bitcast is of an allocation, and the allocation will be
11047 // converted to match the type of the cast, don't touch this.
11048 if (isa<AllocationInst>(BCI->getOperand(0))) {
11049 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11050 if (Instruction *I = visitBitCast(*BCI)) {
11051 if (I != BCI) {
11052 I->takeName(BCI);
11053 BCI->getParent()->getInstList().insert(BCI, I);
11054 ReplaceInstUsesWith(*BCI, I);
11055 }
11056 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011057 }
Chris Lattner58407792009-01-09 04:53:57 +000011058 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011059 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011060 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011061
11062 // Otherwise, if the offset is non-zero, we need to find out if there is a
11063 // field at Offset in 'A's type. If so, we can pull the cast through the
11064 // GEP.
11065 SmallVector<Value*, 8> NewIndices;
11066 const Type *InTy =
11067 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011068 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011069 Value *NGEP = Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11070 NewIndices.end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011071 if (cast<GEPOperator>(&GEP)->isInBounds())
11072 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011073
11074 if (NGEP->getType() == GEP.getType())
11075 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011076 NGEP->takeName(&GEP);
11077 return new BitCastInst(NGEP, GEP.getType());
11078 }
Chris Lattner58407792009-01-09 04:53:57 +000011079 }
11080 }
11081
Chris Lattner8a2a3112001-12-14 16:52:21 +000011082 return 0;
11083}
11084
Chris Lattner0864acf2002-11-04 16:18:53 +000011085Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11086 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011087 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011088 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11089 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011090 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011091 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011092
11093 // Create and insert the replacement instruction...
11094 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011095 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011096 else {
11097 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011098 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011099 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011100 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011101
Chris Lattner0864acf2002-11-04 16:18:53 +000011102 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011103 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011104 //
11105 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011106 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011107
11108 // Now that I is pointing to the first non-allocation-inst in the block,
11109 // insert our getelementptr instruction...
11110 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011111 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011112 Value *Idx[2];
11113 Idx[0] = NullIdx;
11114 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011115 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11116 New->getName()+".sub", It);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011117 cast<GEPOperator>(V)->setIsInBounds(true);
Chris Lattner0864acf2002-11-04 16:18:53 +000011118
11119 // Now make everything use the getelementptr instead of the original
11120 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011121 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011122 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011123 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011124 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011125 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011126
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011127 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011128 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011129 // Note that we only do this for alloca's, because malloc should allocate
11130 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011131 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011132 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011133
11134 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11135 if (AI.getAlignment() == 0)
11136 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11137 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011138
Chris Lattner0864acf2002-11-04 16:18:53 +000011139 return 0;
11140}
11141
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011142Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11143 Value *Op = FI.getOperand(0);
11144
Chris Lattner17be6352004-10-18 02:59:09 +000011145 // free undef -> unreachable.
11146 if (isa<UndefValue>(Op)) {
11147 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011148 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000011149 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011150 return EraseInstFromFunction(FI);
11151 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011152
Chris Lattner6160e852004-02-28 04:57:37 +000011153 // If we have 'free null' delete the instruction. This can happen in stl code
11154 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011155 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011156 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011157
11158 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11159 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11160 FI.setOperand(0, CI->getOperand(0));
11161 return &FI;
11162 }
11163
11164 // Change free (gep X, 0,0,0,0) into free(X)
11165 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11166 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011167 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011168 FI.setOperand(0, GEPI->getOperand(0));
11169 return &FI;
11170 }
11171 }
11172
11173 // Change free(malloc) into nothing, if the malloc has a single use.
11174 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11175 if (MI->hasOneUse()) {
11176 EraseInstFromFunction(FI);
11177 return EraseInstFromFunction(*MI);
11178 }
Chris Lattner6160e852004-02-28 04:57:37 +000011179
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011180 return 0;
11181}
11182
11183
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011184/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011185static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011186 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011187 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011188 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011189 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011190
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011191 if (TD) {
11192 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11193 // Instead of loading constant c string, use corresponding integer value
11194 // directly if string length is small enough.
11195 std::string Str;
11196 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11197 unsigned len = Str.length();
11198 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11199 unsigned numBits = Ty->getPrimitiveSizeInBits();
11200 // Replace LI with immediate integer store.
11201 if ((numBits >> 3) == len + 1) {
11202 APInt StrVal(numBits, 0);
11203 APInt SingleChar(numBits, 0);
11204 if (TD->isLittleEndian()) {
11205 for (signed i = len-1; i >= 0; i--) {
11206 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11207 StrVal = (StrVal << 8) | SingleChar;
11208 }
11209 } else {
11210 for (unsigned i = 0; i < len; i++) {
11211 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11212 StrVal = (StrVal << 8) | SingleChar;
11213 }
11214 // Append NULL at the end.
11215 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011216 StrVal = (StrVal << 8) | SingleChar;
11217 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011218 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011219 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011220 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011221 }
11222 }
11223 }
11224
Mon P Wang6753f952009-02-07 22:19:29 +000011225 const PointerType *DestTy = cast<PointerType>(CI->getType());
11226 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011227 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011228
11229 // If the address spaces don't match, don't eliminate the cast.
11230 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11231 return 0;
11232
Chris Lattnerb89e0712004-07-13 01:49:43 +000011233 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011234
Reid Spencer42230162007-01-22 05:51:25 +000011235 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011236 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011237 // If the source is an array, the code below will not succeed. Check to
11238 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11239 // constants.
11240 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11241 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11242 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011243 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011244 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011245 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011246 SrcTy = cast<PointerType>(CastOp->getType());
11247 SrcPTy = SrcTy->getElementType();
11248 }
11249
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011250 if (IC.getTargetData() &&
11251 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011252 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011253 // Do not allow turning this into a load of an integer, which is then
11254 // casted to a pointer, this pessimizes pointer analysis a lot.
11255 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011256 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11257 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011258
Chris Lattnerf9527852005-01-31 04:50:46 +000011259 // Okay, we are casting from one integer or pointer type to another of
11260 // the same size. Instead of casting the pointer before the load, cast
11261 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011262 Value *NewLoad =
11263 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011264 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011265 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011266 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011267 }
11268 }
11269 return 0;
11270}
11271
Chris Lattner833b8a42003-06-26 05:06:25 +000011272Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11273 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011274
Dan Gohman9941f742007-07-20 16:34:21 +000011275 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011276 if (TD) {
11277 unsigned KnownAlign =
11278 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11279 if (KnownAlign >
11280 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11281 LI.getAlignment()))
11282 LI.setAlignment(KnownAlign);
11283 }
Dan Gohman9941f742007-07-20 16:34:21 +000011284
Chris Lattner963f4ba2009-08-30 20:36:46 +000011285 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011286 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011287 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011288 return Res;
11289
11290 // None of the following transforms are legal for volatile loads.
11291 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011292
Dan Gohman2276a7b2008-10-15 23:19:35 +000011293 // Do really simple store-to-load forwarding and load CSE, to catch cases
11294 // where there are several consequtive memory accesses to the same location,
11295 // separated by a few arithmetic operations.
11296 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011297 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11298 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011299
Christopher Lambb15147e2007-12-29 07:56:53 +000011300 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11301 const Value *GEPI0 = GEPI->getOperand(0);
11302 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011303 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011304 // Insert a new store to null instruction before the load to indicate
11305 // that this code is not reachable. We do this instead of inserting
11306 // an unreachable instruction directly because we cannot modify the
11307 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011308 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011309 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011310 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011311 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011312 }
Chris Lattner37366c12005-05-01 04:24:53 +000011313
Chris Lattnere87597f2004-10-16 18:11:37 +000011314 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011315 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011316 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011317 if (isa<UndefValue>(C) ||
11318 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011319 // Insert a new store to null instruction before the load to indicate that
11320 // this code is not reachable. We do this instead of inserting an
11321 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011322 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011323 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011324 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011325 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011326
Chris Lattnere87597f2004-10-16 18:11:37 +000011327 // Instcombine load (constant global) into the value loaded.
11328 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011329 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011330 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011331
Chris Lattnere87597f2004-10-16 18:11:37 +000011332 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011333 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011334 if (CE->getOpcode() == Instruction::GetElementPtr) {
11335 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011336 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011337 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011338 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011339 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011340 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011341 if (CE->getOperand(0)->isNullValue()) {
11342 // Insert a new store to null instruction before the load to indicate
11343 // that this code is not reachable. We do this instead of inserting
11344 // an unreachable instruction directly because we cannot modify the
11345 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011346 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011347 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011348 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011349 }
11350
Reid Spencer3da59db2006-11-27 01:05:10 +000011351 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011352 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011353 return Res;
11354 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011355 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011356 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011357
11358 // If this load comes from anywhere in a constant global, and if the global
11359 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011360 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011361 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011362 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011363 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011364 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011365 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011366 }
11367 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011368
Chris Lattner37366c12005-05-01 04:24:53 +000011369 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011370 // Change select and PHI nodes to select values instead of addresses: this
11371 // helps alias analysis out a lot, allows many others simplifications, and
11372 // exposes redundancy in the code.
11373 //
11374 // Note that we cannot do the transformation unless we know that the
11375 // introduced loads cannot trap! Something like this is valid as long as
11376 // the condition is always false: load (select bool %C, int* null, int* %G),
11377 // but it would not be valid if we transformed it to load from null
11378 // unconditionally.
11379 //
11380 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11381 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011382 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11383 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011384 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11385 SI->getOperand(1)->getName()+".val");
11386 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11387 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011388 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011389 }
11390
Chris Lattner684fe212004-09-23 15:46:00 +000011391 // load (select (cond, null, P)) -> load P
11392 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11393 if (C->isNullValue()) {
11394 LI.setOperand(0, SI->getOperand(2));
11395 return &LI;
11396 }
11397
11398 // load (select (cond, P, null)) -> load P
11399 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11400 if (C->isNullValue()) {
11401 LI.setOperand(0, SI->getOperand(1));
11402 return &LI;
11403 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011404 }
11405 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011406 return 0;
11407}
11408
Reid Spencer55af2b52007-01-19 21:20:31 +000011409/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011410/// when possible. This makes it generally easy to do alias analysis and/or
11411/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011412static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11413 User *CI = cast<User>(SI.getOperand(1));
11414 Value *CastOp = CI->getOperand(0);
11415
11416 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011417 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11418 if (SrcTy == 0) return 0;
11419
11420 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011421
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011422 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11423 return 0;
11424
Chris Lattner3914f722009-01-24 01:00:13 +000011425 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11426 /// to its first element. This allows us to handle things like:
11427 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11428 /// on 32-bit hosts.
11429 SmallVector<Value*, 4> NewGEPIndices;
11430
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011431 // If the source is an array, the code below will not succeed. Check to
11432 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11433 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011434 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11435 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011436 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011437 NewGEPIndices.push_back(Zero);
11438
11439 while (1) {
11440 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011441 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011442 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011443 NewGEPIndices.push_back(Zero);
11444 SrcPTy = STy->getElementType(0);
11445 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11446 NewGEPIndices.push_back(Zero);
11447 SrcPTy = ATy->getElementType();
11448 } else {
11449 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011450 }
Chris Lattner3914f722009-01-24 01:00:13 +000011451 }
11452
Owen Andersondebcb012009-07-29 22:17:13 +000011453 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011454 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011455
11456 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11457 return 0;
11458
Chris Lattner71759c42009-01-16 20:12:52 +000011459 // If the pointers point into different address spaces or if they point to
11460 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011461 if (!IC.getTargetData() ||
11462 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011463 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011464 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11465 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011466 return 0;
11467
11468 // Okay, we are casting from one integer or pointer type to another of
11469 // the same size. Instead of casting the pointer before
11470 // the store, cast the value to be stored.
11471 Value *NewCast;
11472 Value *SIOp0 = SI.getOperand(0);
11473 Instruction::CastOps opcode = Instruction::BitCast;
11474 const Type* CastSrcTy = SIOp0->getType();
11475 const Type* CastDstTy = SrcPTy;
11476 if (isa<PointerType>(CastDstTy)) {
11477 if (CastSrcTy->isInteger())
11478 opcode = Instruction::IntToPtr;
11479 } else if (isa<IntegerType>(CastDstTy)) {
11480 if (isa<PointerType>(SIOp0->getType()))
11481 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011482 }
Chris Lattner3914f722009-01-24 01:00:13 +000011483
11484 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11485 // emit a GEP to index into its first field.
11486 if (!NewGEPIndices.empty()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011487 CastOp = IC.Builder->CreateGEP(CastOp, NewGEPIndices.begin(),
11488 NewGEPIndices.end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011489 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner3914f722009-01-24 01:00:13 +000011490 }
11491
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011492 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11493 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011494 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011495}
11496
Chris Lattner4aebaee2008-11-27 08:56:30 +000011497/// equivalentAddressValues - Test if A and B will obviously have the same
11498/// value. This includes recognizing that %t0 and %t1 will have the same
11499/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011500/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011501/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011502/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011503/// %t2 = load i32* %t1
11504///
11505static bool equivalentAddressValues(Value *A, Value *B) {
11506 // Test if the values are trivially equivalent.
11507 if (A == B) return true;
11508
11509 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011510 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11511 // its only used to compare two uses within the same basic block, which
11512 // means that they'll always either have the same value or one of them
11513 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011514 if (isa<BinaryOperator>(A) ||
11515 isa<CastInst>(A) ||
11516 isa<PHINode>(A) ||
11517 isa<GetElementPtrInst>(A))
11518 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011519 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011520 return true;
11521
11522 // Otherwise they may not be equivalent.
11523 return false;
11524}
11525
Dale Johannesen4945c652009-03-03 21:26:39 +000011526// If this instruction has two uses, one of which is a llvm.dbg.declare,
11527// return the llvm.dbg.declare.
11528DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11529 if (!V->hasNUses(2))
11530 return 0;
11531 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11532 UI != E; ++UI) {
11533 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11534 return DI;
11535 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11536 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11537 return DI;
11538 }
11539 }
11540 return 0;
11541}
11542
Chris Lattner2f503e62005-01-31 05:36:43 +000011543Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11544 Value *Val = SI.getOperand(0);
11545 Value *Ptr = SI.getOperand(1);
11546
11547 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011548 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011549 ++NumCombined;
11550 return 0;
11551 }
Chris Lattner836692d2007-01-15 06:51:56 +000011552
11553 // If the RHS is an alloca with a single use, zapify the store, making the
11554 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011555 // If the RHS is an alloca with a two uses, the other one being a
11556 // llvm.dbg.declare, zapify the store and the declare, making the
11557 // alloca dead. We must do this to prevent declare's from affecting
11558 // codegen.
11559 if (!SI.isVolatile()) {
11560 if (Ptr->hasOneUse()) {
11561 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011562 EraseInstFromFunction(SI);
11563 ++NumCombined;
11564 return 0;
11565 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011566 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11567 if (isa<AllocaInst>(GEP->getOperand(0))) {
11568 if (GEP->getOperand(0)->hasOneUse()) {
11569 EraseInstFromFunction(SI);
11570 ++NumCombined;
11571 return 0;
11572 }
11573 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11574 EraseInstFromFunction(*DI);
11575 EraseInstFromFunction(SI);
11576 ++NumCombined;
11577 return 0;
11578 }
11579 }
11580 }
11581 }
11582 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11583 EraseInstFromFunction(*DI);
11584 EraseInstFromFunction(SI);
11585 ++NumCombined;
11586 return 0;
11587 }
Chris Lattner836692d2007-01-15 06:51:56 +000011588 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011589
Dan Gohman9941f742007-07-20 16:34:21 +000011590 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011591 if (TD) {
11592 unsigned KnownAlign =
11593 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11594 if (KnownAlign >
11595 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11596 SI.getAlignment()))
11597 SI.setAlignment(KnownAlign);
11598 }
Dan Gohman9941f742007-07-20 16:34:21 +000011599
Dale Johannesenacb51a32009-03-03 01:43:03 +000011600 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011601 // stores to the same location, separated by a few arithmetic operations. This
11602 // situation often occurs with bitfield accesses.
11603 BasicBlock::iterator BBI = &SI;
11604 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11605 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011606 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011607 // Don't count debug info directives, lest they affect codegen,
11608 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11609 // It is necessary for correctness to skip those that feed into a
11610 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011611 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011612 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011613 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011614 continue;
11615 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011616
11617 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11618 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011619 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11620 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011621 ++NumDeadStore;
11622 ++BBI;
11623 EraseInstFromFunction(*PrevSI);
11624 continue;
11625 }
11626 break;
11627 }
11628
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011629 // If this is a load, we have to stop. However, if the loaded value is from
11630 // the pointer we're loading and is producing the pointer we're storing,
11631 // then *this* store is dead (X = load P; store X -> P).
11632 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011633 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11634 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011635 EraseInstFromFunction(SI);
11636 ++NumCombined;
11637 return 0;
11638 }
11639 // Otherwise, this is a load from some other location. Stores before it
11640 // may not be dead.
11641 break;
11642 }
11643
Chris Lattner9ca96412006-02-08 03:25:32 +000011644 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011645 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011646 break;
11647 }
11648
11649
11650 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011651
11652 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011653 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011654 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011655 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011656 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011657 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011658 ++NumCombined;
11659 }
11660 return 0; // Do not modify these!
11661 }
11662
11663 // store undef, Ptr -> noop
11664 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011665 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011666 ++NumCombined;
11667 return 0;
11668 }
11669
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011670 // If the pointer destination is a cast, see if we can fold the cast into the
11671 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011672 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011673 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11674 return Res;
11675 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011676 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011677 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11678 return Res;
11679
Chris Lattner408902b2005-09-12 23:23:25 +000011680
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011681 // If this store is the last instruction in the basic block (possibly
11682 // excepting debug info instructions and the pointer bitcasts that feed
11683 // into them), and if the block ends with an unconditional branch, try
11684 // to move it to the successor block.
11685 BBI = &SI;
11686 do {
11687 ++BBI;
11688 } while (isa<DbgInfoIntrinsic>(BBI) ||
11689 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011690 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011691 if (BI->isUnconditional())
11692 if (SimplifyStoreAtEndOfBlock(SI))
11693 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011694
Chris Lattner2f503e62005-01-31 05:36:43 +000011695 return 0;
11696}
11697
Chris Lattner3284d1f2007-04-15 00:07:55 +000011698/// SimplifyStoreAtEndOfBlock - Turn things like:
11699/// if () { *P = v1; } else { *P = v2 }
11700/// into a phi node with a store in the successor.
11701///
Chris Lattner31755a02007-04-15 01:02:18 +000011702/// Simplify things like:
11703/// *P = v1; if () { *P = v2; }
11704/// into a phi node with a store in the successor.
11705///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011706bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11707 BasicBlock *StoreBB = SI.getParent();
11708
11709 // Check to see if the successor block has exactly two incoming edges. If
11710 // so, see if the other predecessor contains a store to the same location.
11711 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011712 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011713
11714 // Determine whether Dest has exactly two predecessors and, if so, compute
11715 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011716 pred_iterator PI = pred_begin(DestBB);
11717 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011718 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011719 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011720 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011721 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011722 return false;
11723
11724 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011725 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011726 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011727 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011728 }
Chris Lattner31755a02007-04-15 01:02:18 +000011729 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011730 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011731
11732 // Bail out if all the relevant blocks aren't distinct (this can happen,
11733 // for example, if SI is in an infinite loop)
11734 if (StoreBB == DestBB || OtherBB == DestBB)
11735 return false;
11736
Chris Lattner31755a02007-04-15 01:02:18 +000011737 // Verify that the other block ends in a branch and is not otherwise empty.
11738 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011739 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011740 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011741 return false;
11742
Chris Lattner31755a02007-04-15 01:02:18 +000011743 // If the other block ends in an unconditional branch, check for the 'if then
11744 // else' case. there is an instruction before the branch.
11745 StoreInst *OtherStore = 0;
11746 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011747 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011748 // Skip over debugging info.
11749 while (isa<DbgInfoIntrinsic>(BBI) ||
11750 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11751 if (BBI==OtherBB->begin())
11752 return false;
11753 --BBI;
11754 }
11755 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011756 OtherStore = dyn_cast<StoreInst>(BBI);
11757 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11758 return false;
11759 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011760 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011761 // destinations is StoreBB, then we have the if/then case.
11762 if (OtherBr->getSuccessor(0) != StoreBB &&
11763 OtherBr->getSuccessor(1) != StoreBB)
11764 return false;
11765
11766 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011767 // if/then triangle. See if there is a store to the same ptr as SI that
11768 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011769 for (;; --BBI) {
11770 // Check to see if we find the matching store.
11771 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11772 if (OtherStore->getOperand(1) != SI.getOperand(1))
11773 return false;
11774 break;
11775 }
Eli Friedman6903a242008-06-13 22:02:12 +000011776 // If we find something that may be using or overwriting the stored
11777 // value, or if we run out of instructions, we can't do the xform.
11778 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011779 BBI == OtherBB->begin())
11780 return false;
11781 }
11782
11783 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011784 // make sure nothing reads or overwrites the stored value in
11785 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011786 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11787 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011788 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011789 return false;
11790 }
11791 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011792
Chris Lattner31755a02007-04-15 01:02:18 +000011793 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011794 Value *MergedVal = OtherStore->getOperand(0);
11795 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011796 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011797 PN->reserveOperandSpace(2);
11798 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011799 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11800 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011801 }
11802
11803 // Advance to a place where it is safe to insert the new store and
11804 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011805 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011806 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11807 OtherStore->isVolatile()), *BBI);
11808
11809 // Nuke the old stores.
11810 EraseInstFromFunction(SI);
11811 EraseInstFromFunction(*OtherStore);
11812 ++NumCombined;
11813 return true;
11814}
11815
Chris Lattner2f503e62005-01-31 05:36:43 +000011816
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011817Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11818 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011819 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011820 BasicBlock *TrueDest;
11821 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011822 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011823 !isa<Constant>(X)) {
11824 // Swap Destinations and condition...
11825 BI.setCondition(X);
11826 BI.setSuccessor(0, FalseDest);
11827 BI.setSuccessor(1, TrueDest);
11828 return &BI;
11829 }
11830
Reid Spencere4d87aa2006-12-23 06:05:41 +000011831 // Cannonicalize fcmp_one -> fcmp_oeq
11832 FCmpInst::Predicate FPred; Value *Y;
11833 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011834 TrueDest, FalseDest)) &&
11835 BI.getCondition()->hasOneUse())
11836 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11837 FPred == FCmpInst::FCMP_OGE) {
11838 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11839 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11840
11841 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011842 BI.setSuccessor(0, FalseDest);
11843 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011844 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011845 return &BI;
11846 }
11847
11848 // Cannonicalize icmp_ne -> icmp_eq
11849 ICmpInst::Predicate IPred;
11850 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011851 TrueDest, FalseDest)) &&
11852 BI.getCondition()->hasOneUse())
11853 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11854 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11855 IPred == ICmpInst::ICMP_SGE) {
11856 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11857 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11858 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011859 BI.setSuccessor(0, FalseDest);
11860 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011861 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011862 return &BI;
11863 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011864
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011865 return 0;
11866}
Chris Lattner0864acf2002-11-04 16:18:53 +000011867
Chris Lattner46238a62004-07-03 00:26:11 +000011868Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11869 Value *Cond = SI.getCondition();
11870 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11871 if (I->getOpcode() == Instruction::Add)
11872 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11873 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11874 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011875 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000011876 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011877 AddRHS));
11878 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000011879 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011880 return &SI;
11881 }
11882 }
11883 return 0;
11884}
11885
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011886Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011887 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011888
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011889 if (!EV.hasIndices())
11890 return ReplaceInstUsesWith(EV, Agg);
11891
11892 if (Constant *C = dyn_cast<Constant>(Agg)) {
11893 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011894 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011895
11896 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000011897 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011898
11899 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11900 // Extract the element indexed by the first index out of the constant
11901 Value *V = C->getOperand(*EV.idx_begin());
11902 if (EV.getNumIndices() > 1)
11903 // Extract the remaining indices out of the constant indexed by the
11904 // first index
11905 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11906 else
11907 return ReplaceInstUsesWith(EV, V);
11908 }
11909 return 0; // Can't handle other constants
11910 }
11911 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11912 // We're extracting from an insertvalue instruction, compare the indices
11913 const unsigned *exti, *exte, *insi, *inse;
11914 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11915 exte = EV.idx_end(), inse = IV->idx_end();
11916 exti != exte && insi != inse;
11917 ++exti, ++insi) {
11918 if (*insi != *exti)
11919 // The insert and extract both reference distinctly different elements.
11920 // This means the extract is not influenced by the insert, and we can
11921 // replace the aggregate operand of the extract with the aggregate
11922 // operand of the insert. i.e., replace
11923 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11924 // %E = extractvalue { i32, { i32 } } %I, 0
11925 // with
11926 // %E = extractvalue { i32, { i32 } } %A, 0
11927 return ExtractValueInst::Create(IV->getAggregateOperand(),
11928 EV.idx_begin(), EV.idx_end());
11929 }
11930 if (exti == exte && insi == inse)
11931 // Both iterators are at the end: Index lists are identical. Replace
11932 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11933 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11934 // with "i32 42"
11935 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11936 if (exti == exte) {
11937 // The extract list is a prefix of the insert list. i.e. replace
11938 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11939 // %E = extractvalue { i32, { i32 } } %I, 1
11940 // with
11941 // %X = extractvalue { i32, { i32 } } %A, 1
11942 // %E = insertvalue { i32 } %X, i32 42, 0
11943 // by switching the order of the insert and extract (though the
11944 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011945 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
11946 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011947 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11948 insi, inse);
11949 }
11950 if (insi == inse)
11951 // The insert list is a prefix of the extract list
11952 // We can simply remove the common indices from the extract and make it
11953 // operate on the inserted value instead of the insertvalue result.
11954 // i.e., replace
11955 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11956 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11957 // with
11958 // %E extractvalue { i32 } { i32 42 }, 0
11959 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11960 exti, exte);
11961 }
11962 // Can't simplify extracts from other values. Note that nested extracts are
11963 // already simplified implicitely by the above (extract ( extract (insert) )
11964 // will be translated into extract ( insert ( extract ) ) first and then just
11965 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011966 return 0;
11967}
11968
Chris Lattner220b0cf2006-03-05 00:22:33 +000011969/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11970/// is to leave as a vector operation.
11971static bool CheapToScalarize(Value *V, bool isConstant) {
11972 if (isa<ConstantAggregateZero>(V))
11973 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011974 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011975 if (isConstant) return true;
11976 // If all elts are the same, we can extract.
11977 Constant *Op0 = C->getOperand(0);
11978 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11979 if (C->getOperand(i) != Op0)
11980 return false;
11981 return true;
11982 }
11983 Instruction *I = dyn_cast<Instruction>(V);
11984 if (!I) return false;
11985
11986 // Insert element gets simplified to the inserted element or is deleted if
11987 // this is constant idx extract element and its a constant idx insertelt.
11988 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11989 isa<ConstantInt>(I->getOperand(2)))
11990 return true;
11991 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11992 return true;
11993 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11994 if (BO->hasOneUse() &&
11995 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11996 CheapToScalarize(BO->getOperand(1), isConstant)))
11997 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011998 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11999 if (CI->hasOneUse() &&
12000 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12001 CheapToScalarize(CI->getOperand(1), isConstant)))
12002 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012003
12004 return false;
12005}
12006
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012007/// Read and decode a shufflevector mask.
12008///
12009/// It turns undef elements into values that are larger than the number of
12010/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012011static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12012 unsigned NElts = SVI->getType()->getNumElements();
12013 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12014 return std::vector<unsigned>(NElts, 0);
12015 if (isa<UndefValue>(SVI->getOperand(2)))
12016 return std::vector<unsigned>(NElts, 2*NElts);
12017
12018 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012019 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012020 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12021 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012022 Result.push_back(NElts*2); // undef -> 8
12023 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012024 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012025 return Result;
12026}
12027
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012028/// FindScalarElement - Given a vector and an element number, see if the scalar
12029/// value is already around as a register, for example if it were inserted then
12030/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012031static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012032 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012033 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12034 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012035 unsigned Width = PTy->getNumElements();
12036 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012037 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012038
12039 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012040 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012041 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012042 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012043 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012044 return CP->getOperand(EltNo);
12045 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12046 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012047 if (!isa<ConstantInt>(III->getOperand(2)))
12048 return 0;
12049 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012050
12051 // If this is an insert to the element we are looking for, return the
12052 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012053 if (EltNo == IIElt)
12054 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012055
12056 // Otherwise, the insertelement doesn't modify the value, recurse on its
12057 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012058 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012059 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012060 unsigned LHSWidth =
12061 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012062 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012063 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012064 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012065 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012066 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012067 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012068 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012069 }
12070
12071 // Otherwise, we don't know.
12072 return 0;
12073}
12074
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012075Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012076 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012077 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012078 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012079
Dan Gohman07a96762007-07-16 14:29:03 +000012080 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012081 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012082 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012083
Reid Spencer9d6565a2007-02-15 02:26:10 +000012084 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012085 // If vector val is constant with all elements the same, replace EI with
12086 // that element. When the elements are not identical, we cannot replace yet
12087 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012088 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012089 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012090 if (C->getOperand(i) != op0) {
12091 op0 = 0;
12092 break;
12093 }
12094 if (op0)
12095 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012096 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012097
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012098 // If extracting a specified index from the vector, see if we can recursively
12099 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012100 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012101 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012102 unsigned VectorWidth =
12103 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012104
12105 // If this is extracting an invalid index, turn this into undef, to avoid
12106 // crashing the code below.
12107 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012108 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012109
Chris Lattner867b99f2006-10-05 06:55:50 +000012110 // This instruction only demands the single element from the input vector.
12111 // If the input vector has a single use, simplify it based on this use
12112 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012113 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012114 APInt UndefElts(VectorWidth, 0);
12115 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012116 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012117 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012118 EI.setOperand(0, V);
12119 return &EI;
12120 }
12121 }
12122
Owen Andersond672ecb2009-07-03 00:17:18 +000012123 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012124 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012125
12126 // If the this extractelement is directly using a bitcast from a vector of
12127 // the same number of elements, see if we can find the source element from
12128 // it. In this case, we will end up needing to bitcast the scalars.
12129 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12130 if (const VectorType *VT =
12131 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12132 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012133 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12134 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012135 return new BitCastInst(Elt, EI.getType());
12136 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012137 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012138
Chris Lattner73fa49d2006-05-25 22:53:38 +000012139 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012140 if (I->hasOneUse()) {
12141 // Push extractelement into predecessor operation if legal and
12142 // profitable to do so
12143 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012144 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12145 if (CheapToScalarize(BO, isConstantElt)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012146 Value *newEI0 =
12147 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12148 EI.getName()+".lhs");
12149 Value *newEI1 =
12150 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12151 EI.getName()+".rhs");
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012152 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012153 }
Chris Lattner08142f22009-08-30 19:47:22 +000012154 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
12155 unsigned AS = LI->getPointerAddressSpace();
12156 Value *Ptr = Builder->CreateBitCast(I->getOperand(0),
12157 PointerType::get(EI.getType(), AS),
12158 I->getOperand(0)->getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012159 Value *GEP =
12160 Builder->CreateGEP(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012161 cast<GEPOperator>(GEP)->setIsInBounds(true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012162
12163 LoadInst *Load = Builder->CreateLoad(GEP, "tmp");
12164
12165 // Make sure the Load goes before the load instruction in the source,
12166 // not wherever the extract happens to be.
Chris Lattner08142f22009-08-30 19:47:22 +000012167 if (Instruction *P = dyn_cast<Instruction>(Ptr))
12168 P->moveBefore(I);
12169 if (Instruction *G = dyn_cast<Instruction>(GEP))
12170 G->moveBefore(I);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012171 Load->moveBefore(I);
12172
Mon P Wang7c4efa62009-08-13 05:12:13 +000012173 return ReplaceInstUsesWith(EI, Load);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012174 }
12175 }
12176 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12177 // Extracting the inserted element?
12178 if (IE->getOperand(2) == EI.getOperand(1))
12179 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12180 // If the inserted and extracted elements are constants, they must not
12181 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012182 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012183 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012184 EI.setOperand(0, IE->getOperand(0));
12185 return &EI;
12186 }
12187 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12188 // If this is extracting an element from a shufflevector, figure out where
12189 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012190 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12191 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012192 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012193 unsigned LHSWidth =
12194 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12195
12196 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012197 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012198 else if (SrcIdx < LHSWidth*2) {
12199 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012200 Src = SVI->getOperand(1);
12201 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012202 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012203 }
Eric Christophera3500da2009-07-25 02:28:41 +000012204 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012205 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12206 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012207 }
12208 }
Eli Friedman2451a642009-07-18 23:06:53 +000012209 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012210 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012211 return 0;
12212}
12213
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012214/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12215/// elements from either LHS or RHS, return the shuffle mask and true.
12216/// Otherwise, return false.
12217static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012218 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012219 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012220 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12221 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012222 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012223
12224 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012225 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012226 return true;
12227 } else if (V == LHS) {
12228 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012229 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012230 return true;
12231 } else if (V == RHS) {
12232 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012233 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012234 return true;
12235 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12236 // If this is an insert of an extract from some other vector, include it.
12237 Value *VecOp = IEI->getOperand(0);
12238 Value *ScalarOp = IEI->getOperand(1);
12239 Value *IdxOp = IEI->getOperand(2);
12240
Chris Lattnerd929f062006-04-27 21:14:21 +000012241 if (!isa<ConstantInt>(IdxOp))
12242 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012243 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012244
12245 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12246 // Okay, we can handle this if the vector we are insertinting into is
12247 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012248 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012249 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012250 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012251 return true;
12252 }
12253 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12254 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012255 EI->getOperand(0)->getType() == V->getType()) {
12256 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012257 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012258
12259 // This must be extracting from either LHS or RHS.
12260 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12261 // Okay, we can handle this if the vector we are insertinting into is
12262 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012263 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012264 // If so, update the mask to reflect the inserted value.
12265 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012266 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012267 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012268 } else {
12269 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012270 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012271 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012272
12273 }
12274 return true;
12275 }
12276 }
12277 }
12278 }
12279 }
12280 // TODO: Handle shufflevector here!
12281
12282 return false;
12283}
12284
12285/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12286/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12287/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012288static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012289 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012290 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012291 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012292 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012293 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012294
12295 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012296 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012297 return V;
12298 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012299 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012300 return V;
12301 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12302 // If this is an insert of an extract from some other vector, include it.
12303 Value *VecOp = IEI->getOperand(0);
12304 Value *ScalarOp = IEI->getOperand(1);
12305 Value *IdxOp = IEI->getOperand(2);
12306
12307 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12308 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12309 EI->getOperand(0)->getType() == V->getType()) {
12310 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012311 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12312 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012313
12314 // Either the extracted from or inserted into vector must be RHSVec,
12315 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012316 if (EI->getOperand(0) == RHS || RHS == 0) {
12317 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012318 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012319 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012320 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012321 return V;
12322 }
12323
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012324 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012325 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12326 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012327 // Everything but the extracted element is replaced with the RHS.
12328 for (unsigned i = 0; i != NumElts; ++i) {
12329 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012330 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012331 }
12332 return V;
12333 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012334
12335 // If this insertelement is a chain that comes from exactly these two
12336 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012337 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12338 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012339 return EI->getOperand(0);
12340
Chris Lattnerefb47352006-04-15 01:39:45 +000012341 }
12342 }
12343 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012344 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012345
12346 // Otherwise, can't do anything fancy. Return an identity vector.
12347 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012348 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012349 return V;
12350}
12351
12352Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12353 Value *VecOp = IE.getOperand(0);
12354 Value *ScalarOp = IE.getOperand(1);
12355 Value *IdxOp = IE.getOperand(2);
12356
Chris Lattner599ded12007-04-09 01:11:16 +000012357 // Inserting an undef or into an undefined place, remove this.
12358 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12359 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012360
Chris Lattnerefb47352006-04-15 01:39:45 +000012361 // If the inserted element was extracted from some other vector, and if the
12362 // indexes are constant, try to turn this into a shufflevector operation.
12363 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12364 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12365 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012366 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012367 unsigned ExtractedIdx =
12368 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012369 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012370
12371 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12372 return ReplaceInstUsesWith(IE, VecOp);
12373
12374 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012375 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012376
12377 // If we are extracting a value from a vector, then inserting it right
12378 // back into the same place, just use the input vector.
12379 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12380 return ReplaceInstUsesWith(IE, VecOp);
12381
12382 // We could theoretically do this for ANY input. However, doing so could
12383 // turn chains of insertelement instructions into a chain of shufflevector
12384 // instructions, and right now we do not merge shufflevectors. As such,
12385 // only do this in a situation where it is clear that there is benefit.
12386 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12387 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12388 // the values of VecOp, except then one read from EIOp0.
12389 // Build a new shuffle mask.
12390 std::vector<Constant*> Mask;
12391 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012392 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012393 else {
12394 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012395 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012396 NumVectorElts));
12397 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012398 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012399 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012400 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012401 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012402 }
12403
12404 // If this insertelement isn't used by some other insertelement, turn it
12405 // (and any insertelements it points to), into one big shuffle.
12406 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12407 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012408 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012409 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012410 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012411 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012412 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012413 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012414 }
12415 }
12416 }
12417
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012418 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12419 APInt UndefElts(VWidth, 0);
12420 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12421 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12422 return &IE;
12423
Chris Lattnerefb47352006-04-15 01:39:45 +000012424 return 0;
12425}
12426
12427
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012428Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12429 Value *LHS = SVI.getOperand(0);
12430 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012431 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012432
12433 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012434
Chris Lattner867b99f2006-10-05 06:55:50 +000012435 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012436 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012437 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012438
Dan Gohman488fbfc2008-09-09 18:11:14 +000012439 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012440
12441 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12442 return 0;
12443
Evan Cheng388df622009-02-03 10:05:09 +000012444 APInt UndefElts(VWidth, 0);
12445 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12446 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012447 LHS = SVI.getOperand(0);
12448 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012449 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012450 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012451
Chris Lattner863bcff2006-05-25 23:48:38 +000012452 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12453 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12454 if (LHS == RHS || isa<UndefValue>(LHS)) {
12455 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012456 // shuffle(undef,undef,mask) -> undef.
12457 return ReplaceInstUsesWith(SVI, LHS);
12458 }
12459
Chris Lattner863bcff2006-05-25 23:48:38 +000012460 // Remap any references to RHS to use LHS.
12461 std::vector<Constant*> Elts;
12462 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012463 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012464 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012465 else {
12466 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012467 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012468 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012469 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012470 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012471 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012472 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012473 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012474 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012475 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012476 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012477 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012478 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012479 LHS = SVI.getOperand(0);
12480 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012481 MadeChange = true;
12482 }
12483
Chris Lattner7b2e27922006-05-26 00:29:06 +000012484 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012485 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012486
Chris Lattner863bcff2006-05-25 23:48:38 +000012487 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12488 if (Mask[i] >= e*2) continue; // Ignore undef values.
12489 // Is this an identity shuffle of the LHS value?
12490 isLHSID &= (Mask[i] == i);
12491
12492 // Is this an identity shuffle of the RHS value?
12493 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012494 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012495
Chris Lattner863bcff2006-05-25 23:48:38 +000012496 // Eliminate identity shuffles.
12497 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12498 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012499
Chris Lattner7b2e27922006-05-26 00:29:06 +000012500 // If the LHS is a shufflevector itself, see if we can combine it with this
12501 // one without producing an unusual shuffle. Here we are really conservative:
12502 // we are absolutely afraid of producing a shuffle mask not in the input
12503 // program, because the code gen may not be smart enough to turn a merged
12504 // shuffle into two specific shuffles: it may produce worse code. As such,
12505 // we only merge two shuffles if the result is one of the two input shuffle
12506 // masks. In this case, merging the shuffles just removes one instruction,
12507 // which we know is safe. This is good for things like turning:
12508 // (splat(splat)) -> splat.
12509 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12510 if (isa<UndefValue>(RHS)) {
12511 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12512
12513 std::vector<unsigned> NewMask;
12514 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12515 if (Mask[i] >= 2*e)
12516 NewMask.push_back(2*e);
12517 else
12518 NewMask.push_back(LHSMask[Mask[i]]);
12519
12520 // If the result mask is equal to the src shuffle or this shuffle mask, do
12521 // the replacement.
12522 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012523 unsigned LHSInNElts =
12524 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012525 std::vector<Constant*> Elts;
12526 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012527 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012528 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012529 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012530 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012531 }
12532 }
12533 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12534 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012535 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012536 }
12537 }
12538 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012539
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012540 return MadeChange ? &SVI : 0;
12541}
12542
12543
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012544
Chris Lattnerea1c4542004-12-08 23:43:58 +000012545
12546/// TryToSinkInstruction - Try to move the specified instruction from its
12547/// current block into the beginning of DestBlock, which can only happen if it's
12548/// safe to move the instruction past all of the instructions between it and the
12549/// end of its block.
12550static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12551 assert(I->hasOneUse() && "Invariants didn't hold!");
12552
Chris Lattner108e9022005-10-27 17:13:11 +000012553 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012554 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012555 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012556
Chris Lattnerea1c4542004-12-08 23:43:58 +000012557 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012558 if (isa<AllocaInst>(I) && I->getParent() ==
12559 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012560 return false;
12561
Chris Lattner96a52a62004-12-09 07:14:34 +000012562 // We can only sink load instructions if there is nothing between the load and
12563 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012564 if (I->mayReadFromMemory()) {
12565 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012566 Scan != E; ++Scan)
12567 if (Scan->mayWriteToMemory())
12568 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012569 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012570
Dan Gohman02dea8b2008-05-23 21:05:58 +000012571 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012572
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012573 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012574 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012575 ++NumSunkInst;
12576 return true;
12577}
12578
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012579
12580/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12581/// all reachable code to the worklist.
12582///
12583/// This has a couple of tricks to make the code faster and more powerful. In
12584/// particular, we constant fold and DCE instructions as we go, to avoid adding
12585/// them to the worklist (this significantly speeds up instcombine on code where
12586/// many instructions are dead or constant). Additionally, if we find a branch
12587/// whose condition is a known constant, we only visit the reachable successors.
12588///
12589static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012590 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012591 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012592 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012593 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012594 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012595
Chris Lattner2c7718a2007-03-23 19:17:18 +000012596 while (!Worklist.empty()) {
12597 BB = Worklist.back();
12598 Worklist.pop_back();
12599
12600 // We have now visited this block! If we've already been here, ignore it.
12601 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012602
12603 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012604 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12605 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012606
Chris Lattner2c7718a2007-03-23 19:17:18 +000012607 // DCE instruction if trivially dead.
12608 if (isInstructionTriviallyDead(Inst)) {
12609 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012610 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012611 Inst->eraseFromParent();
12612 continue;
12613 }
12614
12615 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012616 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012617 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12618 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012619 Inst->replaceAllUsesWith(C);
12620 ++NumConstProp;
12621 Inst->eraseFromParent();
12622 continue;
12623 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012624
Devang Patel7fe1dec2008-11-19 18:56:50 +000012625 // If there are two consecutive llvm.dbg.stoppoint calls then
12626 // it is likely that the optimizer deleted code in between these
12627 // two intrinsics.
12628 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12629 if (DBI_Next) {
12630 if (DBI_Prev
12631 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12632 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012633 IC.Worklist.Remove(DBI_Prev);
Devang Patel7fe1dec2008-11-19 18:56:50 +000012634 DBI_Prev->eraseFromParent();
12635 }
12636 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012637 } else {
12638 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012639 }
12640
Chris Lattner7a1e9242009-08-30 06:13:40 +000012641 IC.Worklist.Add(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012642 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012643
12644 // Recursively visit successors. If this is a branch or switch on a
12645 // constant, only visit the reachable successor.
12646 TerminatorInst *TI = BB->getTerminator();
12647 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12648 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12649 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012650 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012651 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012652 continue;
12653 }
12654 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12655 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12656 // See if this is an explicit destination.
12657 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12658 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012659 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012660 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012661 continue;
12662 }
12663
12664 // Otherwise it is the default destination.
12665 Worklist.push_back(SI->getSuccessor(0));
12666 continue;
12667 }
12668 }
12669
12670 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12671 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012672 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012673}
12674
Chris Lattnerec9c3582007-03-03 02:04:50 +000012675bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012676 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012677 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012678
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012679 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12680 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012681
Chris Lattnerb3d59702005-07-07 20:40:38 +000012682 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012683 // Do a depth-first traversal of the function, populate the worklist with
12684 // the reachable instructions. Ignore blocks that are not reachable. Keep
12685 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012686 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012687 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012688
Chris Lattnerb3d59702005-07-07 20:40:38 +000012689 // Do a quick scan over the function. If we find any blocks that are
12690 // unreachable, remove any instructions inside of them. This prevents
12691 // the instcombine code from having to deal with some bad special cases.
12692 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12693 if (!Visited.count(BB)) {
12694 Instruction *Term = BB->getTerminator();
12695 while (Term != BB->begin()) { // Remove instrs bottom-up
12696 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012697
Chris Lattnerbdff5482009-08-23 04:37:46 +000012698 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012699 // A debug intrinsic shouldn't force another iteration if we weren't
12700 // going to do one without it.
12701 if (!isa<DbgInfoIntrinsic>(I)) {
12702 ++NumDeadInst;
12703 Changed = true;
12704 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012705 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012706 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012707 I->eraseFromParent();
12708 }
12709 }
12710 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012711
Chris Lattner873ff012009-08-30 05:55:36 +000012712 while (!Worklist.isEmpty()) {
12713 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012714 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012715
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012716 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012717 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012718 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012719 EraseInstFromFunction(*I);
12720 ++NumDeadInst;
Chris Lattner1e19d602009-01-31 07:04:22 +000012721 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012722 continue;
12723 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012724
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012725 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012726 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012727 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012728
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012729 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012730 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012731 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012732 EraseInstFromFunction(*I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012733 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012734 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012735 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012736
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012737 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012738 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012739 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12740 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012741 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12742 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012743 if (NewC != CE) {
12744 i->set(NewC);
12745 Changed = true;
12746 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012747 }
12748
Chris Lattnerea1c4542004-12-08 23:43:58 +000012749 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012750 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012751 BasicBlock *BB = I->getParent();
12752 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12753 if (UserParent != BB) {
12754 bool UserIsSuccessor = false;
12755 // See if the user is one of our successors.
12756 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12757 if (*SI == UserParent) {
12758 UserIsSuccessor = true;
12759 break;
12760 }
12761
12762 // If the user is one of our immediate successors, and if that successor
12763 // only has us as a predecessors (we'd have to split the critical edge
12764 // otherwise), we can keep going.
12765 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12766 next(pred_begin(UserParent)) == pred_end(UserParent))
12767 // Okay, the CFG is simple enough, try to sink this instruction.
12768 Changed |= TryToSinkInstruction(I, UserParent);
12769 }
12770 }
12771
Chris Lattner74381062009-08-30 07:44:24 +000012772 // Now that we have an instruction, try combining it to simplify it.
12773 Builder->SetInsertPoint(I->getParent(), I);
12774
Reid Spencera9b81012007-03-26 17:44:01 +000012775#ifndef NDEBUG
12776 std::string OrigI;
12777#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012778 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattner74381062009-08-30 07:44:24 +000012779
Chris Lattner90ac28c2002-08-02 19:29:35 +000012780 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012781 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012782 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012783 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012784 DEBUG(errs() << "IC: Old = " << *I << '\n'
12785 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012786
Chris Lattnerf523d062004-06-09 05:08:07 +000012787 // Everything uses the new instruction now.
12788 I->replaceAllUsesWith(Result);
12789
12790 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012791 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012792 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012793
Chris Lattner6934a042007-02-11 01:23:03 +000012794 // Move the name to the new instruction first.
12795 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012796
12797 // Insert the new instruction into the basic block...
12798 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012799 BasicBlock::iterator InsertPos = I;
12800
12801 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12802 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12803 ++InsertPos;
12804
12805 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012806
Chris Lattner7a1e9242009-08-30 06:13:40 +000012807 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012808 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012809#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012810 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12811 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012812#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012813
Chris Lattner90ac28c2002-08-02 19:29:35 +000012814 // If the instruction was modified, it's possible that it is now dead.
12815 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012816 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012817 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012818 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012819 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012820 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012821 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012822 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012823 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012824 }
12825 }
12826
Chris Lattner873ff012009-08-30 05:55:36 +000012827 Worklist.Zap();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012828 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012829}
12830
Chris Lattnerec9c3582007-03-03 02:04:50 +000012831
12832bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012833 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012834 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000012835
Chris Lattner74381062009-08-30 07:44:24 +000012836
12837 /// Builder - This is an IRBuilder that automatically inserts new
12838 /// instructions into the worklist when they are created.
12839 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12840 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12841 InstCombineIRInserter(Worklist));
12842 Builder = &TheBuilder;
12843
Chris Lattnerec9c3582007-03-03 02:04:50 +000012844 bool EverMadeChange = false;
12845
12846 // Iterate while there is work to do.
12847 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012848 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012849 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012850
12851 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012852 return EverMadeChange;
12853}
12854
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012855FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012856 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012857}