blob: 91e10a3ff3c9561cd5e2eeb11ff33fdc72a26d2c [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 }
306
Chris Lattner0c967662004-09-24 15:21:34 +0000307 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
308 /// This also adds the cast to the worklist. Finally, this returns the
309 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000310 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
311 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000312 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000313
Chris Lattnere2ed0572006-04-06 19:19:17 +0000314 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000315 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000316
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000317 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000318 Worklist.Add(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000319 return C;
320 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000321
Chris Lattner8b170942002-08-09 23:47:40 +0000322 // ReplaceInstUsesWith - This method is to be used when an instruction is
323 // found to be dead, replacable with another preexisting expression. Here
324 // we add all uses of I to the worklist, replace all uses of I with the new
325 // value, then return I, so that the inst combiner will know that I was
326 // modified.
327 //
328 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000329 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000330
331 // If we are replacing the instruction with itself, this must be in a
332 // segment of unreachable code, so just clobber the instruction.
333 if (&I == V)
334 V = UndefValue::get(I.getType());
335
336 I.replaceAllUsesWith(V);
337 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000338 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000339
340 // EraseInstFromFunction - When dealing with an instruction that has side
341 // effects or produces a void value, we can't rely on DCE to delete the
342 // instruction. Instead, visit methods should return the value returned by
343 // this function.
344 Instruction *EraseInstFromFunction(Instruction &I) {
345 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000346 // Make sure that we reprocess all operands now that we reduced their
347 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000348 if (I.getNumOperands() < 8) {
349 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
350 if (Instruction *Op = dyn_cast<Instruction>(*i))
351 Worklist.Add(Op);
352 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000353 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000354 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000355 return 0; // Don't do anything with FI
356 }
Chris Lattner173234a2008-06-02 01:18:21 +0000357
358 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
359 APInt &KnownOne, unsigned Depth = 0) const {
360 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
361 }
362
363 bool MaskedValueIsZero(Value *V, const APInt &Mask,
364 unsigned Depth = 0) const {
365 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
366 }
367 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
368 return llvm::ComputeNumSignBits(Op, TD, Depth);
369 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000370
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000371 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000372
Reid Spencere4d87aa2006-12-23 06:05:41 +0000373 /// SimplifyCommutative - This performs a few simplifications for
374 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000375 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000376
Reid Spencere4d87aa2006-12-23 06:05:41 +0000377 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
378 /// most-complex to least-complex order.
379 bool SimplifyCompare(CmpInst &I);
380
Chris Lattner886ab6c2009-01-31 08:15:18 +0000381 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
382 /// based on the demanded bits.
383 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
384 APInt& KnownZero, APInt& KnownOne,
385 unsigned Depth);
386 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000387 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000388 unsigned Depth=0);
389
390 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
391 /// SimplifyDemandedBits knows about. See if the instruction has any
392 /// properties that allow us to simplify its operands.
393 bool SimplifyDemandedInstructionBits(Instruction &Inst);
394
Evan Cheng388df622009-02-03 10:05:09 +0000395 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
396 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000397
Chris Lattner4e998b22004-09-29 05:07:12 +0000398 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
399 // PHI node as operand #0, see if we can fold the instruction into the PHI
400 // (which is only possible if all operands to the PHI are constants).
401 Instruction *FoldOpIntoPhi(Instruction &I);
402
Chris Lattnerbac32862004-11-14 19:13:23 +0000403 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
404 // operator and they all are only used by the PHI, PHI together their
405 // inputs, and do the operation once, to the result of the PHI.
406 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000407 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000408 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
409
Chris Lattner7da52b22006-11-01 04:51:18 +0000410
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000411 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
412 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000413
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000414 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000415 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000416 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000417 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000418 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000419 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000420 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000421 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000422 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000423
Chris Lattnerafe91a52006-06-15 19:07:26 +0000424
Reid Spencerc55b2432006-12-13 18:21:21 +0000425 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000426
Dan Gohman6de29f82009-06-15 22:12:54 +0000427 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000428 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000429 unsigned GetOrEnforceKnownAlignment(Value *V,
430 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000431
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000432 };
Chris Lattner873ff012009-08-30 05:55:36 +0000433} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000434
Dan Gohman844731a2008-05-13 00:00:25 +0000435char InstCombiner::ID = 0;
436static RegisterPass<InstCombiner>
437X("instcombine", "Combine redundant instructions");
438
Chris Lattner4f98c562003-03-10 21:43:22 +0000439// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000440// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000441static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000442 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000443 if (BinaryOperator::isNeg(V) ||
444 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000445 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000446 return 3;
447 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000448 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000449 if (isa<Argument>(V)) return 3;
450 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000451}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000452
Chris Lattnerc8802d22003-03-11 00:12:48 +0000453// isOnlyUse - Return true if this instruction will be deleted if we stop using
454// it.
455static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000456 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000457}
458
Chris Lattner4cb170c2004-02-23 06:38:22 +0000459// getPromotedType - Return the specified type promoted as it would be to pass
460// though a va_arg area...
461static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000462 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
463 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000464 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000465 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000466 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000467}
468
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000469/// getBitCastOperand - If the specified operand is a CastInst, a constant
470/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
471/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000472static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000473 if (Operator *O = dyn_cast<Operator>(V)) {
474 if (O->getOpcode() == Instruction::BitCast)
475 return O->getOperand(0);
476 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
477 if (GEP->hasAllZeroIndices())
478 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000479 }
Chris Lattnereed48272005-09-13 00:40:14 +0000480 return 0;
481}
482
Reid Spencer3da59db2006-11-27 01:05:10 +0000483/// This function is a wrapper around CastInst::isEliminableCastPair. It
484/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000485static Instruction::CastOps
486isEliminableCastPair(
487 const CastInst *CI, ///< The first cast instruction
488 unsigned opcode, ///< The opcode of the second cast instruction
489 const Type *DstTy, ///< The target type for the second cast instruction
490 TargetData *TD ///< The target data for pointer size
491) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000492
Reid Spencer3da59db2006-11-27 01:05:10 +0000493 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
494 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000495
Reid Spencer3da59db2006-11-27 01:05:10 +0000496 // Get the opcodes of the two Cast instructions
497 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
498 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000499
Chris Lattnera0e69692009-03-24 18:35:40 +0000500 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000501 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000502 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000503
504 // We don't want to form an inttoptr or ptrtoint that converts to an integer
505 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000506 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000507 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000508 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000509 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000510 Res = 0;
511
512 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000513}
514
515/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
516/// in any code being generated. It does not require codegen if V is simple
517/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000518static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
519 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000520 if (V->getType() == Ty || isa<Constant>(V)) return false;
521
Chris Lattner01575b72006-05-25 23:24:33 +0000522 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000523 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000524 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000525 return false;
526 return true;
527}
528
Chris Lattner4f98c562003-03-10 21:43:22 +0000529// SimplifyCommutative - This performs a few simplifications for commutative
530// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000531//
Chris Lattner4f98c562003-03-10 21:43:22 +0000532// 1. Order operands such that they are listed from right (least complex) to
533// left (most complex). This puts constants before unary operators before
534// binary operators.
535//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000536// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
537// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000538//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000539bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000540 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000541 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000542 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000543
Chris Lattner4f98c562003-03-10 21:43:22 +0000544 if (!I.isAssociative()) return Changed;
545 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000546 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
547 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
548 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000549 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000550 cast<Constant>(I.getOperand(1)),
551 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000552 I.setOperand(0, Op->getOperand(0));
553 I.setOperand(1, Folded);
554 return true;
555 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
556 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
557 isOnlyUse(Op) && isOnlyUse(Op1)) {
558 Constant *C1 = cast<Constant>(Op->getOperand(1));
559 Constant *C2 = cast<Constant>(Op1->getOperand(1));
560
561 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000562 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000563 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000564 Op1->getOperand(0),
565 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000566 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000567 I.setOperand(0, New);
568 I.setOperand(1, Folded);
569 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000570 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000571 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000572 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000573}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000574
Reid Spencere4d87aa2006-12-23 06:05:41 +0000575/// SimplifyCompare - For a CmpInst this function just orders the operands
576/// so that theyare listed from right (least complex) to left (most complex).
577/// This puts constants before unary operators before binary operators.
578bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000579 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000580 return false;
581 I.swapOperands();
582 // Compare instructions are not associative so there's nothing else we can do.
583 return true;
584}
585
Chris Lattner8d969642003-03-10 23:06:50 +0000586// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
587// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000588//
Dan Gohman186a6362009-08-12 16:04:34 +0000589static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000590 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000591 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000592
Chris Lattner0ce85802004-12-14 20:08:06 +0000593 // Constants can be considered to be negated values if they can be folded.
594 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000595 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000596
597 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
598 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000599 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000600
Chris Lattner8d969642003-03-10 23:06:50 +0000601 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000602}
603
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000604// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
605// instruction if the LHS is a constant negative zero (which is the 'negate'
606// form).
607//
Dan Gohman186a6362009-08-12 16:04:34 +0000608static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000609 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000610 return BinaryOperator::getFNegArgument(V);
611
612 // Constants can be considered to be negated values if they can be folded.
613 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000614 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000615
616 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
617 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000618 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000619
620 return 0;
621}
622
Dan Gohman186a6362009-08-12 16:04:34 +0000623static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000624 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000625 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000626
627 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000628 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000629 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000630 return 0;
631}
632
Chris Lattnerc8802d22003-03-11 00:12:48 +0000633// dyn_castFoldableMul - If this value is a multiply that can be folded into
634// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000635// non-constant operand of the multiply, and set CST to point to the multiplier.
636// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000637//
Dan Gohman186a6362009-08-12 16:04:34 +0000638static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000639 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000640 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000641 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000642 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000643 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000644 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000645 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000646 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000647 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000648 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000649 CST = ConstantInt::get(V->getType()->getContext(),
650 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000651 return I->getOperand(0);
652 }
653 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000654 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000655}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000656
Reid Spencer7177c3a2007-03-25 05:33:51 +0000657/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000658static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000659 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000660 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000661}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000662/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000663static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000664 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000665 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000666}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000667/// MultiplyOverflows - True if the multiply can not be expressed in an int
668/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000669static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000670 uint32_t W = C1->getBitWidth();
671 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
672 if (sign) {
673 LHSExt.sext(W * 2);
674 RHSExt.sext(W * 2);
675 } else {
676 LHSExt.zext(W * 2);
677 RHSExt.zext(W * 2);
678 }
679
680 APInt MulExt = LHSExt * RHSExt;
681
682 if (sign) {
683 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
684 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
685 return MulExt.slt(Min) || MulExt.sgt(Max);
686 } else
687 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
688}
Chris Lattner955f3312004-09-28 21:48:02 +0000689
Reid Spencere7816b52007-03-08 01:52:58 +0000690
Chris Lattner255d8912006-02-11 09:31:47 +0000691/// ShrinkDemandedConstant - Check to see if the specified operand of the
692/// specified instruction is a constant integer. If so, check to see if there
693/// are any bits set in the constant that are not demanded. If so, shrink the
694/// constant and return true.
695static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000696 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000697 assert(I && "No instruction?");
698 assert(OpNo < I->getNumOperands() && "Operand index too large");
699
700 // If the operand is not a constant integer, nothing to do.
701 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
702 if (!OpC) return false;
703
704 // If there are no bits set that aren't demanded, nothing to do.
705 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
706 if ((~Demanded & OpC->getValue()) == 0)
707 return false;
708
709 // This instruction is producing bits that are not demanded. Shrink the RHS.
710 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000711 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000712 return true;
713}
714
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000715// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
716// set of known zero and one bits, compute the maximum and minimum values that
717// could have the specified known zero and known one bits, returning them in
718// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000719static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000720 const APInt& KnownOne,
721 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000722 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
723 KnownZero.getBitWidth() == Min.getBitWidth() &&
724 KnownZero.getBitWidth() == Max.getBitWidth() &&
725 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000726 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000727
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000728 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
729 // bit if it is unknown.
730 Min = KnownOne;
731 Max = KnownOne|UnknownBits;
732
Dan Gohman1c8491e2009-04-25 17:12:48 +0000733 if (UnknownBits.isNegative()) { // Sign bit is unknown
734 Min.set(Min.getBitWidth()-1);
735 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000736 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000737}
738
739// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
740// a set of known zero and one bits, compute the maximum and minimum values that
741// could have the specified known zero and known one bits, returning them in
742// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000743static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000744 const APInt &KnownOne,
745 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000746 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
747 KnownZero.getBitWidth() == Min.getBitWidth() &&
748 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000749 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000750 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000751
752 // The minimum value is when the unknown bits are all zeros.
753 Min = KnownOne;
754 // The maximum value is when the unknown bits are all ones.
755 Max = KnownOne|UnknownBits;
756}
Chris Lattner255d8912006-02-11 09:31:47 +0000757
Chris Lattner886ab6c2009-01-31 08:15:18 +0000758/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
759/// SimplifyDemandedBits knows about. See if the instruction has any
760/// properties that allow us to simplify its operands.
761bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000762 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000763 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
764 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
765
766 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
767 KnownZero, KnownOne, 0);
768 if (V == 0) return false;
769 if (V == &Inst) return true;
770 ReplaceInstUsesWith(Inst, V);
771 return true;
772}
773
774/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
775/// specified instruction operand if possible, updating it in place. It returns
776/// true if it made any change and false otherwise.
777bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
778 APInt &KnownZero, APInt &KnownOne,
779 unsigned Depth) {
780 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
781 KnownZero, KnownOne, Depth);
782 if (NewVal == 0) return false;
783 U.set(NewVal);
784 return true;
785}
786
787
788/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
789/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000790/// that only the bits set in DemandedMask of the result of V are ever used
791/// downstream. Consequently, depending on the mask and V, it may be possible
792/// to replace V with a constant or one of its operands. In such cases, this
793/// function does the replacement and returns true. In all other cases, it
794/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000795/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000796/// to be zero in the expression. These are provided to potentially allow the
797/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
798/// the expression. KnownOne and KnownZero always follow the invariant that
799/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
800/// the bits in KnownOne and KnownZero may only be accurate for those bits set
801/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
802/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000803///
804/// This returns null if it did not change anything and it permits no
805/// simplification. This returns V itself if it did some simplification of V's
806/// operands based on the information about what bits are demanded. This returns
807/// some other non-null value if it found out that V is equal to another value
808/// in the context where the specified bits are demanded, but not for all users.
809Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
810 APInt &KnownZero, APInt &KnownOne,
811 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000812 assert(V != 0 && "Null pointer of Value???");
813 assert(Depth <= 6 && "Limit Search Depth");
814 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000815 const Type *VTy = V->getType();
816 assert((TD || !isa<PointerType>(VTy)) &&
817 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000818 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
819 (!VTy->isIntOrIntVector() ||
820 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000821 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000822 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000823 "Value *V, DemandedMask, KnownZero and KnownOne "
824 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000825 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
826 // We know all of the bits for a constant!
827 KnownOne = CI->getValue() & DemandedMask;
828 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000829 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000830 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000831 if (isa<ConstantPointerNull>(V)) {
832 // We know all of the bits for a constant!
833 KnownOne.clear();
834 KnownZero = DemandedMask;
835 return 0;
836 }
837
Chris Lattner08d2cc72009-01-31 07:26:06 +0000838 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000839 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000840 if (DemandedMask == 0) { // Not demanding any bits from V.
841 if (isa<UndefValue>(V))
842 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000843 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000844 }
845
Chris Lattner4598c942009-01-31 08:24:16 +0000846 if (Depth == 6) // Limit search depth.
847 return 0;
848
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000849 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
850 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
851
Dan Gohman1c8491e2009-04-25 17:12:48 +0000852 Instruction *I = dyn_cast<Instruction>(V);
853 if (!I) {
854 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
855 return 0; // Only analyze instructions.
856 }
857
Chris Lattner4598c942009-01-31 08:24:16 +0000858 // If there are multiple uses of this value and we aren't at the root, then
859 // we can't do any simplifications of the operands, because DemandedMask
860 // only reflects the bits demanded by *one* of the users.
861 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000862 // Despite the fact that we can't simplify this instruction in all User's
863 // context, we can at least compute the knownzero/knownone bits, and we can
864 // do simplifications that apply to *just* the one user if we know that
865 // this instruction has a simpler value in that context.
866 if (I->getOpcode() == Instruction::And) {
867 // If either the LHS or the RHS are Zero, the result is zero.
868 ComputeMaskedBits(I->getOperand(1), DemandedMask,
869 RHSKnownZero, RHSKnownOne, Depth+1);
870 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
871 LHSKnownZero, LHSKnownOne, Depth+1);
872
873 // If all of the demanded bits are known 1 on one side, return the other.
874 // These bits cannot contribute to the result of the 'and' in this
875 // context.
876 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
877 (DemandedMask & ~LHSKnownZero))
878 return I->getOperand(0);
879 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
880 (DemandedMask & ~RHSKnownZero))
881 return I->getOperand(1);
882
883 // If all of the demanded bits in the inputs are known zeros, return zero.
884 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000885 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000886
887 } else if (I->getOpcode() == Instruction::Or) {
888 // We can simplify (X|Y) -> X or Y in the user's context if we know that
889 // only bits from X or Y are demanded.
890
891 // If either the LHS or the RHS are One, the result is One.
892 ComputeMaskedBits(I->getOperand(1), DemandedMask,
893 RHSKnownZero, RHSKnownOne, Depth+1);
894 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
895 LHSKnownZero, LHSKnownOne, Depth+1);
896
897 // If all of the demanded bits are known zero on one side, return the
898 // other. These bits cannot contribute to the result of the 'or' in this
899 // context.
900 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
901 (DemandedMask & ~LHSKnownOne))
902 return I->getOperand(0);
903 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
904 (DemandedMask & ~RHSKnownOne))
905 return I->getOperand(1);
906
907 // If all of the potentially set bits on one side are known to be set on
908 // the other side, just use the 'other' side.
909 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
910 (DemandedMask & (~RHSKnownZero)))
911 return I->getOperand(0);
912 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
913 (DemandedMask & (~LHSKnownZero)))
914 return I->getOperand(1);
915 }
916
Chris Lattner4598c942009-01-31 08:24:16 +0000917 // Compute the KnownZero/KnownOne bits to simplify things downstream.
918 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
919 return 0;
920 }
921
922 // If this is the root being simplified, allow it to have multiple uses,
923 // just set the DemandedMask to all bits so that we can try to simplify the
924 // operands. This allows visitTruncInst (for example) to simplify the
925 // operand of a trunc without duplicating all the logic below.
926 if (Depth == 0 && !V->hasOneUse())
927 DemandedMask = APInt::getAllOnesValue(BitWidth);
928
Reid Spencer8cb68342007-03-12 17:25:59 +0000929 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000930 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000931 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000932 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000933 case Instruction::And:
934 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000935 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
936 RHSKnownZero, RHSKnownOne, Depth+1) ||
937 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000938 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000939 return I;
940 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
941 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000942
943 // If all of the demanded bits are known 1 on one side, return the other.
944 // These bits cannot contribute to the result of the 'and'.
945 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
946 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000947 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000948 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
949 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000950 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000951
952 // If all of the demanded bits in the inputs are known zeros, return zero.
953 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000954 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000955
956 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000957 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000958 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000959
960 // Output known-1 bits are only known if set in both the LHS & RHS.
961 RHSKnownOne &= LHSKnownOne;
962 // Output known-0 are known to be clear if zero in either the LHS | RHS.
963 RHSKnownZero |= LHSKnownZero;
964 break;
965 case Instruction::Or:
966 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000967 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
968 RHSKnownZero, RHSKnownOne, Depth+1) ||
969 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000970 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000971 return I;
972 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
973 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000974
975 // If all of the demanded bits are known zero on one side, return the other.
976 // These bits cannot contribute to the result of the 'or'.
977 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
978 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000979 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000980 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
981 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000982 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000983
984 // If all of the potentially set bits on one side are known to be set on
985 // the other side, just use the 'other' side.
986 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
987 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000989 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
990 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000991 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000992
993 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000994 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000995 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000996
997 // Output known-0 bits are only known if clear in both the LHS & RHS.
998 RHSKnownZero &= LHSKnownZero;
999 // Output known-1 are known to be set if set in either the LHS | RHS.
1000 RHSKnownOne |= LHSKnownOne;
1001 break;
1002 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001003 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1004 RHSKnownZero, RHSKnownOne, Depth+1) ||
1005 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001006 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001007 return I;
1008 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1009 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001010
1011 // If all of the demanded bits are known zero on one side, return the other.
1012 // These bits cannot contribute to the result of the 'xor'.
1013 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001014 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001015 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001016 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001017
1018 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1019 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1020 (RHSKnownOne & LHSKnownOne);
1021 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1022 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1023 (RHSKnownOne & LHSKnownZero);
1024
1025 // If all of the demanded bits are known to be zero on one side or the
1026 // other, turn this into an *inclusive* or.
1027 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner74381062009-08-30 07:44:24 +00001028 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0)
1029 return Builder->CreateOr(I->getOperand(0), I->getOperand(1),I->getName());
Reid Spencer8cb68342007-03-12 17:25:59 +00001030
1031 // If all of the demanded bits on one side are known, and all of the set
1032 // bits on that side are also known to be set on the other side, turn this
1033 // into an AND, as we know the bits will be cleared.
1034 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1035 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1036 // all known
1037 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001038 Constant *AndC = Constant::getIntegerValue(VTy,
1039 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001040 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001041 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001042 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001043 }
1044 }
1045
1046 // If the RHS is a constant, see if we can simplify it.
1047 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001048 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001049 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001050
1051 RHSKnownZero = KnownZeroOut;
1052 RHSKnownOne = KnownOneOut;
1053 break;
1054 }
1055 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1057 RHSKnownZero, RHSKnownOne, Depth+1) ||
1058 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001059 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 return I;
1061 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1062 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001063
1064 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001065 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1066 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001068
1069 // Only known if known in both the LHS and RHS.
1070 RHSKnownOne &= LHSKnownOne;
1071 RHSKnownZero &= LHSKnownZero;
1072 break;
1073 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001074 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001075 DemandedMask.zext(truncBf);
1076 RHSKnownZero.zext(truncBf);
1077 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001079 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001080 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001081 DemandedMask.trunc(BitWidth);
1082 RHSKnownZero.trunc(BitWidth);
1083 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001084 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001085 break;
1086 }
1087 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001088 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001089 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001090
1091 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1092 if (const VectorType *SrcVTy =
1093 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1094 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1095 // Don't touch a bitcast between vectors of different element counts.
1096 return false;
1097 } else
1098 // Don't touch a scalar-to-vector bitcast.
1099 return false;
1100 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1101 // Don't touch a vector-to-scalar bitcast.
1102 return false;
1103
Chris Lattner886ab6c2009-01-31 08:15:18 +00001104 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001105 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001106 return I;
1107 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001108 break;
1109 case Instruction::ZExt: {
1110 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001111 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001112
Zhou Shengd48653a2007-03-29 04:45:55 +00001113 DemandedMask.trunc(SrcBitWidth);
1114 RHSKnownZero.trunc(SrcBitWidth);
1115 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001116 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001117 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001118 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 DemandedMask.zext(BitWidth);
1120 RHSKnownZero.zext(BitWidth);
1121 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001122 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001123 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001124 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001125 break;
1126 }
1127 case Instruction::SExt: {
1128 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001129 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001130
Reid Spencer8cb68342007-03-12 17:25:59 +00001131 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001132 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001133
Zhou Sheng01542f32007-03-29 02:26:30 +00001134 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 // If any of the sign extended bits are demanded, we know that the sign
1136 // bit is demanded.
1137 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001138 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001139
Zhou Shengd48653a2007-03-29 04:45:55 +00001140 InputDemandedBits.trunc(SrcBitWidth);
1141 RHSKnownZero.trunc(SrcBitWidth);
1142 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001143 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001144 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001145 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001146 InputDemandedBits.zext(BitWidth);
1147 RHSKnownZero.zext(BitWidth);
1148 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001149 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001150
1151 // If the sign bit of the input is known set or clear, then we know the
1152 // top bits of the result.
1153
1154 // If the input sign bit is known zero, or if the NewBits are not demanded
1155 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001156 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001157 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001158 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1159 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001160 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001161 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001162 }
1163 break;
1164 }
1165 case Instruction::Add: {
1166 // Figure out what the input bits are. If the top bits of the and result
1167 // are not demanded, then the add doesn't demand them from its input
1168 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001169 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001170
1171 // If there is a constant on the RHS, there are a variety of xformations
1172 // we can do.
1173 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1174 // If null, this should be simplified elsewhere. Some of the xforms here
1175 // won't work if the RHS is zero.
1176 if (RHS->isZero())
1177 break;
1178
1179 // If the top bit of the output is demanded, demand everything from the
1180 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001181 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001182
1183 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001184 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001185 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001186 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001187
1188 // If the RHS of the add has bits set that can't affect the input, reduce
1189 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001190 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001191 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001192
1193 // Avoid excess work.
1194 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1195 break;
1196
1197 // Turn it into OR if input bits are zero.
1198 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1199 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001200 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001201 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001202 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001203 }
1204
1205 // We can say something about the output known-zero and known-one bits,
1206 // depending on potential carries from the input constant and the
1207 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1208 // bits set and the RHS constant is 0x01001, then we know we have a known
1209 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1210
1211 // To compute this, we first compute the potential carry bits. These are
1212 // the bits which may be modified. I'm not aware of a better way to do
1213 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001214 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001215 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001216
1217 // Now that we know which bits have carries, compute the known-1/0 sets.
1218
1219 // Bits are known one if they are known zero in one operand and one in the
1220 // other, and there is no input carry.
1221 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1222 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1223
1224 // Bits are known zero if they are known zero in both operands and there
1225 // is no input carry.
1226 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1227 } else {
1228 // If the high-bits of this ADD are not demanded, then it does not demand
1229 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001230 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 // Right fill the mask of bits for this ADD to demand the most
1232 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001233 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001234 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1235 LHSKnownZero, LHSKnownOne, Depth+1) ||
1236 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001237 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001238 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001239 }
1240 }
1241 break;
1242 }
1243 case Instruction::Sub:
1244 // If the high-bits of this SUB are not demanded, then it does not demand
1245 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001246 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001247 // Right fill the mask of bits for this SUB to demand the most
1248 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001249 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001250 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001251 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1252 LHSKnownZero, LHSKnownOne, Depth+1) ||
1253 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001254 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001255 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001256 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001257 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1258 // the known zeros and ones.
1259 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001260 break;
1261 case Instruction::Shl:
1262 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001263 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001264 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001265 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001266 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001267 return I;
1268 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001269 RHSKnownZero <<= ShiftAmt;
1270 RHSKnownOne <<= ShiftAmt;
1271 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001272 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001273 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001274 }
1275 break;
1276 case Instruction::LShr:
1277 // For a logical shift right
1278 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001279 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001280
Reid Spencer8cb68342007-03-12 17:25:59 +00001281 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001282 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001283 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001284 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001285 return I;
1286 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001287 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1288 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001289 if (ShiftAmt) {
1290 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001291 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001292 RHSKnownZero |= HighBits; // high bits known zero.
1293 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001294 }
1295 break;
1296 case Instruction::AShr:
1297 // If this is an arithmetic shift right and only the low-bit is set, we can
1298 // always convert this into a logical shr, even if the shift amount is
1299 // variable. The low bit of the shift cannot be an input sign bit unless
1300 // the shift amount is >= the size of the datatype, which is undefined.
1301 if (DemandedMask == 1) {
1302 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001303 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001304 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001305 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001306 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001307
1308 // If the sign bit is the only bit demanded by this ashr, then there is no
1309 // need to do it, the shift doesn't change the high bit.
1310 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001311 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001312
1313 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001314 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001315
Reid Spencer8cb68342007-03-12 17:25:59 +00001316 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001317 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001318 // If any of the "high bits" are demanded, we should set the sign bit as
1319 // demanded.
1320 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1321 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001323 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001324 return I;
1325 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001326 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001327 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001328 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1329 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1330
1331 // Handle the sign bits.
1332 APInt SignBit(APInt::getSignBit(BitWidth));
1333 // Adjust to where it is now in the mask.
1334 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1335
1336 // If the input sign bit is known to be zero, or if none of the top bits
1337 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001338 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001339 (HighBits & ~DemandedMask) == HighBits) {
1340 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001341 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001342 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001343 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001344 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1345 RHSKnownOne |= HighBits;
1346 }
1347 }
1348 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001349 case Instruction::SRem:
1350 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001351 APInt RA = Rem->getValue().abs();
1352 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001353 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001354 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001355
Nick Lewycky8e394322008-11-02 02:41:50 +00001356 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001357 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001358 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001359 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001360 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001361
1362 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1363 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001364
1365 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001366
Chris Lattner886ab6c2009-01-31 08:15:18 +00001367 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001368 }
1369 }
1370 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001371 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001372 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1373 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001374 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1375 KnownZero2, KnownOne2, Depth+1) ||
1376 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001377 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001378 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001379
Chris Lattner455e9ab2009-01-21 18:09:24 +00001380 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001381 Leaders = std::max(Leaders,
1382 KnownZero2.countLeadingOnes());
1383 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001384 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001385 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001386 case Instruction::Call:
1387 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1388 switch (II->getIntrinsicID()) {
1389 default: break;
1390 case Intrinsic::bswap: {
1391 // If the only bits demanded come from one byte of the bswap result,
1392 // just shift the input byte into position to eliminate the bswap.
1393 unsigned NLZ = DemandedMask.countLeadingZeros();
1394 unsigned NTZ = DemandedMask.countTrailingZeros();
1395
1396 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1397 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1398 // have 14 leading zeros, round to 8.
1399 NLZ &= ~7;
1400 NTZ &= ~7;
1401 // If we need exactly one byte, we can do this transformation.
1402 if (BitWidth-NLZ-NTZ == 8) {
1403 unsigned ResultBit = NTZ;
1404 unsigned InputBit = BitWidth-NTZ-8;
1405
1406 // Replace this with either a left or right shift to get the byte into
1407 // the right place.
1408 Instruction *NewVal;
1409 if (InputBit > ResultBit)
1410 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001411 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001412 else
1413 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001414 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001415 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001416 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001417 }
1418
1419 // TODO: Could compute known zero/one bits based on the input.
1420 break;
1421 }
1422 }
1423 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001424 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001425 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001426 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001427
1428 // If the client is only demanding bits that we know, return the known
1429 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001430 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1431 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001432 return false;
1433}
1434
Chris Lattner867b99f2006-10-05 06:55:50 +00001435
Mon P Wangaeb06d22008-11-10 04:46:22 +00001436/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001437/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001438/// actually used by the caller. This method analyzes which elements of the
1439/// operand are undef and returns that information in UndefElts.
1440///
1441/// If the information about demanded elements can be used to simplify the
1442/// operation, the operation is simplified, then the resultant value is
1443/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001444Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1445 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001446 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001447 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001448 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001449 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001450
1451 if (isa<UndefValue>(V)) {
1452 // If the entire vector is undefined, just return this info.
1453 UndefElts = EltMask;
1454 return 0;
1455 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1456 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001457 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001458 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001459
Chris Lattner867b99f2006-10-05 06:55:50 +00001460 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001461 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1462 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001463 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001464
1465 std::vector<Constant*> Elts;
1466 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001467 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001468 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001469 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001470 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1471 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001472 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001473 } else { // Otherwise, defined.
1474 Elts.push_back(CP->getOperand(i));
1475 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001476
Chris Lattner867b99f2006-10-05 06:55:50 +00001477 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001478 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001479 return NewCP != CP ? NewCP : 0;
1480 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001481 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001482 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001483
1484 // Check if this is identity. If so, return 0 since we are not simplifying
1485 // anything.
1486 if (DemandedElts == ((1ULL << VWidth) -1))
1487 return 0;
1488
Reid Spencer9d6565a2007-02-15 02:26:10 +00001489 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001490 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001491 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001492 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001493 for (unsigned i = 0; i != VWidth; ++i) {
1494 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1495 Elts.push_back(Elt);
1496 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001497 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001498 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001499 }
1500
Dan Gohman488fbfc2008-09-09 18:11:14 +00001501 // Limit search depth.
1502 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001503 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001504
1505 // If multiple users are using the root value, procede with
1506 // simplification conservatively assuming that all elements
1507 // are needed.
1508 if (!V->hasOneUse()) {
1509 // Quit if we find multiple users of a non-root value though.
1510 // They'll be handled when it's their turn to be visited by
1511 // the main instcombine process.
1512 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001513 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001514 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001515
1516 // Conservatively assume that all elements are needed.
1517 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001518 }
1519
1520 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001521 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001522
1523 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001524 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001525 Value *TmpV;
1526 switch (I->getOpcode()) {
1527 default: break;
1528
1529 case Instruction::InsertElement: {
1530 // If this is a variable index, we don't know which element it overwrites.
1531 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001532 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001533 if (Idx == 0) {
1534 // Note that we can't propagate undef elt info, because we don't know
1535 // which elt is getting updated.
1536 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1537 UndefElts2, Depth+1);
1538 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1539 break;
1540 }
1541
1542 // If this is inserting an element that isn't demanded, remove this
1543 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001544 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001545 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1546 Worklist.Add(I);
1547 return I->getOperand(0);
1548 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001549
1550 // Otherwise, the element inserted overwrites whatever was there, so the
1551 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001552 APInt DemandedElts2 = DemandedElts;
1553 DemandedElts2.clear(IdxNo);
1554 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001555 UndefElts, Depth+1);
1556 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1557
1558 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001559 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001560 break;
1561 }
1562 case Instruction::ShuffleVector: {
1563 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001564 uint64_t LHSVWidth =
1565 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001566 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001567 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001568 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001569 unsigned MaskVal = Shuffle->getMaskValue(i);
1570 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001571 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001572 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001573 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001574 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001575 else
Evan Cheng388df622009-02-03 10:05:09 +00001576 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001577 }
1578 }
1579 }
1580
Nate Begeman7b254672009-02-11 22:36:25 +00001581 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001582 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001583 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001584 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1585
Nate Begeman7b254672009-02-11 22:36:25 +00001586 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001587 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1588 UndefElts3, Depth+1);
1589 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1590
1591 bool NewUndefElts = false;
1592 for (unsigned i = 0; i < VWidth; i++) {
1593 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001594 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001595 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001596 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001597 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001598 NewUndefElts = true;
1599 UndefElts.set(i);
1600 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001601 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001602 if (UndefElts3[MaskVal - LHSVWidth]) {
1603 NewUndefElts = true;
1604 UndefElts.set(i);
1605 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001606 }
1607 }
1608
1609 if (NewUndefElts) {
1610 // Add additional discovered undefs.
1611 std::vector<Constant*> Elts;
1612 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001613 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001614 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001615 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001616 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001617 Shuffle->getMaskValue(i)));
1618 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001619 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001620 MadeChange = true;
1621 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001622 break;
1623 }
Chris Lattner69878332007-04-14 22:29:23 +00001624 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001625 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001626 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1627 if (!VTy) break;
1628 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001629 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001630 unsigned Ratio;
1631
1632 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001633 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001634 // elements as are demanded of us.
1635 Ratio = 1;
1636 InputDemandedElts = DemandedElts;
1637 } else if (VWidth > InVWidth) {
1638 // Untested so far.
1639 break;
1640
1641 // If there are more elements in the result than there are in the source,
1642 // then an input element is live if any of the corresponding output
1643 // elements are live.
1644 Ratio = VWidth/InVWidth;
1645 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001646 if (DemandedElts[OutIdx])
1647 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001648 }
1649 } else {
1650 // Untested so far.
1651 break;
1652
1653 // If there are more elements in the source than there are in the result,
1654 // then an input element is live if the corresponding output element is
1655 // live.
1656 Ratio = InVWidth/VWidth;
1657 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001658 if (DemandedElts[InIdx/Ratio])
1659 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001660 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001661
Chris Lattner69878332007-04-14 22:29:23 +00001662 // div/rem demand all inputs, because they don't want divide by zero.
1663 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1664 UndefElts2, Depth+1);
1665 if (TmpV) {
1666 I->setOperand(0, TmpV);
1667 MadeChange = true;
1668 }
1669
1670 UndefElts = UndefElts2;
1671 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001672 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001673 // If there are more elements in the result than there are in the source,
1674 // then an output element is undef if the corresponding input element is
1675 // undef.
1676 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001677 if (UndefElts2[OutIdx/Ratio])
1678 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001679 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001680 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001681 // If there are more elements in the source than there are in the result,
1682 // then a result element is undef if all of the corresponding input
1683 // elements are undef.
1684 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1685 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001686 if (!UndefElts2[InIdx]) // Not undef?
1687 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001688 }
1689 break;
1690 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001691 case Instruction::And:
1692 case Instruction::Or:
1693 case Instruction::Xor:
1694 case Instruction::Add:
1695 case Instruction::Sub:
1696 case Instruction::Mul:
1697 // div/rem demand all inputs, because they don't want divide by zero.
1698 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1699 UndefElts, Depth+1);
1700 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1701 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1702 UndefElts2, Depth+1);
1703 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1704
1705 // Output elements are undefined if both are undefined. Consider things
1706 // like undef&0. The result is known zero, not undef.
1707 UndefElts &= UndefElts2;
1708 break;
1709
1710 case Instruction::Call: {
1711 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1712 if (!II) break;
1713 switch (II->getIntrinsicID()) {
1714 default: break;
1715
1716 // Binary vector operations that work column-wise. A dest element is a
1717 // function of the corresponding input elements from the two inputs.
1718 case Intrinsic::x86_sse_sub_ss:
1719 case Intrinsic::x86_sse_mul_ss:
1720 case Intrinsic::x86_sse_min_ss:
1721 case Intrinsic::x86_sse_max_ss:
1722 case Intrinsic::x86_sse2_sub_sd:
1723 case Intrinsic::x86_sse2_mul_sd:
1724 case Intrinsic::x86_sse2_min_sd:
1725 case Intrinsic::x86_sse2_max_sd:
1726 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1727 UndefElts, Depth+1);
1728 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1729 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1730 UndefElts2, Depth+1);
1731 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1732
1733 // If only the low elt is demanded and this is a scalarizable intrinsic,
1734 // scalarize it now.
1735 if (DemandedElts == 1) {
1736 switch (II->getIntrinsicID()) {
1737 default: break;
1738 case Intrinsic::x86_sse_sub_ss:
1739 case Intrinsic::x86_sse_mul_ss:
1740 case Intrinsic::x86_sse2_sub_sd:
1741 case Intrinsic::x86_sse2_mul_sd:
1742 // TODO: Lower MIN/MAX/ABS/etc
1743 Value *LHS = II->getOperand(1);
1744 Value *RHS = II->getOperand(2);
1745 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001746 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001747 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001748 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001749 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001750
1751 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001752 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001753 case Intrinsic::x86_sse_sub_ss:
1754 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001755 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001756 II->getName()), *II);
1757 break;
1758 case Intrinsic::x86_sse_mul_ss:
1759 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001760 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001761 II->getName()), *II);
1762 break;
1763 }
1764
1765 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001766 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001767 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001768 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001769 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001770 return New;
1771 }
1772 }
1773
1774 // Output elements are undefined if both are undefined. Consider things
1775 // like undef&0. The result is known zero, not undef.
1776 UndefElts &= UndefElts2;
1777 break;
1778 }
1779 break;
1780 }
1781 }
1782 return MadeChange ? I : 0;
1783}
1784
Dan Gohman45b4e482008-05-19 22:14:15 +00001785
Chris Lattner564a7272003-08-13 19:01:45 +00001786/// AssociativeOpt - Perform an optimization on an associative operator. This
1787/// function is designed to check a chain of associative operators for a
1788/// potential to apply a certain optimization. Since the optimization may be
1789/// applicable if the expression was reassociated, this checks the chain, then
1790/// reassociates the expression as necessary to expose the optimization
1791/// opportunity. This makes use of a special Functor, which must define
1792/// 'shouldApply' and 'apply' methods.
1793///
1794template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001795static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001796 unsigned Opcode = Root.getOpcode();
1797 Value *LHS = Root.getOperand(0);
1798
1799 // Quick check, see if the immediate LHS matches...
1800 if (F.shouldApply(LHS))
1801 return F.apply(Root);
1802
1803 // Otherwise, if the LHS is not of the same opcode as the root, return.
1804 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001805 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001806 // Should we apply this transform to the RHS?
1807 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1808
1809 // If not to the RHS, check to see if we should apply to the LHS...
1810 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1811 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1812 ShouldApply = true;
1813 }
1814
1815 // If the functor wants to apply the optimization to the RHS of LHSI,
1816 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1817 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001818 // Now all of the instructions are in the current basic block, go ahead
1819 // and perform the reassociation.
1820 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1821
1822 // First move the selected RHS to the LHS of the root...
1823 Root.setOperand(0, LHSI->getOperand(1));
1824
1825 // Make what used to be the LHS of the root be the user of the root...
1826 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001827 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001828 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001829 return 0;
1830 }
Chris Lattner65725312004-04-16 18:08:07 +00001831 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001832 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001833 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001834 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001835 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001836
1837 // Now propagate the ExtraOperand down the chain of instructions until we
1838 // get to LHSI.
1839 while (TmpLHSI != LHSI) {
1840 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001841 // Move the instruction to immediately before the chain we are
1842 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001843 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001844 ARI = NextLHSI;
1845
Chris Lattner564a7272003-08-13 19:01:45 +00001846 Value *NextOp = NextLHSI->getOperand(1);
1847 NextLHSI->setOperand(1, ExtraOperand);
1848 TmpLHSI = NextLHSI;
1849 ExtraOperand = NextOp;
1850 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001851
Chris Lattner564a7272003-08-13 19:01:45 +00001852 // Now that the instructions are reassociated, have the functor perform
1853 // the transformation...
1854 return F.apply(Root);
1855 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001856
Chris Lattner564a7272003-08-13 19:01:45 +00001857 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1858 }
1859 return 0;
1860}
1861
Dan Gohman844731a2008-05-13 00:00:25 +00001862namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001863
Nick Lewycky02d639f2008-05-23 04:34:58 +00001864// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001865struct AddRHS {
1866 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001867 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001868 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1869 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001870 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001871 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001872 }
1873};
1874
1875// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1876// iff C1&C2 == 0
1877struct AddMaskingAnd {
1878 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001879 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001880 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001881 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001882 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001883 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001884 }
1885 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001886 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001887 }
1888};
1889
Dan Gohman844731a2008-05-13 00:00:25 +00001890}
1891
Chris Lattner6e7ba452005-01-01 16:22:27 +00001892static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001893 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001894 if (CastInst *CI = dyn_cast<CastInst>(&I))
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001895 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001896
Chris Lattner2eefe512004-04-09 19:05:30 +00001897 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001898 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1899 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001900
Chris Lattner2eefe512004-04-09 19:05:30 +00001901 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1902 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001903 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1904 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001905 }
1906
1907 Value *Op0 = SO, *Op1 = ConstOperand;
1908 if (!ConstIsRHS)
1909 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001910
Chris Lattner6e7ba452005-01-01 16:22:27 +00001911 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001912 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1913 SO->getName()+".op");
1914 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1915 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1916 SO->getName()+".cmp");
1917 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1918 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1919 SO->getName()+".cmp");
1920 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001921}
1922
1923// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1924// constant as the other operand, try to fold the binary operator into the
1925// select arguments. This also works for Cast instructions, which obviously do
1926// not have a second operand.
1927static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1928 InstCombiner *IC) {
1929 // Don't modify shared select instructions
1930 if (!SI->hasOneUse()) return 0;
1931 Value *TV = SI->getOperand(1);
1932 Value *FV = SI->getOperand(2);
1933
1934 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001935 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001936 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001937
Chris Lattner6e7ba452005-01-01 16:22:27 +00001938 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1939 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1940
Gabor Greif051a9502008-04-06 20:25:17 +00001941 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1942 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001943 }
1944 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001945}
1946
Chris Lattner4e998b22004-09-29 05:07:12 +00001947
1948/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1949/// node as operand #0, see if we can fold the instruction into the PHI (which
1950/// is only possible if all operands to the PHI are constants).
1951Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1952 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001953 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001954 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001955
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001956 // Check to see if all of the operands of the PHI are constants. If there is
1957 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001958 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001959 BasicBlock *NonConstBB = 0;
1960 for (unsigned i = 0; i != NumPHIValues; ++i)
1961 if (!isa<Constant>(PN->getIncomingValue(i))) {
1962 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001963 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001964 NonConstBB = PN->getIncomingBlock(i);
1965
1966 // If the incoming non-constant value is in I's block, we have an infinite
1967 // loop.
1968 if (NonConstBB == I.getParent())
1969 return 0;
1970 }
1971
1972 // If there is exactly one non-constant value, we can insert a copy of the
1973 // operation in that block. However, if this is a critical edge, we would be
1974 // inserting the computation one some other paths (e.g. inside a loop). Only
1975 // do this if the pred block is unconditionally branching into the phi block.
1976 if (NonConstBB) {
1977 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1978 if (!BI || !BI->isUnconditional()) return 0;
1979 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001980
1981 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001982 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001983 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001984 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001985 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001986
1987 // Next, add all of the operands to the PHI.
1988 if (I.getNumOperands() == 2) {
1989 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001990 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001991 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001992 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001993 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001994 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001995 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001996 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001997 } else {
1998 assert(PN->getIncomingBlock(i) == NonConstBB);
1999 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002000 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002001 PN->getIncomingValue(i), C, "phitmp",
2002 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002003 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002004 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002005 CI->getPredicate(),
2006 PN->getIncomingValue(i), C, "phitmp",
2007 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002008 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002009 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002010
Chris Lattner7a1e9242009-08-30 06:13:40 +00002011 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002012 }
2013 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002014 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002015 } else {
2016 CastInst *CI = cast<CastInst>(&I);
2017 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002018 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002019 Value *InV;
2020 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002021 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002022 } else {
2023 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002024 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002025 I.getType(), "phitmp",
2026 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002027 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002028 }
2029 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002030 }
2031 }
2032 return ReplaceInstUsesWith(I, NewPN);
2033}
2034
Chris Lattner2454a2e2008-01-29 06:52:45 +00002035
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002036/// WillNotOverflowSignedAdd - Return true if we can prove that:
2037/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2038/// This basically requires proving that the add in the original type would not
2039/// overflow to change the sign bit or have a carry out.
2040bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2041 // There are different heuristics we can use for this. Here are some simple
2042 // ones.
2043
2044 // Add has the property that adding any two 2's complement numbers can only
2045 // have one carry bit which can change a sign. As such, if LHS and RHS each
2046 // have at least two sign bits, we know that the addition of the two values will
2047 // sign extend fine.
2048 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2049 return true;
2050
2051
2052 // If one of the operands only has one non-zero bit, and if the other operand
2053 // has a known-zero bit in a more significant place than it (not including the
2054 // sign bit) the ripple may go up to and fill the zero, but won't change the
2055 // sign. For example, (X & ~4) + 1.
2056
2057 // TODO: Implement.
2058
2059 return false;
2060}
2061
Chris Lattner2454a2e2008-01-29 06:52:45 +00002062
Chris Lattner7e708292002-06-25 16:13:24 +00002063Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002064 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002065 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002066
Chris Lattner66331a42004-04-10 22:01:55 +00002067 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002068 // X + undef -> undef
2069 if (isa<UndefValue>(RHS))
2070 return ReplaceInstUsesWith(I, RHS);
2071
Chris Lattner66331a42004-04-10 22:01:55 +00002072 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002073 if (RHSC->isNullValue())
2074 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002075
Chris Lattner66331a42004-04-10 22:01:55 +00002076 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002077 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002078 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002079 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002080 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002081 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002082
2083 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2084 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002085 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002086 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002087
Eli Friedman709b33d2009-07-13 22:27:52 +00002088 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002089 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002090 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002091 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002092 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002093
2094 if (isa<PHINode>(LHS))
2095 if (Instruction *NV = FoldOpIntoPhi(I))
2096 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002097
Chris Lattner4f637d42006-01-06 17:59:59 +00002098 ConstantInt *XorRHS = 0;
2099 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002100 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002101 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002102 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002103 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002104
Zhou Sheng4351c642007-04-02 08:20:41 +00002105 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002106 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2107 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002108 do {
2109 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002110 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2111 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002112 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2113 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002114 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002115 if (!MaskedValueIsZero(XorLHS,
2116 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002117 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002118 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002119 }
2120 }
2121 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002122 C0080Val = APIntOps::lshr(C0080Val, Size);
2123 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2124 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002125
Reid Spencer35c38852007-03-28 01:36:16 +00002126 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002127 // with funny bit widths then this switch statement should be removed. It
2128 // is just here to get the size of the "middle" type back up to something
2129 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002130 const Type *MiddleType = 0;
2131 switch (Size) {
2132 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002133 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2134 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2135 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002136 }
2137 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002138 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002139 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002140 }
2141 }
Chris Lattner66331a42004-04-10 22:01:55 +00002142 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002143
Owen Anderson1d0be152009-08-13 21:58:54 +00002144 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002145 return BinaryOperator::CreateXor(LHS, RHS);
2146
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002147 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002148 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002149 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002150 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002151
2152 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2153 if (RHSI->getOpcode() == Instruction::Sub)
2154 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2155 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2156 }
2157 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2158 if (LHSI->getOpcode() == Instruction::Sub)
2159 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2160 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2161 }
Robert Bocchino71698282004-07-27 21:02:21 +00002162 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002163
Chris Lattner5c4afb92002-05-08 22:46:53 +00002164 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002165 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002166 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002167 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002168 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002169 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002170 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002171 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002172 }
2173
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002174 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002175 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002176
2177 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002178 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002179 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002180 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002181
Misha Brukmanfd939082005-04-21 23:48:37 +00002182
Chris Lattner50af16a2004-11-13 19:50:12 +00002183 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002184 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002185 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002186 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002187
2188 // X*C1 + X*C2 --> X * (C1+C2)
2189 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002190 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002191 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002192 }
2193
2194 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002195 if (dyn_castFoldableMul(RHS, C2) == LHS)
2196 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002197
Chris Lattnere617c9e2007-01-05 02:17:46 +00002198 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002199 if (dyn_castNotVal(LHS) == RHS ||
2200 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002201 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002202
Chris Lattnerad3448c2003-02-18 19:57:07 +00002203
Chris Lattner564a7272003-08-13 19:01:45 +00002204 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002205 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2206 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002207 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002208
2209 // A+B --> A|B iff A and B have no bits set in common.
2210 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2211 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2212 APInt LHSKnownOne(IT->getBitWidth(), 0);
2213 APInt LHSKnownZero(IT->getBitWidth(), 0);
2214 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2215 if (LHSKnownZero != 0) {
2216 APInt RHSKnownOne(IT->getBitWidth(), 0);
2217 APInt RHSKnownZero(IT->getBitWidth(), 0);
2218 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2219
2220 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002221 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002222 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002223 }
2224 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002225
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002226 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002227 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002228 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002229 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2230 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002231 if (W != Y) {
2232 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002233 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002234 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002235 std::swap(W, X);
2236 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002237 std::swap(Y, Z);
2238 std::swap(W, X);
2239 }
2240 }
2241
2242 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002243 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002244 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002245 }
2246 }
2247 }
2248
Chris Lattner6b032052003-10-02 15:11:26 +00002249 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002250 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002251 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002252 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002253
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002254 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002255 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002256 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002257 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002258 if (Anded == CRHS) {
2259 // See if all bits from the first bit set in the Add RHS up are included
2260 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002261 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002262
2263 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002264 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002265
2266 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002267 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002268
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002269 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2270 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002271 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002272 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002273 }
2274 }
2275 }
2276
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002277 // Try to fold constant add into select arguments.
2278 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002279 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002280 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002281 }
2282
Chris Lattner42790482007-12-20 01:56:58 +00002283 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002284 {
2285 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002286 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002287 if (!SI) {
2288 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002289 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002290 }
Chris Lattner42790482007-12-20 01:56:58 +00002291 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002292 Value *TV = SI->getTrueValue();
2293 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002294 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002295
2296 // Can we fold the add into the argument of the select?
2297 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002298 if (match(FV, m_Zero()) &&
2299 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002300 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002301 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002302 if (match(TV, m_Zero()) &&
2303 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002304 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002305 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002306 }
2307 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002308
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002309 // Check for (add (sext x), y), see if we can merge this into an
2310 // integer add followed by a sext.
2311 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2312 // (add (sext x), cst) --> (sext (add x, cst'))
2313 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2314 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002315 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002316 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002317 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002318 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2319 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002320 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2321 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002322 return new SExtInst(NewAdd, I.getType());
2323 }
2324 }
2325
2326 // (add (sext x), (sext y)) --> (sext (add int x, y))
2327 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2328 // Only do this if x/y have the same type, if at last one of them has a
2329 // single use (so we don't increase the number of sexts), and if the
2330 // integer add will not overflow.
2331 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2332 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2333 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2334 RHSConv->getOperand(0))) {
2335 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002336 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2337 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002338 return new SExtInst(NewAdd, I.getType());
2339 }
2340 }
2341 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002342
2343 return Changed ? &I : 0;
2344}
2345
2346Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2347 bool Changed = SimplifyCommutative(I);
2348 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2349
2350 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2351 // X + 0 --> X
2352 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002353 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002354 (I.getType())->getValueAPF()))
2355 return ReplaceInstUsesWith(I, LHS);
2356 }
2357
2358 if (isa<PHINode>(LHS))
2359 if (Instruction *NV = FoldOpIntoPhi(I))
2360 return NV;
2361 }
2362
2363 // -A + B --> B - A
2364 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002365 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002366 return BinaryOperator::CreateFSub(RHS, LHSV);
2367
2368 // A + -B --> A - B
2369 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002370 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002371 return BinaryOperator::CreateFSub(LHS, V);
2372
2373 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2374 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2375 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2376 return ReplaceInstUsesWith(I, LHS);
2377
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002378 // Check for (add double (sitofp x), y), see if we can merge this into an
2379 // integer add followed by a promotion.
2380 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2381 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2382 // ... if the constant fits in the integer value. This is useful for things
2383 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2384 // requires a constant pool load, and generally allows the add to be better
2385 // instcombined.
2386 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2387 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002388 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002389 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002390 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002391 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2392 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002393 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2394 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002395 return new SIToFPInst(NewAdd, I.getType());
2396 }
2397 }
2398
2399 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2400 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2401 // Only do this if x/y have the same type, if at last one of them has a
2402 // single use (so we don't increase the number of int->fp conversions),
2403 // and if the integer add will not overflow.
2404 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2405 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2406 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2407 RHSConv->getOperand(0))) {
2408 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002409 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2410 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002411 return new SIToFPInst(NewAdd, I.getType());
2412 }
2413 }
2414 }
2415
Chris Lattner7e708292002-06-25 16:13:24 +00002416 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002417}
2418
Chris Lattner7e708292002-06-25 16:13:24 +00002419Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002420 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002421
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002422 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002423 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002424
Chris Lattner233f7dc2002-08-12 21:17:25 +00002425 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002426 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002427 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002428
Chris Lattnere87597f2004-10-16 18:11:37 +00002429 if (isa<UndefValue>(Op0))
2430 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2431 if (isa<UndefValue>(Op1))
2432 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2433
Chris Lattnerd65460f2003-11-05 01:06:05 +00002434 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2435 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002436 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002437 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002438
Chris Lattnerd65460f2003-11-05 01:06:05 +00002439 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002440 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002441 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002442 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002443
Chris Lattner76b7a062007-01-15 07:02:54 +00002444 // -(X >>u 31) -> (X >>s 31)
2445 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002446 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002447 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002448 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002449 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002450 // 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 Spencerb83eb642006-10-20 07:07:24 +00002452 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002453 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002454 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002455 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002456 }
2457 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002458 }
2459 else if (SI->getOpcode() == Instruction::AShr) {
2460 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2461 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002462 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002463 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002464 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002465 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002466 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002467 }
2468 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002469 }
2470 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002471 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002472
2473 // Try to fold constant sub into select arguments.
2474 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002475 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002476 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002477
2478 // C - zext(bool) -> bool ? C - 1 : C
2479 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002480 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002481 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002482 }
2483
Owen Anderson1d0be152009-08-13 21:58:54 +00002484 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002485 return BinaryOperator::CreateXor(Op0, Op1);
2486
Chris Lattner43d84d62005-04-07 16:15:25 +00002487 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002488 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002489 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002490 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002491 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002492 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002493 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002494 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002495 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2496 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2497 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002498 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002499 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002500 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002501 }
2502
Chris Lattnerfd059242003-10-15 16:48:29 +00002503 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002504 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2505 // is not used by anyone else...
2506 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002507 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002508 // Swap the two operands of the subexpr...
2509 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2510 Op1I->setOperand(0, IIOp1);
2511 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002512
Chris Lattnera2881962003-02-18 19:28:33 +00002513 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002514 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002515 }
2516
2517 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2518 //
2519 if (Op1I->getOpcode() == Instruction::And &&
2520 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2521 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2522
Chris Lattner74381062009-08-30 07:44:24 +00002523 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002524 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002525 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002526
Reid Spencerac5209e2006-10-16 23:08:08 +00002527 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002528 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002529 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002530 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002531 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002532 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002533 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002534
Chris Lattnerad3448c2003-02-18 19:57:07 +00002535 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002536 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002537 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002538 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002539 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002540 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002541 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002542 }
Chris Lattner40371712002-05-09 01:29:19 +00002543 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002544 }
Chris Lattnera2881962003-02-18 19:28:33 +00002545
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002546 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2547 if (Op0I->getOpcode() == Instruction::Add) {
2548 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2549 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2550 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2551 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2552 } else if (Op0I->getOpcode() == Instruction::Sub) {
2553 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002554 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002555 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002556 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002557 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002558
Chris Lattner50af16a2004-11-13 19:50:12 +00002559 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002560 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002561 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002562 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002563
Chris Lattner50af16a2004-11-13 19:50:12 +00002564 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002565 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002566 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002567 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002568 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002569}
2570
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002571Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2572 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2573
2574 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002575 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002576 return BinaryOperator::CreateFAdd(Op0, V);
2577
2578 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2579 if (Op1I->getOpcode() == Instruction::FAdd) {
2580 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002581 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002582 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002583 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002584 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002585 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002586 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002587 }
2588
2589 return 0;
2590}
2591
Chris Lattnera0141b92007-07-15 20:42:37 +00002592/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2593/// comparison only checks the sign bit. If it only checks the sign bit, set
2594/// TrueIfSigned if the result of the comparison is true when the input value is
2595/// signed.
2596static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2597 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002598 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002599 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2600 TrueIfSigned = true;
2601 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002602 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2603 TrueIfSigned = true;
2604 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002605 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2606 TrueIfSigned = false;
2607 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002608 case ICmpInst::ICMP_UGT:
2609 // True if LHS u> RHS and RHS == high-bit-mask - 1
2610 TrueIfSigned = true;
2611 return RHS->getValue() ==
2612 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2613 case ICmpInst::ICMP_UGE:
2614 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2615 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002616 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002617 default:
2618 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002619 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002620}
2621
Chris Lattner7e708292002-06-25 16:13:24 +00002622Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002623 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002624 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002625
Eli Friedman1694e092009-07-18 09:12:15 +00002626 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002627 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002628
Chris Lattner233f7dc2002-08-12 21:17:25 +00002629 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002630 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2631 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002632
2633 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002634 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002635 if (SI->getOpcode() == Instruction::Shl)
2636 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002637 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002638 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002639
Zhou Sheng843f07672007-04-19 05:39:12 +00002640 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002641 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2642 if (CI->equalsInt(1)) // X * 1 == X
2643 return ReplaceInstUsesWith(I, Op0);
2644 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002645 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002646
Zhou Sheng97b52c22007-03-29 01:57:21 +00002647 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002648 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002649 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002650 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002651 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002652 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002653 if (Op1->isNullValue())
2654 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002655
2656 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2657 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002658 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002659
2660 // As above, vector X*splat(1.0) -> X in all defined cases.
2661 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002662 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2663 if (CI->equalsInt(1))
2664 return ReplaceInstUsesWith(I, Op0);
2665 }
2666 }
Chris Lattnera2881962003-02-18 19:28:33 +00002667 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002668
2669 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2670 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002671 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002672 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner74381062009-08-30 07:44:24 +00002673 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2674 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002675 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002676
2677 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002678
2679 // Try to fold constant mul into select arguments.
2680 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002681 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002682 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002683
2684 if (isa<PHINode>(Op0))
2685 if (Instruction *NV = FoldOpIntoPhi(I))
2686 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002687 }
2688
Dan Gohman186a6362009-08-12 16:04:34 +00002689 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2690 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002691 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002692
Nick Lewycky0c730792008-11-21 07:33:58 +00002693 // (X / Y) * Y = X - (X % Y)
2694 // (X / Y) * -Y = (X % Y) - X
2695 {
2696 Value *Op1 = I.getOperand(1);
2697 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2698 if (!BO ||
2699 (BO->getOpcode() != Instruction::UDiv &&
2700 BO->getOpcode() != Instruction::SDiv)) {
2701 Op1 = Op0;
2702 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2703 }
Dan Gohman186a6362009-08-12 16:04:34 +00002704 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002705 if (BO && BO->hasOneUse() &&
2706 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2707 (BO->getOpcode() == Instruction::UDiv ||
2708 BO->getOpcode() == Instruction::SDiv)) {
2709 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2710
Dan Gohmanfa94b942009-08-12 16:33:09 +00002711 // If the division is exact, X % Y is zero.
2712 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2713 if (SDiv->isExact()) {
2714 if (Op1BO == Op1)
2715 return ReplaceInstUsesWith(I, Op0BO);
2716 else
2717 return BinaryOperator::CreateNeg(Op0BO);
2718 }
2719
Chris Lattner74381062009-08-30 07:44:24 +00002720 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002721 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002722 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002723 else
Chris Lattner74381062009-08-30 07:44:24 +00002724 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002725 Rem->takeName(BO);
2726
2727 if (Op1BO == Op1)
2728 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002729 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002730 }
2731 }
2732
Owen Anderson1d0be152009-08-13 21:58:54 +00002733 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002734 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2735
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002736 // If one of the operands of the multiply is a cast from a boolean value, then
2737 // we know the bool is either zero or one, so this is a 'masking' multiply.
2738 // See if we can simplify things based on how the boolean was originally
2739 // formed.
2740 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002741 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson1d0be152009-08-13 21:58:54 +00002742 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002743 BoolCast = CI;
2744 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002745 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00002746 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002747 BoolCast = CI;
2748 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002749 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002750 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2751 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002752 bool TIS = false;
2753
Reid Spencere4d87aa2006-12-23 06:05:41 +00002754 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002755 // multiply into a shift/and combination.
2756 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002757 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2758 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002759 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002760 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002761 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner74381062009-08-30 07:44:24 +00002762 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2763 BoolCast->getOperand(0)->getName()+".mask");
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002764
2765 // If the multiply type is not the same as the source type, sign extend
2766 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002767 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002768 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2769 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002770 Instruction::CastOps opcode =
2771 (SrcBits == DstBits ? Instruction::BitCast :
2772 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2773 V = InsertCastBefore(opcode, V, I.getType(), I);
2774 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002775
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002776 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002777 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002778 }
2779 }
2780 }
2781
Chris Lattner7e708292002-06-25 16:13:24 +00002782 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002783}
2784
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002785Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2786 bool Changed = SimplifyCommutative(I);
2787 Value *Op0 = I.getOperand(0);
2788
2789 // Simplify mul instructions with a constant RHS...
2790 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2791 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2792 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2793 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2794 if (Op1F->isExactlyValue(1.0))
2795 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2796 } else if (isa<VectorType>(Op1->getType())) {
2797 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2798 // As above, vector X*splat(1.0) -> X in all defined cases.
2799 if (Constant *Splat = Op1V->getSplatValue()) {
2800 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2801 if (F->isExactlyValue(1.0))
2802 return ReplaceInstUsesWith(I, Op0);
2803 }
2804 }
2805 }
2806
2807 // Try to fold constant mul into select arguments.
2808 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2809 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2810 return R;
2811
2812 if (isa<PHINode>(Op0))
2813 if (Instruction *NV = FoldOpIntoPhi(I))
2814 return NV;
2815 }
2816
Dan Gohman186a6362009-08-12 16:04:34 +00002817 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2818 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002819 return BinaryOperator::CreateFMul(Op0v, Op1v);
2820
2821 return Changed ? &I : 0;
2822}
2823
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002824/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2825/// instruction.
2826bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2827 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2828
2829 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2830 int NonNullOperand = -1;
2831 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2832 if (ST->isNullValue())
2833 NonNullOperand = 2;
2834 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2835 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2836 if (ST->isNullValue())
2837 NonNullOperand = 1;
2838
2839 if (NonNullOperand == -1)
2840 return false;
2841
2842 Value *SelectCond = SI->getOperand(0);
2843
2844 // Change the div/rem to use 'Y' instead of the select.
2845 I.setOperand(1, SI->getOperand(NonNullOperand));
2846
2847 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2848 // problem. However, the select, or the condition of the select may have
2849 // multiple uses. Based on our knowledge that the operand must be non-zero,
2850 // propagate the known value for the select into other uses of it, and
2851 // propagate a known value of the condition into its other users.
2852
2853 // If the select and condition only have a single use, don't bother with this,
2854 // early exit.
2855 if (SI->use_empty() && SelectCond->hasOneUse())
2856 return true;
2857
2858 // Scan the current block backward, looking for other uses of SI.
2859 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2860
2861 while (BBI != BBFront) {
2862 --BBI;
2863 // If we found a call to a function, we can't assume it will return, so
2864 // information from below it cannot be propagated above it.
2865 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2866 break;
2867
2868 // Replace uses of the select or its condition with the known values.
2869 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2870 I != E; ++I) {
2871 if (*I == SI) {
2872 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002873 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002874 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002875 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2876 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002877 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002878 }
2879 }
2880
2881 // If we past the instruction, quit looking for it.
2882 if (&*BBI == SI)
2883 SI = 0;
2884 if (&*BBI == SelectCond)
2885 SelectCond = 0;
2886
2887 // If we ran out of things to eliminate, break out of the loop.
2888 if (SelectCond == 0 && SI == 0)
2889 break;
2890
2891 }
2892 return true;
2893}
2894
2895
Reid Spencer1628cec2006-10-26 06:15:43 +00002896/// This function implements the transforms on div instructions that work
2897/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2898/// used by the visitors to those instructions.
2899/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002900Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002901 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002902
Chris Lattner50b2ca42008-02-19 06:12:18 +00002903 // undef / X -> 0 for integer.
2904 // undef / X -> undef for FP (the undef could be a snan).
2905 if (isa<UndefValue>(Op0)) {
2906 if (Op0->getType()->isFPOrFPVector())
2907 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002908 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002909 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002910
2911 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002912 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002913 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002914
Reid Spencer1628cec2006-10-26 06:15:43 +00002915 return 0;
2916}
Misha Brukmanfd939082005-04-21 23:48:37 +00002917
Reid Spencer1628cec2006-10-26 06:15:43 +00002918/// This function implements the transforms common to both integer division
2919/// instructions (udiv and sdiv). It is called by the visitors to those integer
2920/// division instructions.
2921/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002922Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002923 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2924
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002925 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002926 if (Op0 == Op1) {
2927 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002928 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002929 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002930 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002931 }
2932
Owen Andersoneed707b2009-07-24 23:12:02 +00002933 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002934 return ReplaceInstUsesWith(I, CI);
2935 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002936
Reid Spencer1628cec2006-10-26 06:15:43 +00002937 if (Instruction *Common = commonDivTransforms(I))
2938 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002939
2940 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2941 // This does not apply for fdiv.
2942 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2943 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002944
2945 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2946 // div X, 1 == X
2947 if (RHS->equalsInt(1))
2948 return ReplaceInstUsesWith(I, Op0);
2949
2950 // (X / C1) / C2 -> X / (C1*C2)
2951 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2952 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2953 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002954 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002955 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002956 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002957 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002958 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002959 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002960 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002961
Reid Spencerbca0e382007-03-23 20:05:17 +00002962 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002963 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2964 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2965 return R;
2966 if (isa<PHINode>(Op0))
2967 if (Instruction *NV = FoldOpIntoPhi(I))
2968 return NV;
2969 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002970 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002971
Chris Lattnera2881962003-02-18 19:28:33 +00002972 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002973 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002974 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00002975 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002976
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002977 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00002978 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002979 return ReplaceInstUsesWith(I, Op0);
2980
Nick Lewycky895f0852008-11-27 20:21:08 +00002981 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2982 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2983 // div X, 1 == X
2984 if (X->isOne())
2985 return ReplaceInstUsesWith(I, Op0);
2986 }
2987
Reid Spencer1628cec2006-10-26 06:15:43 +00002988 return 0;
2989}
2990
2991Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2992 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2993
2994 // Handle the integer div common cases
2995 if (Instruction *Common = commonIDivTransforms(I))
2996 return Common;
2997
Reid Spencer1628cec2006-10-26 06:15:43 +00002998 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002999 // X udiv C^2 -> X >> C
3000 // Check to see if this is an unsigned division with an exact power of 2,
3001 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003002 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003003 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003004 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003005
3006 // X udiv C, where C >= signbit
3007 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003008 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003009 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003010 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003011 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003012 }
3013
3014 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003015 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003016 if (RHSI->getOpcode() == Instruction::Shl &&
3017 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003018 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003019 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003020 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003021 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003022 if (uint32_t C2 = C1.logBase2())
3023 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003024 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003025 }
3026 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003027 }
3028
Reid Spencer1628cec2006-10-26 06:15:43 +00003029 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3030 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003031 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003032 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003033 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003034 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003035 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003036 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003037 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003038 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003039 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003040 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003041
3042 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003043 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003044 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003045
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003046 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003047 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003048 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003049 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003050 return 0;
3051}
3052
Reid Spencer1628cec2006-10-26 06:15:43 +00003053Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3054 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3055
3056 // Handle the integer div common cases
3057 if (Instruction *Common = commonIDivTransforms(I))
3058 return Common;
3059
3060 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3061 // sdiv X, -1 == -X
3062 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003063 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003064
Dan Gohmanfa94b942009-08-12 16:33:09 +00003065 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003066 if (cast<SDivOperator>(&I)->isExact() &&
3067 RHS->getValue().isNonNegative() &&
3068 RHS->getValue().isPowerOf2()) {
3069 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3070 RHS->getValue().exactLogBase2());
3071 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3072 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003073
3074 // -X/C --> X/-C provided the negation doesn't overflow.
3075 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3076 if (isa<Constant>(Sub->getOperand(0)) &&
3077 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003078 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003079 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3080 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003081 }
3082
3083 // If the sign bits of both operands are zero (i.e. we can prove they are
3084 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003085 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003086 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003087 if (MaskedValueIsZero(Op0, Mask)) {
3088 if (MaskedValueIsZero(Op1, Mask)) {
3089 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3090 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3091 }
3092 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003093 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003094 ShiftedInt->getValue().isPowerOf2()) {
3095 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3096 // Safe because the only negative value (1 << Y) can take on is
3097 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3098 // the sign bit set.
3099 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3100 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003101 }
Eli Friedman8be17392009-07-18 09:53:21 +00003102 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003103
3104 return 0;
3105}
3106
3107Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3108 return commonDivTransforms(I);
3109}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003110
Reid Spencer0a783f72006-11-02 01:53:59 +00003111/// This function implements the transforms on rem instructions that work
3112/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3113/// is used by the visitors to those instructions.
3114/// @brief Transforms common to all three rem instructions
3115Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003116 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003117
Chris Lattner50b2ca42008-02-19 06:12:18 +00003118 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3119 if (I.getType()->isFPOrFPVector())
3120 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003121 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003122 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003123 if (isa<UndefValue>(Op1))
3124 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003125
3126 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003127 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3128 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003129
Reid Spencer0a783f72006-11-02 01:53:59 +00003130 return 0;
3131}
3132
3133/// This function implements the transforms common to both integer remainder
3134/// instructions (urem and srem). It is called by the visitors to those integer
3135/// remainder instructions.
3136/// @brief Common integer remainder transforms
3137Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3138 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3139
3140 if (Instruction *common = commonRemTransforms(I))
3141 return common;
3142
Dale Johannesened6af242009-01-21 00:35:19 +00003143 // 0 % X == 0 for integer, we don't need to preserve faults!
3144 if (Constant *LHS = dyn_cast<Constant>(Op0))
3145 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003146 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003147
Chris Lattner857e8cd2004-12-12 21:48:58 +00003148 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003149 // X % 0 == undef, we don't need to preserve faults!
3150 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003151 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003152
Chris Lattnera2881962003-02-18 19:28:33 +00003153 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003154 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003155
Chris Lattner97943922006-02-28 05:49:21 +00003156 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3157 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3158 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3159 return R;
3160 } else if (isa<PHINode>(Op0I)) {
3161 if (Instruction *NV = FoldOpIntoPhi(I))
3162 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003163 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003164
3165 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003166 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003167 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003168 }
Chris Lattnera2881962003-02-18 19:28:33 +00003169 }
3170
Reid Spencer0a783f72006-11-02 01:53:59 +00003171 return 0;
3172}
3173
3174Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3175 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3176
3177 if (Instruction *common = commonIRemTransforms(I))
3178 return common;
3179
3180 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3181 // X urem C^2 -> X and C
3182 // Check to see if this is an unsigned remainder with an exact power of 2,
3183 // if so, convert to a bitwise and.
3184 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003185 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003186 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003187 }
3188
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003189 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003190 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3191 if (RHSI->getOpcode() == Instruction::Shl &&
3192 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003193 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003194 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003195 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003196 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003197 }
3198 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003199 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003200
Reid Spencer0a783f72006-11-02 01:53:59 +00003201 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3202 // where C1&C2 are powers of two.
3203 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3204 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3205 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3206 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003207 if ((STO->getValue().isPowerOf2()) &&
3208 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003209 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3210 SI->getName()+".t");
3211 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3212 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003213 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003214 }
3215 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003216 }
3217
Chris Lattner3f5b8772002-05-06 16:14:14 +00003218 return 0;
3219}
3220
Reid Spencer0a783f72006-11-02 01:53:59 +00003221Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3222 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3223
Dan Gohmancff55092007-11-05 23:16:33 +00003224 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003225 if (Instruction *Common = commonIRemTransforms(I))
3226 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003227
Dan Gohman186a6362009-08-12 16:04:34 +00003228 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003229 if (!isa<Constant>(RHSNeg) ||
3230 (isa<ConstantInt>(RHSNeg) &&
3231 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003232 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003233 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003234 I.setOperand(1, RHSNeg);
3235 return &I;
3236 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003237
Dan Gohmancff55092007-11-05 23:16:33 +00003238 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003239 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003240 if (I.getType()->isInteger()) {
3241 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3242 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3243 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003244 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003245 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003246 }
3247
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003248 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003249 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3250 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003251
Nick Lewycky9dce8732008-12-20 16:48:00 +00003252 bool hasNegative = false;
3253 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3254 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3255 if (RHS->getValue().isNegative())
3256 hasNegative = true;
3257
3258 if (hasNegative) {
3259 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003260 for (unsigned i = 0; i != VWidth; ++i) {
3261 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3262 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003263 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003264 else
3265 Elts[i] = RHS;
3266 }
3267 }
3268
Owen Andersonaf7ec972009-07-28 21:19:26 +00003269 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003270 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003271 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003272 I.setOperand(1, NewRHSV);
3273 return &I;
3274 }
3275 }
3276 }
3277
Reid Spencer0a783f72006-11-02 01:53:59 +00003278 return 0;
3279}
3280
3281Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003282 return commonRemTransforms(I);
3283}
3284
Chris Lattner457dd822004-06-09 07:59:58 +00003285// isOneBitSet - Return true if there is exactly one bit set in the specified
3286// constant.
3287static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003288 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003289}
3290
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003291// isHighOnes - Return true if the constant is of the form 1+0+.
3292// This is the same as lowones(~X).
3293static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003294 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003295}
3296
Reid Spencere4d87aa2006-12-23 06:05:41 +00003297/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003298/// are carefully arranged to allow folding of expressions such as:
3299///
3300/// (A < B) | (A > B) --> (A != B)
3301///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003302/// Note that this is only valid if the first and second predicates have the
3303/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003304///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003305/// Three bits are used to represent the condition, as follows:
3306/// 0 A > B
3307/// 1 A == B
3308/// 2 A < B
3309///
3310/// <=> Value Definition
3311/// 000 0 Always false
3312/// 001 1 A > B
3313/// 010 2 A == B
3314/// 011 3 A >= B
3315/// 100 4 A < B
3316/// 101 5 A != B
3317/// 110 6 A <= B
3318/// 111 7 Always true
3319///
3320static unsigned getICmpCode(const ICmpInst *ICI) {
3321 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003322 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003323 case ICmpInst::ICMP_UGT: return 1; // 001
3324 case ICmpInst::ICMP_SGT: return 1; // 001
3325 case ICmpInst::ICMP_EQ: return 2; // 010
3326 case ICmpInst::ICMP_UGE: return 3; // 011
3327 case ICmpInst::ICMP_SGE: return 3; // 011
3328 case ICmpInst::ICMP_ULT: return 4; // 100
3329 case ICmpInst::ICMP_SLT: return 4; // 100
3330 case ICmpInst::ICMP_NE: return 5; // 101
3331 case ICmpInst::ICMP_ULE: return 6; // 110
3332 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003333 // True -> 7
3334 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003335 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003336 return 0;
3337 }
3338}
3339
Evan Cheng8db90722008-10-14 17:15:11 +00003340/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3341/// predicate into a three bit mask. It also returns whether it is an ordered
3342/// predicate by reference.
3343static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3344 isOrdered = false;
3345 switch (CC) {
3346 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3347 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003348 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3349 case FCmpInst::FCMP_UGT: return 1; // 001
3350 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3351 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003352 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3353 case FCmpInst::FCMP_UGE: return 3; // 011
3354 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3355 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003356 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3357 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003358 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3359 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003360 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003361 default:
3362 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003363 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003364 return 0;
3365 }
3366}
3367
Reid Spencere4d87aa2006-12-23 06:05:41 +00003368/// getICmpValue - This is the complement of getICmpCode, which turns an
3369/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003370/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003371/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003372static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003373 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003374 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003375 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003376 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003377 case 1:
3378 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003379 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003380 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003381 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3382 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003383 case 3:
3384 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003385 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003386 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003387 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003388 case 4:
3389 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003390 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003391 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003392 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3393 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003394 case 6:
3395 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003396 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003397 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003398 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003399 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003400 }
3401}
3402
Evan Cheng8db90722008-10-14 17:15:11 +00003403/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3404/// opcode and two operands into either a FCmp instruction. isordered is passed
3405/// in to determine which kind of predicate to use in the new fcmp instruction.
3406static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003407 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003408 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003409 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003410 case 0:
3411 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003412 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003413 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003414 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003415 case 1:
3416 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003417 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003418 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003419 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003420 case 2:
3421 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003422 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003423 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003424 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003425 case 3:
3426 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003427 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003428 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003429 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003430 case 4:
3431 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003432 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003433 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003434 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003435 case 5:
3436 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003437 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003438 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003439 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003440 case 6:
3441 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003442 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003443 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003444 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003445 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003446 }
3447}
3448
Chris Lattnerb9553d62008-11-16 04:55:20 +00003449/// PredicatesFoldable - Return true if both predicates match sign or if at
3450/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003451static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3452 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003453 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3454 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003455}
3456
3457namespace {
3458// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3459struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003460 InstCombiner &IC;
3461 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003462 ICmpInst::Predicate pred;
3463 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3464 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3465 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003466 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003467 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3468 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003469 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3470 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003471 return false;
3472 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003473 Instruction *apply(Instruction &Log) const {
3474 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3475 if (ICI->getOperand(0) != LHS) {
3476 assert(ICI->getOperand(1) == LHS);
3477 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003478 }
3479
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003480 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003481 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003482 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003483 unsigned Code;
3484 switch (Log.getOpcode()) {
3485 case Instruction::And: Code = LHSCode & RHSCode; break;
3486 case Instruction::Or: Code = LHSCode | RHSCode; break;
3487 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003488 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003489 }
3490
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003491 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3492 ICmpInst::isSignedPredicate(ICI->getPredicate());
3493
Owen Andersond672ecb2009-07-03 00:17:18 +00003494 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003495 if (Instruction *I = dyn_cast<Instruction>(RV))
3496 return I;
3497 // Otherwise, it's a constant boolean value...
3498 return IC.ReplaceInstUsesWith(Log, RV);
3499 }
3500};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003501} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003502
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003503// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3504// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003505// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003506Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003507 ConstantInt *OpRHS,
3508 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003509 BinaryOperator &TheAnd) {
3510 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003511 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003512 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003513 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003514
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003515 switch (Op->getOpcode()) {
3516 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003517 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003518 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003519 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003520 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003521 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003522 }
3523 break;
3524 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003525 if (Together == AndRHS) // (X | C) & C --> C
3526 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003527
Chris Lattner6e7ba452005-01-01 16:22:27 +00003528 if (Op->hasOneUse() && Together != OpRHS) {
3529 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003530 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003531 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003532 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003533 }
3534 break;
3535 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003536 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003537 // Adding a one to a single bit bit-field should be turned into an XOR
3538 // of the bit. First thing to check is to see if this AND is with a
3539 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003540 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003541
3542 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003543 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003544 // Ok, at this point, we know that we are masking the result of the
3545 // ADD down to exactly one bit. If the constant we are adding has
3546 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003547 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003548
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003549 // Check to see if any bits below the one bit set in AndRHSV are set.
3550 if ((AddRHS & (AndRHSV-1)) == 0) {
3551 // If not, the only thing that can effect the output of the AND is
3552 // the bit specified by AndRHSV. If that bit is set, the effect of
3553 // the XOR is to toggle the bit. If it is clear, then the ADD has
3554 // no effect.
3555 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3556 TheAnd.setOperand(0, X);
3557 return &TheAnd;
3558 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003559 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003560 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003561 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003562 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003563 }
3564 }
3565 }
3566 }
3567 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003568
3569 case Instruction::Shl: {
3570 // We know that the AND will not produce any of the bits shifted in, so if
3571 // the anded constant includes them, clear them now!
3572 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003573 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003574 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003575 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003576 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003577
Zhou Sheng290bec52007-03-29 08:15:12 +00003578 if (CI->getValue() == ShlMask) {
3579 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003580 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3581 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003582 TheAnd.setOperand(1, CI);
3583 return &TheAnd;
3584 }
3585 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003586 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003587 case Instruction::LShr:
3588 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003589 // We know that the AND will not produce any of the bits shifted in, so if
3590 // the anded constant includes them, clear them now! This only applies to
3591 // unsigned shifts, because a signed shr may bring in set bits!
3592 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003593 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003594 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003595 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003596 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003597
Zhou Sheng290bec52007-03-29 08:15:12 +00003598 if (CI->getValue() == ShrMask) {
3599 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003600 return ReplaceInstUsesWith(TheAnd, Op);
3601 } else if (CI != AndRHS) {
3602 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3603 return &TheAnd;
3604 }
3605 break;
3606 }
3607 case Instruction::AShr:
3608 // Signed shr.
3609 // See if this is shifting in some sign extension, then masking it out
3610 // with an and.
3611 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003612 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003613 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003614 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003615 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003616 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003617 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003618 // Make the argument unsigned.
3619 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003620 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003621 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003622 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003623 }
3624 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003625 }
3626 return 0;
3627}
3628
Chris Lattner8b170942002-08-09 23:47:40 +00003629
Chris Lattnera96879a2004-09-29 17:40:11 +00003630/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3631/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003632/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3633/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003634/// insert new instructions.
3635Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003636 bool isSigned, bool Inside,
3637 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003638 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003639 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003640 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003641
Chris Lattnera96879a2004-09-29 17:40:11 +00003642 if (Inside) {
3643 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003644 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003645
Reid Spencere4d87aa2006-12-23 06:05:41 +00003646 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003647 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003648 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003649 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003650 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003651 }
3652
3653 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003654 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003655 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003656 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003657 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003658 }
3659
3660 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003661 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003662
Reid Spencere4e40032007-03-21 23:19:50 +00003663 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003664 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003665 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003666 ICmpInst::Predicate pred = (isSigned ?
3667 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003668 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003669 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003670
Reid Spencere4e40032007-03-21 23:19:50 +00003671 // Emit V-Lo >u Hi-1-Lo
3672 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003673 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003674 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003675 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003676 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003677}
3678
Chris Lattner7203e152005-09-18 07:22:02 +00003679// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3680// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3681// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3682// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003683static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003684 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003685 uint32_t BitWidth = Val->getType()->getBitWidth();
3686 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003687
3688 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003689 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003690 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003691 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003692 return true;
3693}
3694
Chris Lattner7203e152005-09-18 07:22:02 +00003695/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3696/// where isSub determines whether the operator is a sub. If we can fold one of
3697/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003698///
3699/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3700/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3701/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3702///
3703/// return (A +/- B).
3704///
3705Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003706 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003707 Instruction &I) {
3708 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3709 if (!LHSI || LHSI->getNumOperands() != 2 ||
3710 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3711
3712 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3713
3714 switch (LHSI->getOpcode()) {
3715 default: return 0;
3716 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003717 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003718 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003719 if ((Mask->getValue().countLeadingZeros() +
3720 Mask->getValue().countPopulation()) ==
3721 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003722 break;
3723
3724 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3725 // part, we don't need any explicit masks to take them out of A. If that
3726 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003727 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003728 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003729 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003730 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003731 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003732 break;
3733 }
3734 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003735 return 0;
3736 case Instruction::Or:
3737 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003738 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003739 if ((Mask->getValue().countLeadingZeros() +
3740 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003741 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003742 break;
3743 return 0;
3744 }
3745
Chris Lattnerc8e77562005-09-18 04:24:45 +00003746 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003747 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3748 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003749}
3750
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003751/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3752Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3753 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003754 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003755 ConstantInt *LHSCst, *RHSCst;
3756 ICmpInst::Predicate LHSCC, RHSCC;
3757
Chris Lattnerea065fb2008-11-16 05:10:52 +00003758 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003759 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003760 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003761 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003762 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003763 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003764
3765 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3766 // where C is a power of 2
3767 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3768 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003769 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003770 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003771 }
3772
3773 // From here on, we only handle:
3774 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3775 if (Val != Val2) return 0;
3776
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003777 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3778 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3779 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3780 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3781 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3782 return 0;
3783
3784 // We can't fold (ugt x, C) & (sgt x, C2).
3785 if (!PredicatesFoldable(LHSCC, RHSCC))
3786 return 0;
3787
3788 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003789 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003790 if (ICmpInst::isSignedPredicate(LHSCC) ||
3791 (ICmpInst::isEquality(LHSCC) &&
3792 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003793 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003794 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003795 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3796
3797 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003798 std::swap(LHS, RHS);
3799 std::swap(LHSCst, RHSCst);
3800 std::swap(LHSCC, RHSCC);
3801 }
3802
3803 // At this point, we know we have have two icmp instructions
3804 // comparing a value against two constants and and'ing the result
3805 // together. Because of the above check, we know that we only have
3806 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3807 // (from the FoldICmpLogical check above), that the two constants
3808 // are not equal and that the larger constant is on the RHS
3809 assert(LHSCst != RHSCst && "Compares not folded above?");
3810
3811 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003812 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003813 case ICmpInst::ICMP_EQ:
3814 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003815 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003816 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3817 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3818 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003819 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003820 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3821 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3822 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3823 return ReplaceInstUsesWith(I, LHS);
3824 }
3825 case ICmpInst::ICMP_NE:
3826 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003827 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003828 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003829 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003830 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003831 break; // (X != 13 & X u< 15) -> no change
3832 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003833 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003834 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003835 break; // (X != 13 & X s< 15) -> no change
3836 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3837 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3838 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3839 return ReplaceInstUsesWith(I, RHS);
3840 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003841 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003842 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003843 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003844 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003845 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003846 }
3847 break; // (X != 13 & X != 15) -> no change
3848 }
3849 break;
3850 case ICmpInst::ICMP_ULT:
3851 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003852 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003853 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3854 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003855 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003856 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3857 break;
3858 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3859 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3860 return ReplaceInstUsesWith(I, LHS);
3861 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3862 break;
3863 }
3864 break;
3865 case ICmpInst::ICMP_SLT:
3866 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003867 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003868 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3869 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003870 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003871 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3872 break;
3873 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3874 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3875 return ReplaceInstUsesWith(I, LHS);
3876 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3877 break;
3878 }
3879 break;
3880 case ICmpInst::ICMP_UGT:
3881 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003882 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003883 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3884 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3885 return ReplaceInstUsesWith(I, RHS);
3886 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3887 break;
3888 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003889 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003890 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003891 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003892 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003893 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003894 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003895 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3896 break;
3897 }
3898 break;
3899 case ICmpInst::ICMP_SGT:
3900 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003901 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003902 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3903 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3904 return ReplaceInstUsesWith(I, RHS);
3905 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3906 break;
3907 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003908 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003909 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003910 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003911 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003912 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003913 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003914 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3915 break;
3916 }
3917 break;
3918 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003919
3920 return 0;
3921}
3922
Chris Lattner42d1be02009-07-23 05:14:02 +00003923Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3924 FCmpInst *RHS) {
3925
3926 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3927 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3928 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3929 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3930 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3931 // If either of the constants are nans, then the whole thing returns
3932 // false.
3933 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003934 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003935 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003936 LHS->getOperand(0), RHS->getOperand(0));
3937 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003938
3939 // Handle vector zeros. This occurs because the canonical form of
3940 // "fcmp ord x,x" is "fcmp ord x, 0".
3941 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3942 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003943 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003944 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003945 return 0;
3946 }
3947
3948 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3949 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3950 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3951
3952
3953 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3954 // Swap RHS operands to match LHS.
3955 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3956 std::swap(Op1LHS, Op1RHS);
3957 }
3958
3959 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3960 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3961 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003962 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00003963
3964 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003965 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003966 if (Op0CC == FCmpInst::FCMP_TRUE)
3967 return ReplaceInstUsesWith(I, RHS);
3968 if (Op1CC == FCmpInst::FCMP_TRUE)
3969 return ReplaceInstUsesWith(I, LHS);
3970
3971 bool Op0Ordered;
3972 bool Op1Ordered;
3973 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3974 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3975 if (Op1Pred == 0) {
3976 std::swap(LHS, RHS);
3977 std::swap(Op0Pred, Op1Pred);
3978 std::swap(Op0Ordered, Op1Ordered);
3979 }
3980 if (Op0Pred == 0) {
3981 // uno && ueq -> uno && (uno || eq) -> ueq
3982 // ord && olt -> ord && (ord && lt) -> olt
3983 if (Op0Ordered == Op1Ordered)
3984 return ReplaceInstUsesWith(I, RHS);
3985
3986 // uno && oeq -> uno && (ord && eq) -> false
3987 // uno && ord -> false
3988 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00003989 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003990 // ord && ueq -> ord && (uno || eq) -> oeq
3991 return cast<Instruction>(getFCmpValue(true, Op1Pred,
3992 Op0LHS, Op0RHS, Context));
3993 }
3994 }
3995
3996 return 0;
3997}
3998
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003999
Chris Lattner7e708292002-06-25 16:13:24 +00004000Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004001 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004002 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004003
Chris Lattnere87597f2004-10-16 18:11:37 +00004004 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004005 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004006
Chris Lattner6e7ba452005-01-01 16:22:27 +00004007 // and X, X = X
4008 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004009 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004010
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004011 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004012 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004013 if (SimplifyDemandedInstructionBits(I))
4014 return &I;
4015 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004016 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004017 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004018 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004019 } else if (isa<ConstantAggregateZero>(Op1)) {
4020 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004021 }
4022 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004023
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004024 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004025 const APInt& AndRHSMask = AndRHS->getValue();
4026 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004027
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004028 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004029 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004030 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004031 Value *Op0LHS = Op0I->getOperand(0);
4032 Value *Op0RHS = Op0I->getOperand(1);
4033 switch (Op0I->getOpcode()) {
4034 case Instruction::Xor:
4035 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004036 // If the mask is only needed on one incoming arm, push it up.
4037 if (Op0I->hasOneUse()) {
4038 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4039 // Not masking anything out for the LHS, move to RHS.
Chris Lattner74381062009-08-30 07:44:24 +00004040 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4041 Op0RHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004042 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004043 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004044 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004045 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004046 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4047 // Not masking anything out for the RHS, move to LHS.
Chris Lattner74381062009-08-30 07:44:24 +00004048 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4049 Op0LHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004050 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004051 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4052 }
4053 }
4054
Chris Lattner6e7ba452005-01-01 16:22:27 +00004055 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004056 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004057 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4058 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4059 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4060 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004061 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004062 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004063 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004064 break;
4065
4066 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004067 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4068 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4069 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4070 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004071 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004072
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004073 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4074 // has 1's for all bits that the subtraction with A might affect.
4075 if (Op0I->hasOneUse()) {
4076 uint32_t BitWidth = AndRHSMask.getBitWidth();
4077 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4078 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4079
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004080 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004081 if (!(A && A->isZero()) && // avoid infinite recursion.
4082 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004083 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004084 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4085 }
4086 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004087 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004088
4089 case Instruction::Shl:
4090 case Instruction::LShr:
4091 // (1 << x) & 1 --> zext(x == 0)
4092 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004093 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004094 Value *NewICmp =
4095 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004096 return new ZExtInst(NewICmp, I.getType());
4097 }
4098 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004099 }
4100
Chris Lattner58403262003-07-23 19:25:52 +00004101 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004102 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004103 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004104 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004105 // If this is an integer truncation or change from signed-to-unsigned, and
4106 // if the source is an and/or with immediate, transform it. This
4107 // frequently occurs for bitfield accesses.
4108 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004109 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004110 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004111 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004112 if (CastOp->getOpcode() == Instruction::And) {
4113 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004114 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4115 // This will fold the two constants together, which may allow
4116 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004117 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004118 CastOp->getOperand(0), I.getType(),
4119 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004120 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004121 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004122 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004123 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004124 } else if (CastOp->getOpcode() == Instruction::Or) {
4125 // Change: and (cast (or X, C1) to T), C2
4126 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004127 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004128 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004129 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004130 return ReplaceInstUsesWith(I, AndRHS);
4131 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004132 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004133 }
Chris Lattner06782f82003-07-23 19:36:21 +00004134 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004135
4136 // Try to fold constant and into select arguments.
4137 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004138 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004139 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004140 if (isa<PHINode>(Op0))
4141 if (Instruction *NV = FoldOpIntoPhi(I))
4142 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004143 }
4144
Dan Gohman186a6362009-08-12 16:04:34 +00004145 Value *Op0NotVal = dyn_castNotVal(Op0);
4146 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004147
Chris Lattner5b62aa72004-06-18 06:07:51 +00004148 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004149 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004150
Misha Brukmancb6267b2004-07-30 12:50:08 +00004151 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004152 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004153 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4154 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004155 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004156 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004157
4158 {
Chris Lattner003b6202007-06-15 05:58:24 +00004159 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004160 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004161 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4162 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004163
4164 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004165 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004166 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004167 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004168 }
4169 }
4170
Dan Gohman4ae51262009-08-12 16:23:25 +00004171 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004172 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4173 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004174
4175 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004176 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004177 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004178 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004179 }
4180 }
Chris Lattner64daab52006-04-01 08:03:55 +00004181
4182 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004183 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004184 if (A == Op1) { // (A^B)&A -> A&(A^B)
4185 I.swapOperands(); // Simplify below
4186 std::swap(Op0, Op1);
4187 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4188 cast<BinaryOperator>(Op0)->swapOperands();
4189 I.swapOperands(); // Simplify below
4190 std::swap(Op0, Op1);
4191 }
4192 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004193
Chris Lattner64daab52006-04-01 08:03:55 +00004194 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004195 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004196 if (B == Op0) { // B&(A^B) -> B&(B^A)
4197 cast<BinaryOperator>(Op1)->swapOperands();
4198 std::swap(A, B);
4199 }
Chris Lattner74381062009-08-30 07:44:24 +00004200 if (A == Op0) // A&(A^B) -> A & ~B
4201 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004202 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004203
4204 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004205 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4206 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004207 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004208 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4209 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004210 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004211 }
4212
Reid Spencere4d87aa2006-12-23 06:05:41 +00004213 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4214 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004215 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004216 return R;
4217
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004218 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4219 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4220 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004221 }
4222
Chris Lattner6fc205f2006-05-05 06:39:07 +00004223 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004224 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4225 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4226 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4227 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004228 if (SrcTy == Op1C->getOperand(0)->getType() &&
4229 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004230 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004231 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4232 I.getType(), TD) &&
4233 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4234 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004235 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4236 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004237 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004238 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004239 }
Chris Lattnere511b742006-11-14 07:46:50 +00004240
4241 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004242 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4243 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4244 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004245 SI0->getOperand(1) == SI1->getOperand(1) &&
4246 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004247 Value *NewOp =
4248 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4249 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004250 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004251 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004252 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004253 }
4254
Evan Cheng8db90722008-10-14 17:15:11 +00004255 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004256 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004257 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4258 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4259 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004260 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004261
Chris Lattner7e708292002-06-25 16:13:24 +00004262 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004263}
4264
Chris Lattner8c34cd22008-10-05 02:13:19 +00004265/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4266/// capable of providing pieces of a bswap. The subexpression provides pieces
4267/// of a bswap if it is proven that each of the non-zero bytes in the output of
4268/// the expression came from the corresponding "byte swapped" byte in some other
4269/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4270/// we know that the expression deposits the low byte of %X into the high byte
4271/// of the bswap result and that all other bytes are zero. This expression is
4272/// accepted, the high byte of ByteValues is set to X to indicate a correct
4273/// match.
4274///
4275/// This function returns true if the match was unsuccessful and false if so.
4276/// On entry to the function the "OverallLeftShift" is a signed integer value
4277/// indicating the number of bytes that the subexpression is later shifted. For
4278/// example, if the expression is later right shifted by 16 bits, the
4279/// OverallLeftShift value would be -2 on entry. This is used to specify which
4280/// byte of ByteValues is actually being set.
4281///
4282/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4283/// byte is masked to zero by a user. For example, in (X & 255), X will be
4284/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4285/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4286/// always in the local (OverallLeftShift) coordinate space.
4287///
4288static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4289 SmallVector<Value*, 8> &ByteValues) {
4290 if (Instruction *I = dyn_cast<Instruction>(V)) {
4291 // If this is an or instruction, it may be an inner node of the bswap.
4292 if (I->getOpcode() == Instruction::Or) {
4293 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4294 ByteValues) ||
4295 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4296 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004297 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004298
4299 // If this is a logical shift by a constant multiple of 8, recurse with
4300 // OverallLeftShift and ByteMask adjusted.
4301 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4302 unsigned ShAmt =
4303 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4304 // Ensure the shift amount is defined and of a byte value.
4305 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4306 return true;
4307
4308 unsigned ByteShift = ShAmt >> 3;
4309 if (I->getOpcode() == Instruction::Shl) {
4310 // X << 2 -> collect(X, +2)
4311 OverallLeftShift += ByteShift;
4312 ByteMask >>= ByteShift;
4313 } else {
4314 // X >>u 2 -> collect(X, -2)
4315 OverallLeftShift -= ByteShift;
4316 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004317 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004318 }
4319
4320 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4321 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4322
4323 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4324 ByteValues);
4325 }
4326
4327 // If this is a logical 'and' with a mask that clears bytes, clear the
4328 // corresponding bytes in ByteMask.
4329 if (I->getOpcode() == Instruction::And &&
4330 isa<ConstantInt>(I->getOperand(1))) {
4331 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4332 unsigned NumBytes = ByteValues.size();
4333 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4334 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4335
4336 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4337 // If this byte is masked out by a later operation, we don't care what
4338 // the and mask is.
4339 if ((ByteMask & (1 << i)) == 0)
4340 continue;
4341
4342 // If the AndMask is all zeros for this byte, clear the bit.
4343 APInt MaskB = AndMask & Byte;
4344 if (MaskB == 0) {
4345 ByteMask &= ~(1U << i);
4346 continue;
4347 }
4348
4349 // If the AndMask is not all ones for this byte, it's not a bytezap.
4350 if (MaskB != Byte)
4351 return true;
4352
4353 // Otherwise, this byte is kept.
4354 }
4355
4356 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4357 ByteValues);
4358 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004359 }
4360
Chris Lattner8c34cd22008-10-05 02:13:19 +00004361 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4362 // the input value to the bswap. Some observations: 1) if more than one byte
4363 // is demanded from this input, then it could not be successfully assembled
4364 // into a byteswap. At least one of the two bytes would not be aligned with
4365 // their ultimate destination.
4366 if (!isPowerOf2_32(ByteMask)) return true;
4367 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004368
Chris Lattner8c34cd22008-10-05 02:13:19 +00004369 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4370 // is demanded, it needs to go into byte 0 of the result. This means that the
4371 // byte needs to be shifted until it lands in the right byte bucket. The
4372 // shift amount depends on the position: if the byte is coming from the high
4373 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4374 // low part, it must be shifted left.
4375 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4376 if (InputByteNo < ByteValues.size()/2) {
4377 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4378 return true;
4379 } else {
4380 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4381 return true;
4382 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004383
4384 // If the destination byte value is already defined, the values are or'd
4385 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004386 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004387 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004388 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004389 return false;
4390}
4391
4392/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4393/// If so, insert the new bswap intrinsic and return it.
4394Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004395 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004396 if (!ITy || ITy->getBitWidth() % 16 ||
4397 // ByteMask only allows up to 32-byte values.
4398 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004399 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004400
4401 /// ByteValues - For each byte of the result, we keep track of which value
4402 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004403 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004404 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004405
4406 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004407 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4408 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004409 return 0;
4410
4411 // Check to see if all of the bytes come from the same value.
4412 Value *V = ByteValues[0];
4413 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4414
4415 // Check to make sure that all of the bytes come from the same value.
4416 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4417 if (ByteValues[i] != V)
4418 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004419 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004420 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004421 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004422 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004423}
4424
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004425/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4426/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4427/// we can simplify this expression to "cond ? C : D or B".
4428static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004429 Value *C, Value *D,
4430 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004431 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004432 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004433 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004434 return 0;
4435
Chris Lattnera6a474d2008-11-16 04:26:55 +00004436 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004437 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004438 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004439 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004440 return SelectInst::Create(Cond, C, B);
4441 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004442 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004443 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004444 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004445 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004446 return 0;
4447}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004448
Chris Lattner69d4ced2008-11-16 05:20:07 +00004449/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4450Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4451 ICmpInst *LHS, ICmpInst *RHS) {
4452 Value *Val, *Val2;
4453 ConstantInt *LHSCst, *RHSCst;
4454 ICmpInst::Predicate LHSCC, RHSCC;
4455
4456 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004457 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004458 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004459 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004460 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004461 return 0;
4462
4463 // From here on, we only handle:
4464 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4465 if (Val != Val2) return 0;
4466
4467 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4468 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4469 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4470 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4471 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4472 return 0;
4473
4474 // We can't fold (ugt x, C) | (sgt x, C2).
4475 if (!PredicatesFoldable(LHSCC, RHSCC))
4476 return 0;
4477
4478 // Ensure that the larger constant is on the RHS.
4479 bool ShouldSwap;
4480 if (ICmpInst::isSignedPredicate(LHSCC) ||
4481 (ICmpInst::isEquality(LHSCC) &&
4482 ICmpInst::isSignedPredicate(RHSCC)))
4483 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4484 else
4485 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4486
4487 if (ShouldSwap) {
4488 std::swap(LHS, RHS);
4489 std::swap(LHSCst, RHSCst);
4490 std::swap(LHSCC, RHSCC);
4491 }
4492
4493 // At this point, we know we have have two icmp instructions
4494 // comparing a value against two constants and or'ing the result
4495 // together. Because of the above check, we know that we only have
4496 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4497 // FoldICmpLogical check above), that the two constants are not
4498 // equal.
4499 assert(LHSCst != RHSCst && "Compares not folded above?");
4500
4501 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004502 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004503 case ICmpInst::ICMP_EQ:
4504 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004505 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004506 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004507 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004508 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004509 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004510 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004511 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004512 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004513 }
4514 break; // (X == 13 | X == 15) -> no change
4515 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4516 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4517 break;
4518 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4519 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4520 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4521 return ReplaceInstUsesWith(I, RHS);
4522 }
4523 break;
4524 case ICmpInst::ICMP_NE:
4525 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004526 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004527 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4528 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4529 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4530 return ReplaceInstUsesWith(I, LHS);
4531 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4532 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4533 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004534 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004535 }
4536 break;
4537 case ICmpInst::ICMP_ULT:
4538 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004539 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004540 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4541 break;
4542 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4543 // If RHSCst is [us]MAXINT, it is always false. Not handling
4544 // this can cause overflow.
4545 if (RHSCst->isMaxValue(false))
4546 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004547 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004548 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004549 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4550 break;
4551 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4552 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4553 return ReplaceInstUsesWith(I, RHS);
4554 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4555 break;
4556 }
4557 break;
4558 case ICmpInst::ICMP_SLT:
4559 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004560 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004561 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4562 break;
4563 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4564 // If RHSCst is [us]MAXINT, it is always false. Not handling
4565 // this can cause overflow.
4566 if (RHSCst->isMaxValue(true))
4567 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004568 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004569 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004570 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4571 break;
4572 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4573 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4574 return ReplaceInstUsesWith(I, RHS);
4575 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4576 break;
4577 }
4578 break;
4579 case ICmpInst::ICMP_UGT:
4580 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004581 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004582 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4583 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4584 return ReplaceInstUsesWith(I, LHS);
4585 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4586 break;
4587 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4588 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004589 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004590 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4591 break;
4592 }
4593 break;
4594 case ICmpInst::ICMP_SGT:
4595 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004596 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004597 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4598 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4599 return ReplaceInstUsesWith(I, LHS);
4600 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4601 break;
4602 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4603 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004604 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004605 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4606 break;
4607 }
4608 break;
4609 }
4610 return 0;
4611}
4612
Chris Lattner5414cc52009-07-23 05:46:22 +00004613Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4614 FCmpInst *RHS) {
4615 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4616 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4617 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4618 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4619 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4620 // If either of the constants are nans, then the whole thing returns
4621 // true.
4622 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004623 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004624
4625 // Otherwise, no need to compare the two constants, compare the
4626 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004627 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004628 LHS->getOperand(0), RHS->getOperand(0));
4629 }
4630
4631 // Handle vector zeros. This occurs because the canonical form of
4632 // "fcmp uno x,x" is "fcmp uno x, 0".
4633 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4634 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004635 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004636 LHS->getOperand(0), RHS->getOperand(0));
4637
4638 return 0;
4639 }
4640
4641 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4642 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4643 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4644
4645 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4646 // Swap RHS operands to match LHS.
4647 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4648 std::swap(Op1LHS, Op1RHS);
4649 }
4650 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4651 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4652 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004653 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004654 Op0LHS, Op0RHS);
4655 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004656 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004657 if (Op0CC == FCmpInst::FCMP_FALSE)
4658 return ReplaceInstUsesWith(I, RHS);
4659 if (Op1CC == FCmpInst::FCMP_FALSE)
4660 return ReplaceInstUsesWith(I, LHS);
4661 bool Op0Ordered;
4662 bool Op1Ordered;
4663 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4664 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4665 if (Op0Ordered == Op1Ordered) {
4666 // If both are ordered or unordered, return a new fcmp with
4667 // or'ed predicates.
4668 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4669 Op0LHS, Op0RHS, Context);
4670 if (Instruction *I = dyn_cast<Instruction>(RV))
4671 return I;
4672 // Otherwise, it's a constant boolean value...
4673 return ReplaceInstUsesWith(I, RV);
4674 }
4675 }
4676 return 0;
4677}
4678
Bill Wendlinga698a472008-12-01 08:23:25 +00004679/// FoldOrWithConstants - This helper function folds:
4680///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004681/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004682///
4683/// into:
4684///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004685/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004686///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004687/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004688Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004689 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004690 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4691 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004692
Bill Wendling286a0542008-12-02 06:24:20 +00004693 Value *V1 = 0;
4694 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004695 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004696
Bill Wendling29976b92008-12-02 06:18:11 +00004697 APInt Xor = CI1->getValue() ^ CI2->getValue();
4698 if (!Xor.isAllOnesValue()) return 0;
4699
Bill Wendling286a0542008-12-02 06:24:20 +00004700 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004701 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004702 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004703 }
4704
4705 return 0;
4706}
4707
Chris Lattner7e708292002-06-25 16:13:24 +00004708Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004709 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004710 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004711
Chris Lattner42593e62007-03-24 23:56:43 +00004712 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004713 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004714
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004715 // or X, X = X
4716 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004717 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004718
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004719 // See if we can simplify any instructions used by the instruction whose sole
4720 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004721 if (SimplifyDemandedInstructionBits(I))
4722 return &I;
4723 if (isa<VectorType>(I.getType())) {
4724 if (isa<ConstantAggregateZero>(Op1)) {
4725 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4726 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4727 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4728 return ReplaceInstUsesWith(I, I.getOperand(1));
4729 }
Chris Lattner42593e62007-03-24 23:56:43 +00004730 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004731
Chris Lattner3f5b8772002-05-06 16:14:14 +00004732 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004733 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004734 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004735 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004736 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004737 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004738 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004739 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004740 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004741 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004742 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004743
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004744 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004745 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004746 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004747 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004748 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004749 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004750 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004751 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004752
4753 // Try to fold constant and into select arguments.
4754 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004755 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004756 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004757 if (isa<PHINode>(Op0))
4758 if (Instruction *NV = FoldOpIntoPhi(I))
4759 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004760 }
4761
Chris Lattner4f637d42006-01-06 17:59:59 +00004762 Value *A = 0, *B = 0;
4763 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004764
Dan Gohman4ae51262009-08-12 16:23:25 +00004765 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004766 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4767 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004768 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004769 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4770 return ReplaceInstUsesWith(I, Op0);
4771
Chris Lattner6423d4c2006-07-10 20:25:24 +00004772 // (A | B) | C and A | (B | C) -> bswap if possible.
4773 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004774 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4775 match(Op1, m_Or(m_Value(), m_Value())) ||
4776 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4777 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004778 if (Instruction *BSwap = MatchBSwap(I))
4779 return BSwap;
4780 }
4781
Chris Lattner6e4c6492005-05-09 04:58:36 +00004782 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004783 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004784 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004785 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004786 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004787 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004788 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004789 }
4790
4791 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004792 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004793 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004794 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004795 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004796 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004797 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004798 }
4799
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004800 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004801 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004802 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4803 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004804 Value *V1 = 0, *V2 = 0, *V3 = 0;
4805 C1 = dyn_cast<ConstantInt>(C);
4806 C2 = dyn_cast<ConstantInt>(D);
4807 if (C1 && C2) { // (A & C1)|(B & C2)
4808 // If we have: ((V + N) & C1) | (V & C2)
4809 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4810 // replace with V+N.
4811 if (C1->getValue() == ~C2->getValue()) {
4812 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004813 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004814 // Add commutes, try both ways.
4815 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4816 return ReplaceInstUsesWith(I, A);
4817 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4818 return ReplaceInstUsesWith(I, A);
4819 }
4820 // Or commutes, try both ways.
4821 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004822 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004823 // Add commutes, try both ways.
4824 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4825 return ReplaceInstUsesWith(I, B);
4826 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4827 return ReplaceInstUsesWith(I, B);
4828 }
4829 }
Chris Lattner044e5332007-04-08 08:01:49 +00004830 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004831 }
4832
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004833 // Check to see if we have any common things being and'ed. If so, find the
4834 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004835 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4836 if (A == B) // (A & C)|(A & D) == A & (C|D)
4837 V1 = A, V2 = C, V3 = D;
4838 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4839 V1 = A, V2 = B, V3 = C;
4840 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4841 V1 = C, V2 = A, V3 = D;
4842 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4843 V1 = C, V2 = A, V3 = B;
4844
4845 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004846 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004847 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004848 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004849 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004850
Dan Gohman1975d032008-10-30 20:40:10 +00004851 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004852 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004853 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004854 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004855 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004856 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004857 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004858 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004859 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004860
Bill Wendlingb01865c2008-11-30 13:52:49 +00004861 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004862 if ((match(C, m_Not(m_Specific(D))) &&
4863 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004864 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004865 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004866 if ((match(A, m_Not(m_Specific(D))) &&
4867 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004868 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004869 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004870 if ((match(C, m_Not(m_Specific(B))) &&
4871 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004872 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004873 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004874 if ((match(A, m_Not(m_Specific(B))) &&
4875 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004876 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004877 }
Chris Lattnere511b742006-11-14 07:46:50 +00004878
4879 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004880 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4881 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4882 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004883 SI0->getOperand(1) == SI1->getOperand(1) &&
4884 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004885 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4886 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004887 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004888 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004889 }
4890 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004891
Bill Wendlingb3833d12008-12-01 01:07:11 +00004892 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004893 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4894 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004895 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004896 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004897 }
4898 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004899 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4900 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004901 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004902 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004903 }
4904
Dan Gohman4ae51262009-08-12 16:23:25 +00004905 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004906 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004907 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004908 } else {
4909 A = 0;
4910 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004911 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004912 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004913 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004914 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004915
Misha Brukmancb6267b2004-07-30 12:50:08 +00004916 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004917 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004918 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004919 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004920 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004921 }
Chris Lattnera2881962003-02-18 19:28:33 +00004922
Reid Spencere4d87aa2006-12-23 06:05:41 +00004923 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4924 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004925 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004926 return R;
4927
Chris Lattner69d4ced2008-11-16 05:20:07 +00004928 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4929 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4930 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004931 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004932
4933 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004934 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004935 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004936 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004937 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4938 !isa<ICmpInst>(Op1C->getOperand(0))) {
4939 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004940 if (SrcTy == Op1C->getOperand(0)->getType() &&
4941 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004942 // Only do this if the casts both really cause code to be
4943 // generated.
4944 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4945 I.getType(), TD) &&
4946 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4947 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004948 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4949 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004950 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004951 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004952 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004953 }
Chris Lattner99c65742007-10-24 05:38:08 +00004954 }
4955
4956
4957 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4958 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00004959 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4960 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4961 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004962 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004963
Chris Lattner7e708292002-06-25 16:13:24 +00004964 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004965}
4966
Dan Gohman844731a2008-05-13 00:00:25 +00004967namespace {
4968
Chris Lattnerc317d392004-02-16 01:20:27 +00004969// XorSelf - Implements: X ^ X --> 0
4970struct XorSelf {
4971 Value *RHS;
4972 XorSelf(Value *rhs) : RHS(rhs) {}
4973 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4974 Instruction *apply(BinaryOperator &Xor) const {
4975 return &Xor;
4976 }
4977};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004978
Dan Gohman844731a2008-05-13 00:00:25 +00004979}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004980
Chris Lattner7e708292002-06-25 16:13:24 +00004981Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004982 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004983 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004984
Evan Chengd34af782008-03-25 20:07:13 +00004985 if (isa<UndefValue>(Op1)) {
4986 if (isa<UndefValue>(Op0))
4987 // Handle undef ^ undef -> 0 special case. This is a common
4988 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00004989 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004990 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004991 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004992
Chris Lattnerc317d392004-02-16 01:20:27 +00004993 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00004994 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004995 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00004996 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004997 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004998
4999 // See if we can simplify any instructions used by the instruction whose sole
5000 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005001 if (SimplifyDemandedInstructionBits(I))
5002 return &I;
5003 if (isa<VectorType>(I.getType()))
5004 if (isa<ConstantAggregateZero>(Op1))
5005 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005006
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005007 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005008 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005009 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5010 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5011 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5012 if (Op0I->getOpcode() == Instruction::And ||
5013 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005014 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5015 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005016 Value *NotY =
5017 Builder->CreateNot(Op0I->getOperand(1),
5018 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005019 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005020 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005021 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005022 }
5023 }
5024 }
5025 }
5026
5027
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005028 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005029 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005030 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005031 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005032 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005033 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005034
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005035 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005036 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005037 FCI->getOperand(0), FCI->getOperand(1));
5038 }
5039
Nick Lewycky517e1f52008-05-31 19:01:33 +00005040 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5041 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5042 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5043 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5044 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005045 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5046 (RHS == ConstantExpr::getCast(Opcode,
5047 ConstantInt::getTrue(*Context),
5048 Op0C->getDestTy()))) {
5049 CI->setPredicate(CI->getInversePredicate());
5050 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005051 }
5052 }
5053 }
5054 }
5055
Reid Spencere4d87aa2006-12-23 06:05:41 +00005056 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005057 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005058 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5059 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005060 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5061 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005062 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005063 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005064 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005065
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005066 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005067 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005068 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005069 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005070 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005071 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005072 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005073 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005074 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005075 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005076 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005077 Constant *C = ConstantInt::get(*Context,
5078 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005079 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005080
Chris Lattner7c4049c2004-01-12 19:35:11 +00005081 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005082 } else if (Op0I->getOpcode() == Instruction::Or) {
5083 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005084 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005085 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005086 // Anything in both C1 and C2 is known to be zero, remove it from
5087 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005088 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5089 NewRHS = ConstantExpr::getAnd(NewRHS,
5090 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005091 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005092 I.setOperand(0, Op0I->getOperand(0));
5093 I.setOperand(1, NewRHS);
5094 return &I;
5095 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005096 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005097 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005098 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005099
5100 // Try to fold constant and into select arguments.
5101 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005102 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005103 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005104 if (isa<PHINode>(Op0))
5105 if (Instruction *NV = FoldOpIntoPhi(I))
5106 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005107 }
5108
Dan Gohman186a6362009-08-12 16:04:34 +00005109 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005110 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005111 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005112
Dan Gohman186a6362009-08-12 16:04:34 +00005113 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005114 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005115 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005116
Chris Lattner318bf792007-03-18 22:51:34 +00005117
5118 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5119 if (Op1I) {
5120 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005121 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005122 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005123 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005124 I.swapOperands();
5125 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005126 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005127 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005128 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005129 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005130 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005131 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005132 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005133 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005134 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005135 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005136 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005137 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005138 std::swap(A, B);
5139 }
Chris Lattner318bf792007-03-18 22:51:34 +00005140 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005141 I.swapOperands(); // Simplified below.
5142 std::swap(Op0, Op1);
5143 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005144 }
Chris Lattner318bf792007-03-18 22:51:34 +00005145 }
5146
5147 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5148 if (Op0I) {
5149 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005150 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005151 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005152 if (A == Op1) // (B|A)^B == (A|B)^B
5153 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005154 if (B == Op1) // (A|B)^B == A & ~B
5155 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005156 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005157 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005158 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005159 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005160 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005161 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005162 if (A == Op1) // (A&B)^A -> (B&A)^A
5163 std::swap(A, B);
5164 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005165 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005166 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005167 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005168 }
Chris Lattner318bf792007-03-18 22:51:34 +00005169 }
5170
5171 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5172 if (Op0I && Op1I && Op0I->isShift() &&
5173 Op0I->getOpcode() == Op1I->getOpcode() &&
5174 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5175 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005176 Value *NewOp =
5177 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5178 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005179 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005180 Op1I->getOperand(1));
5181 }
5182
5183 if (Op0I && Op1I) {
5184 Value *A, *B, *C, *D;
5185 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005186 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5187 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005188 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005189 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005190 }
5191 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005192 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5193 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005194 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005195 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005196 }
5197
5198 // (A & B)^(C & D)
5199 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005200 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5201 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005202 // (X & Y)^(X & Y) -> (Y^Z) & X
5203 Value *X = 0, *Y = 0, *Z = 0;
5204 if (A == C)
5205 X = A, Y = B, Z = D;
5206 else if (A == D)
5207 X = A, Y = B, Z = C;
5208 else if (B == C)
5209 X = B, Y = A, Z = D;
5210 else if (B == D)
5211 X = B, Y = A, Z = C;
5212
5213 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005214 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005215 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005216 }
5217 }
5218 }
5219
Reid Spencere4d87aa2006-12-23 06:05:41 +00005220 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5221 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005222 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005223 return R;
5224
Chris Lattner6fc205f2006-05-05 06:39:07 +00005225 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005226 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005227 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005228 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5229 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005230 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005231 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005232 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5233 I.getType(), TD) &&
5234 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5235 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005236 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5237 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005238 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005239 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005240 }
Chris Lattner99c65742007-10-24 05:38:08 +00005241 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005242
Chris Lattner7e708292002-06-25 16:13:24 +00005243 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005244}
5245
Owen Andersond672ecb2009-07-03 00:17:18 +00005246static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005247 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005248 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005249}
Chris Lattnera96879a2004-09-29 17:40:11 +00005250
Dan Gohman6de29f82009-06-15 22:12:54 +00005251static bool HasAddOverflow(ConstantInt *Result,
5252 ConstantInt *In1, ConstantInt *In2,
5253 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005254 if (IsSigned)
5255 if (In2->getValue().isNegative())
5256 return Result->getValue().sgt(In1->getValue());
5257 else
5258 return Result->getValue().slt(In1->getValue());
5259 else
5260 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005261}
5262
Dan Gohman6de29f82009-06-15 22:12:54 +00005263/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005264/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005265static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005266 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005267 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005268 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005269
Dan Gohman6de29f82009-06-15 22:12:54 +00005270 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5271 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005272 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005273 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5274 ExtractElement(In1, Idx, Context),
5275 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005276 IsSigned))
5277 return true;
5278 }
5279 return false;
5280 }
5281
5282 return HasAddOverflow(cast<ConstantInt>(Result),
5283 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5284 IsSigned);
5285}
5286
5287static bool HasSubOverflow(ConstantInt *Result,
5288 ConstantInt *In1, ConstantInt *In2,
5289 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005290 if (IsSigned)
5291 if (In2->getValue().isNegative())
5292 return Result->getValue().slt(In1->getValue());
5293 else
5294 return Result->getValue().sgt(In1->getValue());
5295 else
5296 return Result->getValue().ugt(In1->getValue());
5297}
5298
Dan Gohman6de29f82009-06-15 22:12:54 +00005299/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5300/// overflowed for this type.
5301static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005302 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005303 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005304 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005305
5306 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5307 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005308 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005309 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5310 ExtractElement(In1, Idx, Context),
5311 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005312 IsSigned))
5313 return true;
5314 }
5315 return false;
5316 }
5317
5318 return HasSubOverflow(cast<ConstantInt>(Result),
5319 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5320 IsSigned);
5321}
5322
Chris Lattner574da9b2005-01-13 20:14:25 +00005323/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5324/// code necessary to compute the offset from the base pointer (without adding
5325/// in the base pointer). Return the result as a signed integer of intptr size.
5326static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005327 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005328 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005329 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005330 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005331
5332 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005333 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005334 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005335
Gabor Greif177dd3f2008-06-12 21:37:33 +00005336 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5337 ++i, ++GTI) {
5338 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005339 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005340 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5341 if (OpC->isZero()) continue;
5342
5343 // Handle a struct index, which adds its field offset to the pointer.
5344 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5345 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5346
Chris Lattner74381062009-08-30 07:44:24 +00005347 Result = IC.Builder->CreateAdd(Result,
5348 ConstantInt::get(IntPtrTy, Size),
5349 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005350 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005351 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005352
Owen Andersoneed707b2009-07-24 23:12:02 +00005353 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005354 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005355 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5356 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005357 // Emit an add instruction.
5358 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005359 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005360 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005361 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005362 if (Op->getType() != IntPtrTy)
5363 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005364 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005365 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005366 // We'll let instcombine(mul) convert this to a shl if possible.
5367 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005368 }
5369
5370 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005371 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005372 }
5373 return Result;
5374}
5375
Chris Lattner10c0d912008-04-22 02:53:33 +00005376
Dan Gohman8f080f02009-07-17 22:16:21 +00005377/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5378/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5379/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5380/// be complex, and scales are involved. The above expression would also be
5381/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5382/// This later form is less amenable to optimization though, and we are allowed
5383/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005384///
5385/// If we can't emit an optimized form for this expression, this returns null.
5386///
5387static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5388 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005389 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005390 gep_type_iterator GTI = gep_type_begin(GEP);
5391
5392 // Check to see if this gep only has a single variable index. If so, and if
5393 // any constant indices are a multiple of its scale, then we can compute this
5394 // in terms of the scale of the variable index. For example, if the GEP
5395 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5396 // because the expression will cross zero at the same point.
5397 unsigned i, e = GEP->getNumOperands();
5398 int64_t Offset = 0;
5399 for (i = 1; i != e; ++i, ++GTI) {
5400 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5401 // Compute the aggregate offset of constant indices.
5402 if (CI->isZero()) continue;
5403
5404 // Handle a struct index, which adds its field offset to the pointer.
5405 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5406 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5407 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005408 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005409 Offset += Size*CI->getSExtValue();
5410 }
5411 } else {
5412 // Found our variable index.
5413 break;
5414 }
5415 }
5416
5417 // If there are no variable indices, we must have a constant offset, just
5418 // evaluate it the general way.
5419 if (i == e) return 0;
5420
5421 Value *VariableIdx = GEP->getOperand(i);
5422 // Determine the scale factor of the variable element. For example, this is
5423 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005424 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005425
5426 // Verify that there are no other variable indices. If so, emit the hard way.
5427 for (++i, ++GTI; i != e; ++i, ++GTI) {
5428 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5429 if (!CI) return 0;
5430
5431 // Compute the aggregate offset of constant indices.
5432 if (CI->isZero()) continue;
5433
5434 // Handle a struct index, which adds its field offset to the pointer.
5435 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5436 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5437 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005438 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005439 Offset += Size*CI->getSExtValue();
5440 }
5441 }
5442
5443 // Okay, we know we have a single variable index, which must be a
5444 // pointer/array/vector index. If there is no offset, life is simple, return
5445 // the index.
5446 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5447 if (Offset == 0) {
5448 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5449 // we don't need to bother extending: the extension won't affect where the
5450 // computation crosses zero.
5451 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005452 VariableIdx = new TruncInst(VariableIdx,
5453 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005454 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005455 return VariableIdx;
5456 }
5457
5458 // Otherwise, there is an index. The computation we will do will be modulo
5459 // the pointer size, so get it.
5460 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5461
5462 Offset &= PtrSizeMask;
5463 VariableScale &= PtrSizeMask;
5464
5465 // To do this transformation, any constant index must be a multiple of the
5466 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5467 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5468 // multiple of the variable scale.
5469 int64_t NewOffs = Offset / (int64_t)VariableScale;
5470 if (Offset != NewOffs*(int64_t)VariableScale)
5471 return 0;
5472
5473 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005474 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005475 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005476 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005477 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005478 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005479 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005480 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005481}
5482
5483
Reid Spencere4d87aa2006-12-23 06:05:41 +00005484/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005485/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005486Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005487 ICmpInst::Predicate Cond,
5488 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005489 // Look through bitcasts.
5490 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5491 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005492
Chris Lattner574da9b2005-01-13 20:14:25 +00005493 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005494 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005495 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005496 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005497 // know pointers can't overflow since the gep is inbounds. See if we can
5498 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005499 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5500
5501 // If not, synthesize the offset the hard way.
5502 if (Offset == 0)
5503 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005504 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005505 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005506 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005507 // If the base pointers are different, but the indices are the same, just
5508 // compare the base pointer.
5509 if (PtrBase != GEPRHS->getOperand(0)) {
5510 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005511 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005512 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005513 if (IndicesTheSame)
5514 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5515 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5516 IndicesTheSame = false;
5517 break;
5518 }
5519
5520 // If all indices are the same, just compare the base pointers.
5521 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005522 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005523 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005524
5525 // Otherwise, the base pointers are different and the indices are
5526 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005527 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005528 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005529
Chris Lattnere9d782b2005-01-13 22:25:21 +00005530 // If one of the GEPs has all zero indices, recurse.
5531 bool AllZeros = true;
5532 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5533 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5534 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5535 AllZeros = false;
5536 break;
5537 }
5538 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005539 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5540 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005541
5542 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005543 AllZeros = true;
5544 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5545 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5546 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5547 AllZeros = false;
5548 break;
5549 }
5550 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005551 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005552
Chris Lattner4401c9c2005-01-14 00:20:05 +00005553 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5554 // If the GEPs only differ by one index, compare it.
5555 unsigned NumDifferences = 0; // Keep track of # differences.
5556 unsigned DiffOperand = 0; // The operand that differs.
5557 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5558 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005559 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5560 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005561 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005562 NumDifferences = 2;
5563 break;
5564 } else {
5565 if (NumDifferences++) break;
5566 DiffOperand = i;
5567 }
5568 }
5569
5570 if (NumDifferences == 0) // SAME GEP?
5571 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005572 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005573 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005574
Chris Lattner4401c9c2005-01-14 00:20:05 +00005575 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005576 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5577 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005578 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005579 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005580 }
5581 }
5582
Reid Spencere4d87aa2006-12-23 06:05:41 +00005583 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005584 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005585 if (TD &&
5586 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005587 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5588 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5589 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5590 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005591 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005592 }
5593 }
5594 return 0;
5595}
5596
Chris Lattnera5406232008-05-19 20:18:56 +00005597/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5598///
5599Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5600 Instruction *LHSI,
5601 Constant *RHSC) {
5602 if (!isa<ConstantFP>(RHSC)) return 0;
5603 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5604
5605 // Get the width of the mantissa. We don't want to hack on conversions that
5606 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005607 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005608 if (MantissaWidth == -1) return 0; // Unknown.
5609
5610 // Check to see that the input is converted from an integer type that is small
5611 // enough that preserves all bits. TODO: check here for "known" sign bits.
5612 // 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 +00005613 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005614
5615 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005616 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5617 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005618 ++InputSize;
5619
5620 // If the conversion would lose info, don't hack on this.
5621 if ((int)InputSize > MantissaWidth)
5622 return 0;
5623
5624 // Otherwise, we can potentially simplify the comparison. We know that it
5625 // will always come through as an integer value and we know the constant is
5626 // not a NAN (it would have been previously simplified).
5627 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5628
5629 ICmpInst::Predicate Pred;
5630 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005631 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005632 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005633 case FCmpInst::FCMP_OEQ:
5634 Pred = ICmpInst::ICMP_EQ;
5635 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005636 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005637 case FCmpInst::FCMP_OGT:
5638 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5639 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005640 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005641 case FCmpInst::FCMP_OGE:
5642 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5643 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005644 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005645 case FCmpInst::FCMP_OLT:
5646 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5647 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005648 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005649 case FCmpInst::FCMP_OLE:
5650 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5651 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005652 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005653 case FCmpInst::FCMP_ONE:
5654 Pred = ICmpInst::ICMP_NE;
5655 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005656 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005657 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005658 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005659 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005660 }
5661
5662 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5663
5664 // Now we know that the APFloat is a normal number, zero or inf.
5665
Chris Lattner85162782008-05-20 03:50:52 +00005666 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005667 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005668 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005669
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005670 if (!LHSUnsigned) {
5671 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5672 // and large values.
5673 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5674 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5675 APFloat::rmNearestTiesToEven);
5676 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5677 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5678 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005679 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5680 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005681 }
5682 } else {
5683 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5684 // +INF and large values.
5685 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5686 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5687 APFloat::rmNearestTiesToEven);
5688 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5689 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5690 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005691 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5692 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005693 }
Chris Lattnera5406232008-05-19 20:18:56 +00005694 }
5695
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005696 if (!LHSUnsigned) {
5697 // See if the RHS value is < SignedMin.
5698 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5699 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5700 APFloat::rmNearestTiesToEven);
5701 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5702 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5703 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005704 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5705 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005706 }
Chris Lattnera5406232008-05-19 20:18:56 +00005707 }
5708
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005709 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5710 // [0, UMAX], but it may still be fractional. See if it is fractional by
5711 // casting the FP value to the integer value and back, checking for equality.
5712 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005713 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005714 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5715 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005716 if (!RHS.isZero()) {
5717 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005718 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5719 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005720 if (!Equal) {
5721 // If we had a comparison against a fractional value, we have to adjust
5722 // the compare predicate and sometimes the value. RHSC is rounded towards
5723 // zero at this point.
5724 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005725 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005726 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005727 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005728 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005729 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005730 case ICmpInst::ICMP_ULE:
5731 // (float)int <= 4.4 --> int <= 4
5732 // (float)int <= -4.4 --> false
5733 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005734 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005735 break;
5736 case ICmpInst::ICMP_SLE:
5737 // (float)int <= 4.4 --> int <= 4
5738 // (float)int <= -4.4 --> int < -4
5739 if (RHS.isNegative())
5740 Pred = ICmpInst::ICMP_SLT;
5741 break;
5742 case ICmpInst::ICMP_ULT:
5743 // (float)int < -4.4 --> false
5744 // (float)int < 4.4 --> int <= 4
5745 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005746 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005747 Pred = ICmpInst::ICMP_ULE;
5748 break;
5749 case ICmpInst::ICMP_SLT:
5750 // (float)int < -4.4 --> int < -4
5751 // (float)int < 4.4 --> int <= 4
5752 if (!RHS.isNegative())
5753 Pred = ICmpInst::ICMP_SLE;
5754 break;
5755 case ICmpInst::ICMP_UGT:
5756 // (float)int > 4.4 --> int > 4
5757 // (float)int > -4.4 --> true
5758 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005759 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005760 break;
5761 case ICmpInst::ICMP_SGT:
5762 // (float)int > 4.4 --> int > 4
5763 // (float)int > -4.4 --> int >= -4
5764 if (RHS.isNegative())
5765 Pred = ICmpInst::ICMP_SGE;
5766 break;
5767 case ICmpInst::ICMP_UGE:
5768 // (float)int >= -4.4 --> true
5769 // (float)int >= 4.4 --> int > 4
5770 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005771 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005772 Pred = ICmpInst::ICMP_UGT;
5773 break;
5774 case ICmpInst::ICMP_SGE:
5775 // (float)int >= -4.4 --> int >= -4
5776 // (float)int >= 4.4 --> int > 4
5777 if (!RHS.isNegative())
5778 Pred = ICmpInst::ICMP_SGT;
5779 break;
5780 }
Chris Lattnera5406232008-05-19 20:18:56 +00005781 }
5782 }
5783
5784 // Lower this FP comparison into an appropriate integer version of the
5785 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005786 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005787}
5788
Reid Spencere4d87aa2006-12-23 06:05:41 +00005789Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5790 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005791 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005792
Chris Lattner58e97462007-01-14 19:42:17 +00005793 // Fold trivial predicates.
5794 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005795 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005796 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005797 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005798
5799 // Simplify 'fcmp pred X, X'
5800 if (Op0 == Op1) {
5801 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005802 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005803 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5804 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5805 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson5defacc2009-07-31 17:39:07 +00005806 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005807 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5808 case FCmpInst::FCMP_OLT: // True if ordered and less than
5809 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson5defacc2009-07-31 17:39:07 +00005810 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005811
5812 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5813 case FCmpInst::FCMP_ULT: // True if unordered or less than
5814 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5815 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5816 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5817 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005818 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005819 return &I;
5820
5821 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5822 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5823 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5824 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5825 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5826 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005827 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005828 return &I;
5829 }
5830 }
5831
Reid Spencere4d87aa2006-12-23 06:05:41 +00005832 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005833 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Chris Lattnere87597f2004-10-16 18:11:37 +00005834
Reid Spencere4d87aa2006-12-23 06:05:41 +00005835 // Handle fcmp with constant RHS
5836 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005837 // If the constant is a nan, see if we can fold the comparison based on it.
5838 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5839 if (CFP->getValueAPF().isNaN()) {
5840 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005841 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005842 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5843 "Comparison must be either ordered or unordered!");
5844 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005845 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005846 }
5847 }
5848
Reid Spencere4d87aa2006-12-23 06:05:41 +00005849 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5850 switch (LHSI->getOpcode()) {
5851 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005852 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5853 // block. If in the same block, we're encouraging jump threading. If
5854 // not, we are just pessimizing the code by making an i1 phi.
5855 if (LHSI->getParent() == I.getParent())
5856 if (Instruction *NV = FoldOpIntoPhi(I))
5857 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005858 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005859 case Instruction::SIToFP:
5860 case Instruction::UIToFP:
5861 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5862 return NV;
5863 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005864 case Instruction::Select:
5865 // If either operand of the select is a constant, we can fold the
5866 // comparison into the select arms, which will cause one to be
5867 // constant folded and the select turned into a bitwise or.
5868 Value *Op1 = 0, *Op2 = 0;
5869 if (LHSI->hasOneUse()) {
5870 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5871 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005872 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005873 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005874 Op2 = Builder->CreateFCmp(I.getPredicate(),
5875 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005876 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5877 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005878 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005879 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005880 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5881 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005882 }
5883 }
5884
5885 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005886 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005887 break;
5888 }
5889 }
5890
5891 return Changed ? &I : 0;
5892}
5893
5894Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5895 bool Changed = SimplifyCompare(I);
5896 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5897 const Type *Ty = Op0->getType();
5898
5899 // icmp X, X
5900 if (Op0 == Op1)
Owen Anderson1d0be152009-08-13 21:58:54 +00005901 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005902 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005903
5904 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005905 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005906
Reid Spencere4d87aa2006-12-23 06:05:41 +00005907 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005908 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005909 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5910 isa<ConstantPointerNull>(Op0)) &&
5911 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005912 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00005913 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005914 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005915
Reid Spencere4d87aa2006-12-23 06:05:41 +00005916 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005917 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005918 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005919 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005920 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005921 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005922 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005923 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005924 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005925 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005926
Reid Spencere4d87aa2006-12-23 06:05:41 +00005927 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005928 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005929 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005930 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00005931 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005932 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005933 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005934 case ICmpInst::ICMP_SGT:
5935 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005936 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005937 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00005938 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005939 return BinaryOperator::CreateAnd(Not, Op0);
5940 }
5941 case ICmpInst::ICMP_UGE:
5942 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5943 // FALL THROUGH
5944 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00005945 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005946 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005947 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005948 case ICmpInst::ICMP_SGE:
5949 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5950 // FALL THROUGH
5951 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00005952 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005953 return BinaryOperator::CreateOr(Not, Op0);
5954 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005955 }
Chris Lattner8b170942002-08-09 23:47:40 +00005956 }
5957
Dan Gohman1c8491e2009-04-25 17:12:48 +00005958 unsigned BitWidth = 0;
5959 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00005960 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5961 else if (Ty->isIntOrIntVector())
5962 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00005963
5964 bool isSignBit = false;
5965
Dan Gohman81b28ce2008-09-16 18:46:06 +00005966 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005967 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005968 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005969
Chris Lattnerb6566012008-01-05 01:18:20 +00005970 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5971 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005972 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00005973 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005974 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005975 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005976
Dan Gohman81b28ce2008-09-16 18:46:06 +00005977 // If we have an icmp le or icmp ge instruction, turn it into the
5978 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5979 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005980 switch (I.getPredicate()) {
5981 default: break;
5982 case ICmpInst::ICMP_ULE:
5983 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005984 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005985 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005986 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005987 case ICmpInst::ICMP_SLE:
5988 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005989 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005990 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005991 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005992 case ICmpInst::ICMP_UGE:
5993 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005994 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005995 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005996 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005997 case ICmpInst::ICMP_SGE:
5998 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005999 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006000 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006001 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006002 }
6003
Chris Lattner183661e2008-07-11 05:40:05 +00006004 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006005 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006006 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006007 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6008 }
6009
6010 // See if we can fold the comparison based on range information we can get
6011 // by checking whether bits are known to be zero or one in the input.
6012 if (BitWidth != 0) {
6013 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6014 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6015
6016 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006017 isSignBit ? APInt::getSignBit(BitWidth)
6018 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006019 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006020 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006021 if (SimplifyDemandedBits(I.getOperandUse(1),
6022 APInt::getAllOnesValue(BitWidth),
6023 Op1KnownZero, Op1KnownOne, 0))
6024 return &I;
6025
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006026 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006027 // in. Compute the Min, Max and RHS values based on the known bits. For the
6028 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006029 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6030 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6031 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6032 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6033 Op0Min, Op0Max);
6034 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6035 Op1Min, Op1Max);
6036 } else {
6037 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6038 Op0Min, Op0Max);
6039 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6040 Op1Min, Op1Max);
6041 }
6042
Chris Lattner183661e2008-07-11 05:40:05 +00006043 // If Min and Max are known to be the same, then SimplifyDemandedBits
6044 // figured out that the LHS is a constant. Just constant fold this now so
6045 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006046 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006047 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006048 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006049 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006050 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006051 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006052
Chris Lattner183661e2008-07-11 05:40:05 +00006053 // Based on the range information we know about the LHS, see if we can
6054 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006055 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006056 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006057 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006058 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006059 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006060 break;
6061 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006062 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006063 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006064 break;
6065 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006066 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006067 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006068 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006069 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006070 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006071 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006072 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6073 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006074 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006075 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006076
6077 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6078 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006079 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006080 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006081 }
Chris Lattner84dff672008-07-11 05:08:55 +00006082 break;
6083 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006084 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006085 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006086 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006087 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006088
6089 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006090 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006091 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6092 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006093 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006094 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006095
6096 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6097 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006098 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006099 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006100 }
Chris Lattner84dff672008-07-11 05:08:55 +00006101 break;
6102 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006103 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006104 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006105 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006106 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006107 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006108 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006109 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6110 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006111 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006112 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006113 }
Chris Lattner84dff672008-07-11 05:08:55 +00006114 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006115 case ICmpInst::ICMP_SGT:
6116 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006117 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006118 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006119 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006120
6121 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006122 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006123 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6124 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006125 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006126 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006127 }
6128 break;
6129 case ICmpInst::ICMP_SGE:
6130 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6131 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006132 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006133 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006134 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006135 break;
6136 case ICmpInst::ICMP_SLE:
6137 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6138 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006139 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006140 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006141 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006142 break;
6143 case ICmpInst::ICMP_UGE:
6144 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6145 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006146 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006147 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006148 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006149 break;
6150 case ICmpInst::ICMP_ULE:
6151 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6152 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006153 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006154 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006155 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006156 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006157 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006158
6159 // Turn a signed comparison into an unsigned one if both operands
6160 // are known to have the same sign.
6161 if (I.isSignedPredicate() &&
6162 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6163 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006164 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006165 }
6166
6167 // Test if the ICmpInst instruction is used exclusively by a select as
6168 // part of a minimum or maximum operation. If so, refrain from doing
6169 // any other folding. This helps out other analyses which understand
6170 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6171 // and CodeGen. And in this case, at least one of the comparison
6172 // operands has at least one user besides the compare (the select),
6173 // which would often largely negate the benefit of folding anyway.
6174 if (I.hasOneUse())
6175 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6176 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6177 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6178 return 0;
6179
6180 // See if we are doing a comparison between a constant and an instruction that
6181 // can be folded into the comparison.
6182 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006183 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006184 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006185 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006186 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006187 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6188 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006189 }
6190
Chris Lattner01deb9d2007-04-03 17:43:25 +00006191 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006192 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6193 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6194 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006195 case Instruction::GetElementPtr:
6196 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006197 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006198 bool isAllZeros = true;
6199 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6200 if (!isa<Constant>(LHSI->getOperand(i)) ||
6201 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6202 isAllZeros = false;
6203 break;
6204 }
6205 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006206 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006207 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006208 }
6209 break;
6210
Chris Lattner6970b662005-04-23 15:31:55 +00006211 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006212 // Only fold icmp into the PHI if the phi and fcmp are in the same
6213 // block. If in the same block, we're encouraging jump threading. If
6214 // not, we are just pessimizing the code by making an i1 phi.
6215 if (LHSI->getParent() == I.getParent())
6216 if (Instruction *NV = FoldOpIntoPhi(I))
6217 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006218 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006219 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006220 // If either operand of the select is a constant, we can fold the
6221 // comparison into the select arms, which will cause one to be
6222 // constant folded and the select turned into a bitwise or.
6223 Value *Op1 = 0, *Op2 = 0;
6224 if (LHSI->hasOneUse()) {
6225 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6226 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006227 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006228 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006229 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6230 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006231 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6232 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006233 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006234 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006235 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6236 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006237 }
6238 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006239
Chris Lattner6970b662005-04-23 15:31:55 +00006240 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006241 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006242 break;
6243 }
Chris Lattner4802d902007-04-06 18:57:34 +00006244 case Instruction::Malloc:
6245 // If we have (malloc != null), and if the malloc has a single use, we
6246 // can assume it is successful and remove the malloc.
6247 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006248 Worklist.Add(LHSI);
Owen Anderson1d0be152009-08-13 21:58:54 +00006249 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006250 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006251 }
6252 break;
6253 }
Chris Lattner6970b662005-04-23 15:31:55 +00006254 }
6255
Reid Spencere4d87aa2006-12-23 06:05:41 +00006256 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006257 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006258 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006259 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006260 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006261 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6262 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006263 return NI;
6264
Reid Spencere4d87aa2006-12-23 06:05:41 +00006265 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006266 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6267 // now.
6268 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6269 if (isa<PointerType>(Op0->getType()) &&
6270 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006271 // We keep moving the cast from the left operand over to the right
6272 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006273 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006274
Chris Lattner57d86372007-01-06 01:45:59 +00006275 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6276 // so eliminate it as well.
6277 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6278 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006279
Chris Lattnerde90b762003-11-03 04:25:02 +00006280 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006281 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006282 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006283 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006284 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006285 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006286 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006287 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006288 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006289 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006290 }
Chris Lattner57d86372007-01-06 01:45:59 +00006291 }
6292
6293 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006294 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006295 // This comes up when you have code like
6296 // int X = A < B;
6297 // if (X) ...
6298 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006299 // with a constant or another cast from the same type.
6300 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006301 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006302 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006303 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006304
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006305 // See if it's the same type of instruction on the left and right.
6306 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6307 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006308 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006309 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006310 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006311 default: break;
6312 case Instruction::Add:
6313 case Instruction::Sub:
6314 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006315 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006316 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006317 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006318 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6319 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6320 if (CI->getValue().isSignBit()) {
6321 ICmpInst::Predicate Pred = I.isSignedPredicate()
6322 ? I.getUnsignedPredicate()
6323 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006324 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006325 Op1I->getOperand(0));
6326 }
6327
6328 if (CI->getValue().isMaxSignedValue()) {
6329 ICmpInst::Predicate Pred = I.isSignedPredicate()
6330 ? I.getUnsignedPredicate()
6331 : I.getSignedPredicate();
6332 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006333 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006334 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006335 }
6336 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006337 break;
6338 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006339 if (!I.isEquality())
6340 break;
6341
Nick Lewycky5d52c452008-08-21 05:56:10 +00006342 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6343 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6344 // Mask = -1 >> count-trailing-zeros(Cst).
6345 if (!CI->isZero() && !CI->isOne()) {
6346 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006347 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006348 APInt::getLowBitsSet(AP.getBitWidth(),
6349 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006350 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006351 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6352 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006353 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006354 }
6355 }
6356 break;
6357 }
6358 }
6359 }
6360 }
6361
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006362 // ~x < ~y --> y < x
6363 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006364 if (match(Op0, m_Not(m_Value(A))) &&
6365 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006366 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006367 }
6368
Chris Lattner65b72ba2006-09-18 04:22:48 +00006369 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006370 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006371
6372 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006373 if (match(Op0, m_Neg(m_Value(A))) &&
6374 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006375 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006376
Dan Gohman4ae51262009-08-12 16:23:25 +00006377 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006378 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6379 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006380 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006381 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006382 }
6383
Dan Gohman4ae51262009-08-12 16:23:25 +00006384 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006385 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006386 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006387 if (match(B, m_ConstantInt(C1)) &&
6388 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006389 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006390 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006391 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6392 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006393 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006394
6395 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006396 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6397 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6398 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6399 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006400 }
6401 }
6402
Dan Gohman4ae51262009-08-12 16:23:25 +00006403 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006404 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006405 // A == (A^B) -> B == 0
6406 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006407 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006408 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006409 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006410
6411 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006412 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006413 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006414 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006415
6416 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006417 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006418 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006419 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006420
Chris Lattner9c2328e2006-11-14 06:06:06 +00006421 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6422 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006423 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6424 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006425 Value *X = 0, *Y = 0, *Z = 0;
6426
6427 if (A == C) {
6428 X = B; Y = D; Z = A;
6429 } else if (A == D) {
6430 X = B; Y = C; Z = A;
6431 } else if (B == C) {
6432 X = A; Y = D; Z = B;
6433 } else if (B == D) {
6434 X = A; Y = C; Z = B;
6435 }
6436
6437 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006438 Op1 = Builder->CreateXor(X, Y, "tmp");
6439 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006440 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006441 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006442 return &I;
6443 }
6444 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006445 }
Chris Lattner7e708292002-06-25 16:13:24 +00006446 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006447}
6448
Chris Lattner562ef782007-06-20 23:46:26 +00006449
6450/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6451/// and CmpRHS are both known to be integer constants.
6452Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6453 ConstantInt *DivRHS) {
6454 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6455 const APInt &CmpRHSV = CmpRHS->getValue();
6456
6457 // FIXME: If the operand types don't match the type of the divide
6458 // then don't attempt this transform. The code below doesn't have the
6459 // logic to deal with a signed divide and an unsigned compare (and
6460 // vice versa). This is because (x /s C1) <s C2 produces different
6461 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6462 // (x /u C1) <u C2. Simply casting the operands and result won't
6463 // work. :( The if statement below tests that condition and bails
6464 // if it finds it.
6465 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6466 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6467 return 0;
6468 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006469 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006470 if (DivIsSigned && DivRHS->isAllOnesValue())
6471 return 0; // The overflow computation also screws up here
6472 if (DivRHS->isOne())
6473 return 0; // Not worth bothering, and eliminates some funny cases
6474 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006475
6476 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6477 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6478 // C2 (CI). By solving for X we can turn this into a range check
6479 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006480 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006481
6482 // Determine if the product overflows by seeing if the product is
6483 // not equal to the divide. Make sure we do the same kind of divide
6484 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006485 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6486 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006487
6488 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006489 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006490
Chris Lattner1dbfd482007-06-21 18:11:19 +00006491 // Figure out the interval that is being checked. For example, a comparison
6492 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6493 // Compute this interval based on the constants involved and the signedness of
6494 // the compare/divide. This computes a half-open interval, keeping track of
6495 // whether either value in the interval overflows. After analysis each
6496 // overflow variable is set to 0 if it's corresponding bound variable is valid
6497 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6498 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006499 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006500
Chris Lattner562ef782007-06-20 23:46:26 +00006501 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006502 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006503 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006504 HiOverflow = LoOverflow = ProdOV;
6505 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006506 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006507 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006508 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006509 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006510 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006511 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006512 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006513 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6514 HiOverflow = LoOverflow = ProdOV;
6515 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006516 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006517 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006518 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006519 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006520 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6521 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006522 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006523 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006524 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006525 true) ? -1 : 0;
6526 }
Chris Lattner562ef782007-06-20 23:46:26 +00006527 }
Dan Gohman76491272008-02-13 22:09:18 +00006528 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006529 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006530 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006531 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006532 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006533 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6534 HiOverflow = 1; // [INTMIN+1, overflow)
6535 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6536 }
Dan Gohman76491272008-02-13 22:09:18 +00006537 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006538 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006539 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006540 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006541 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006542 LoOverflow = AddWithOverflow(LoBound, HiBound,
6543 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006544 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006545 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6546 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006547 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006548 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006549 }
6550
Chris Lattner1dbfd482007-06-21 18:11:19 +00006551 // Dividing by a negative swaps the condition. LT <-> GT
6552 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006553 }
6554
6555 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006556 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006557 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006558 case ICmpInst::ICMP_EQ:
6559 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006560 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006561 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006562 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006563 ICmpInst::ICMP_UGE, X, LoBound);
6564 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006565 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006566 ICmpInst::ICMP_ULT, X, HiBound);
6567 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006568 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006569 case ICmpInst::ICMP_NE:
6570 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006571 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006572 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006573 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006574 ICmpInst::ICMP_ULT, X, LoBound);
6575 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006576 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006577 ICmpInst::ICMP_UGE, X, HiBound);
6578 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006579 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006580 case ICmpInst::ICMP_ULT:
6581 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006582 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006583 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006584 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006585 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006586 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006587 case ICmpInst::ICMP_UGT:
6588 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006589 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006590 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006591 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006592 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006593 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006594 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006595 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006596 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006597 }
6598}
6599
6600
Chris Lattner01deb9d2007-04-03 17:43:25 +00006601/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6602///
6603Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6604 Instruction *LHSI,
6605 ConstantInt *RHS) {
6606 const APInt &RHSV = RHS->getValue();
6607
6608 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006609 case Instruction::Trunc:
6610 if (ICI.isEquality() && LHSI->hasOneUse()) {
6611 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6612 // of the high bits truncated out of x are known.
6613 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6614 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6615 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6616 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6617 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6618
6619 // If all the high bits are known, we can do this xform.
6620 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6621 // Pull in the high bits from known-ones set.
6622 APInt NewRHS(RHS->getValue());
6623 NewRHS.zext(SrcBits);
6624 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006625 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006626 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006627 }
6628 }
6629 break;
6630
Duncan Sands0091bf22007-04-04 06:42:45 +00006631 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006632 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6633 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6634 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006635 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6636 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006637 Value *CompareVal = LHSI->getOperand(0);
6638
6639 // If the sign bit of the XorCST is not set, there is no change to
6640 // the operation, just stop using the Xor.
6641 if (!XorCST->getValue().isNegative()) {
6642 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006643 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006644 return &ICI;
6645 }
6646
6647 // Was the old condition true if the operand is positive?
6648 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6649
6650 // If so, the new one isn't.
6651 isTrueIfPositive ^= true;
6652
6653 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006654 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006655 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006656 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006657 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006658 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006659 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006660
6661 if (LHSI->hasOneUse()) {
6662 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6663 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6664 const APInt &SignBit = XorCST->getValue();
6665 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6666 ? ICI.getUnsignedPredicate()
6667 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006668 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006669 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006670 }
6671
6672 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006673 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006674 const APInt &NotSignBit = XorCST->getValue();
6675 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6676 ? ICI.getUnsignedPredicate()
6677 : ICI.getSignedPredicate();
6678 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006679 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006680 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006681 }
6682 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006683 }
6684 break;
6685 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6686 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6687 LHSI->getOperand(0)->hasOneUse()) {
6688 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6689
6690 // If the LHS is an AND of a truncating cast, we can widen the
6691 // and/compare to be the input width without changing the value
6692 // produced, eliminating a cast.
6693 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6694 // We can do this transformation if either the AND constant does not
6695 // have its sign bit set or if it is an equality comparison.
6696 // Extending a relational comparison when we're checking the sign
6697 // bit would not work.
6698 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006699 (ICI.isEquality() ||
6700 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006701 uint32_t BitWidth =
6702 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6703 APInt NewCST = AndCST->getValue();
6704 NewCST.zext(BitWidth);
6705 APInt NewCI = RHSV;
6706 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006707 Value *NewAnd =
6708 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006709 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006710 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006711 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006712 }
6713 }
6714
6715 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6716 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6717 // happens a LOT in code produced by the C front-end, for bitfield
6718 // access.
6719 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6720 if (Shift && !Shift->isShift())
6721 Shift = 0;
6722
6723 ConstantInt *ShAmt;
6724 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6725 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6726 const Type *AndTy = AndCST->getType(); // Type of the and.
6727
6728 // We can fold this as long as we can't shift unknown bits
6729 // into the mask. This can only happen with signed shift
6730 // rights, as they sign-extend.
6731 if (ShAmt) {
6732 bool CanFold = Shift->isLogicalShift();
6733 if (!CanFold) {
6734 // To test for the bad case of the signed shr, see if any
6735 // of the bits shifted in could be tested after the mask.
6736 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6737 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6738
6739 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6740 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6741 AndCST->getValue()) == 0)
6742 CanFold = true;
6743 }
6744
6745 if (CanFold) {
6746 Constant *NewCst;
6747 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006748 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006749 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006750 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006751
6752 // Check to see if we are shifting out any of the bits being
6753 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006754 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006755 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006756 // If we shifted bits out, the fold is not going to work out.
6757 // As a special case, check to see if this means that the
6758 // result is always true or false now.
6759 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006760 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006761 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006762 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006763 } else {
6764 ICI.setOperand(1, NewCst);
6765 Constant *NewAndCST;
6766 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006767 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006768 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006769 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006770 LHSI->setOperand(1, NewAndCST);
6771 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006772 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006773 return &ICI;
6774 }
6775 }
6776 }
6777
6778 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6779 // preferable because it allows the C<<Y expression to be hoisted out
6780 // of a loop if Y is invariant and X is not.
6781 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006782 ICI.isEquality() && !Shift->isArithmeticShift() &&
6783 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006784 // Compute C << Y.
6785 Value *NS;
6786 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006787 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006788 } else {
6789 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006790 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006791 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006792
6793 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006794 Value *NewAnd =
6795 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006796
6797 ICI.setOperand(0, NewAnd);
6798 return &ICI;
6799 }
6800 }
6801 break;
6802
Chris Lattnera0141b92007-07-15 20:42:37 +00006803 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6804 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6805 if (!ShAmt) break;
6806
6807 uint32_t TypeBits = RHSV.getBitWidth();
6808
6809 // Check that the shift amount is in range. If not, don't perform
6810 // undefined shifts. When the shift is visited it will be
6811 // simplified.
6812 if (ShAmt->uge(TypeBits))
6813 break;
6814
6815 if (ICI.isEquality()) {
6816 // If we are comparing against bits always shifted out, the
6817 // comparison cannot succeed.
6818 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006819 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006820 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006821 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6822 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006823 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006824 return ReplaceInstUsesWith(ICI, Cst);
6825 }
6826
6827 if (LHSI->hasOneUse()) {
6828 // Otherwise strength reduce the shift into an and.
6829 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6830 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006831 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006832 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006833
Chris Lattner74381062009-08-30 07:44:24 +00006834 Value *And =
6835 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006836 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006837 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006838 }
6839 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006840
6841 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6842 bool TrueIfSigned = false;
6843 if (LHSI->hasOneUse() &&
6844 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6845 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006846 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006847 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006848 Value *And =
6849 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006850 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006851 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006852 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006853 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006854 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006855
6856 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006857 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006858 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006859 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006860 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006861
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006862 // Check that the shift amount is in range. If not, don't perform
6863 // undefined shifts. When the shift is visited it will be
6864 // simplified.
6865 uint32_t TypeBits = RHSV.getBitWidth();
6866 if (ShAmt->uge(TypeBits))
6867 break;
6868
6869 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006870
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006871 // If we are comparing against bits always shifted out, the
6872 // comparison cannot succeed.
6873 APInt Comp = RHSV << ShAmtVal;
6874 if (LHSI->getOpcode() == Instruction::LShr)
6875 Comp = Comp.lshr(ShAmtVal);
6876 else
6877 Comp = Comp.ashr(ShAmtVal);
6878
6879 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6880 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006881 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006882 return ReplaceInstUsesWith(ICI, Cst);
6883 }
6884
6885 // Otherwise, check to see if the bits shifted out are known to be zero.
6886 // If so, we can compare against the unshifted value:
6887 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006888 if (LHSI->hasOneUse() &&
6889 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006890 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006891 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006892 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006893 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006894
Evan Chengf30752c2008-04-23 00:38:06 +00006895 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006896 // Otherwise strength reduce the shift into an and.
6897 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006898 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006899
Chris Lattner74381062009-08-30 07:44:24 +00006900 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6901 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006902 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006903 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006904 }
6905 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006906 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006907
6908 case Instruction::SDiv:
6909 case Instruction::UDiv:
6910 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6911 // Fold this div into the comparison, producing a range check.
6912 // Determine, based on the divide type, what the range is being
6913 // checked. If there is an overflow on the low or high side, remember
6914 // it, otherwise compute the range [low, hi) bounding the new value.
6915 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006916 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6917 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6918 DivRHS))
6919 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006920 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006921
6922 case Instruction::Add:
6923 // Fold: icmp pred (add, X, C1), C2
6924
6925 if (!ICI.isEquality()) {
6926 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6927 if (!LHSC) break;
6928 const APInt &LHSV = LHSC->getValue();
6929
6930 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6931 .subtract(LHSV);
6932
6933 if (ICI.isSignedPredicate()) {
6934 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006935 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006936 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006937 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006938 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006939 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006940 }
6941 } else {
6942 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006943 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006944 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006945 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006946 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006947 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006948 }
6949 }
6950 }
6951 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006952 }
6953
6954 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6955 if (ICI.isEquality()) {
6956 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6957
6958 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6959 // the second operand is a constant, simplify a bit.
6960 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6961 switch (BO->getOpcode()) {
6962 case Instruction::SRem:
6963 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6964 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6965 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6966 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00006967 Value *NewRem =
6968 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6969 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006970 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00006971 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006972 }
6973 }
6974 break;
6975 case Instruction::Add:
6976 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6977 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6978 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006979 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006980 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006981 } else if (RHSV == 0) {
6982 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6983 // efficiently invertible, or if the add has just this one use.
6984 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6985
Dan Gohman186a6362009-08-12 16:04:34 +00006986 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006987 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00006988 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006989 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006990 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00006991 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006992 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006993 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006994 }
6995 }
6996 break;
6997 case Instruction::Xor:
6998 // For the xor case, we can xor two constants together, eliminating
6999 // the explicit xor.
7000 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007001 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007002 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007003
7004 // FALLTHROUGH
7005 case Instruction::Sub:
7006 // Replace (([sub|xor] A, B) != 0) with (A != B)
7007 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007008 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007009 BO->getOperand(1));
7010 break;
7011
7012 case Instruction::Or:
7013 // If bits are being or'd in that are not present in the constant we
7014 // are comparing against, then the comparison could never succeed!
7015 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007016 Constant *NotCI = ConstantExpr::getNot(RHS);
7017 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007018 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007019 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007020 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007021 }
7022 break;
7023
7024 case Instruction::And:
7025 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7026 // If bits are being compared against that are and'd out, then the
7027 // comparison can never succeed!
7028 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007029 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007030 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007031 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007032
7033 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7034 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007035 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007036 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007037 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007038
7039 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007040 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007041 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007042 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007043 ICmpInst::Predicate pred = isICMP_NE ?
7044 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007045 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007046 }
7047
7048 // ((X & ~7) == 0) --> X < 8
7049 if (RHSV == 0 && isHighOnes(BOC)) {
7050 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007051 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007052 ICmpInst::Predicate pred = isICMP_NE ?
7053 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007054 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007055 }
7056 }
7057 default: break;
7058 }
7059 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7060 // Handle icmp {eq|ne} <intrinsic>, intcst.
7061 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007062 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007063 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007064 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007065 return &ICI;
7066 }
7067 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007068 }
7069 return 0;
7070}
7071
7072/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7073/// We only handle extending casts so far.
7074///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007075Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7076 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007077 Value *LHSCIOp = LHSCI->getOperand(0);
7078 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007079 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007080 Value *RHSCIOp;
7081
Chris Lattner8c756c12007-05-05 22:41:33 +00007082 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7083 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007084 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7085 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007086 cast<IntegerType>(DestTy)->getBitWidth()) {
7087 Value *RHSOp = 0;
7088 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007089 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007090 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7091 RHSOp = RHSC->getOperand(0);
7092 // If the pointer types don't match, insert a bitcast.
7093 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007094 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007095 }
7096
7097 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007098 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007099 }
7100
7101 // The code below only handles extension cast instructions, so far.
7102 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007103 if (LHSCI->getOpcode() != Instruction::ZExt &&
7104 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007105 return 0;
7106
Reid Spencere4d87aa2006-12-23 06:05:41 +00007107 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7108 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007109
Reid Spencere4d87aa2006-12-23 06:05:41 +00007110 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007111 // Not an extension from the same type?
7112 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007113 if (RHSCIOp->getType() != LHSCIOp->getType())
7114 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007115
Nick Lewycky4189a532008-01-28 03:48:02 +00007116 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007117 // and the other is a zext), then we can't handle this.
7118 if (CI->getOpcode() != LHSCI->getOpcode())
7119 return 0;
7120
Nick Lewycky4189a532008-01-28 03:48:02 +00007121 // Deal with equality cases early.
7122 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007123 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007124
7125 // A signed comparison of sign extended values simplifies into a
7126 // signed comparison.
7127 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007128 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007129
7130 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007131 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007132 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007133
Reid Spencere4d87aa2006-12-23 06:05:41 +00007134 // If we aren't dealing with a constant on the RHS, exit early
7135 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7136 if (!CI)
7137 return 0;
7138
7139 // Compute the constant that would happen if we truncated to SrcTy then
7140 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007141 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7142 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007143 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007144
7145 // If the re-extended constant didn't change...
7146 if (Res2 == CI) {
7147 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7148 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007149 // %A = sext i16 %X to i32
7150 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007151 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007152 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007153 // because %A may have negative value.
7154 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007155 // However, we allow this when the compare is EQ/NE, because they are
7156 // signless.
7157 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007158 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007159 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007160 }
7161
7162 // The re-extended constant changed so the constant cannot be represented
7163 // in the shorter type. Consequently, we cannot emit a simple comparison.
7164
7165 // First, handle some easy cases. We know the result cannot be equal at this
7166 // point so handle the ICI.isEquality() cases
7167 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007168 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007169 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007170 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007171
7172 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7173 // should have been folded away previously and not enter in here.
7174 Value *Result;
7175 if (isSignedCmp) {
7176 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007177 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007178 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007179 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007180 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007181 } else {
7182 // We're performing an unsigned comparison.
7183 if (isSignedExt) {
7184 // We're performing an unsigned comp with a sign extended value.
7185 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007186 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007187 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007188 } else {
7189 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007190 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007191 }
7192 }
7193
7194 // Finally, return the value computed.
7195 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007196 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007197 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007198
7199 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7200 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7201 "ICmp should be folded!");
7202 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007203 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007204 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007205}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007206
Reid Spencer832254e2007-02-02 02:16:23 +00007207Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7208 return commonShiftTransforms(I);
7209}
7210
7211Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7212 return commonShiftTransforms(I);
7213}
7214
7215Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007216 if (Instruction *R = commonShiftTransforms(I))
7217 return R;
7218
7219 Value *Op0 = I.getOperand(0);
7220
7221 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7222 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7223 if (CSI->isAllOnesValue())
7224 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007225
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007226 // See if we can turn a signed shr into an unsigned shr.
7227 if (MaskedValueIsZero(Op0,
7228 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7229 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7230
7231 // Arithmetic shifting an all-sign-bit value is a no-op.
7232 unsigned NumSignBits = ComputeNumSignBits(Op0);
7233 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7234 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007235
Chris Lattner348f6652007-12-06 01:59:46 +00007236 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007237}
7238
7239Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7240 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007241 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007242
7243 // shl X, 0 == X and shr X, 0 == X
7244 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007245 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7246 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007247 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007248
Reid Spencere4d87aa2006-12-23 06:05:41 +00007249 if (isa<UndefValue>(Op0)) {
7250 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007251 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007252 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007253 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007254 }
7255 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007256 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7257 return ReplaceInstUsesWith(I, Op0);
7258 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007259 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007260 }
7261
Dan Gohman9004c8a2009-05-21 02:28:33 +00007262 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007263 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007264 return &I;
7265
Chris Lattner2eefe512004-04-09 19:05:30 +00007266 // Try to fold constant and into select arguments.
7267 if (isa<Constant>(Op0))
7268 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007269 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007270 return R;
7271
Reid Spencerb83eb642006-10-20 07:07:24 +00007272 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007273 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7274 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007275 return 0;
7276}
7277
Reid Spencerb83eb642006-10-20 07:07:24 +00007278Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007279 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007280 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007281
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007282 // See if we can simplify any instructions used by the instruction whose sole
7283 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007284 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007285
Dan Gohmana119de82009-06-14 23:30:43 +00007286 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7287 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007288 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007289 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007290 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007291 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007292 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007293 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007294 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007295 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007296 }
7297
7298 // ((X*C1) << C2) == (X * (C1 << C2))
7299 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7300 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7301 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007302 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007303 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007304
7305 // Try to fold constant and into select arguments.
7306 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7307 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7308 return R;
7309 if (isa<PHINode>(Op0))
7310 if (Instruction *NV = FoldOpIntoPhi(I))
7311 return NV;
7312
Chris Lattner8999dd32007-12-22 09:07:47 +00007313 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7314 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7315 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7316 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7317 // place. Don't try to do this transformation in this case. Also, we
7318 // require that the input operand is a shift-by-constant so that we have
7319 // confidence that the shifts will get folded together. We could do this
7320 // xform in more cases, but it is unlikely to be profitable.
7321 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7322 isa<ConstantInt>(TrOp->getOperand(1))) {
7323 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007324 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007325 // (shift2 (shift1 & 0x00FF), c2)
7326 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007327
7328 // For logical shifts, the truncation has the effect of making the high
7329 // part of the register be zeros. Emulate this by inserting an AND to
7330 // clear the top bits as needed. This 'and' will usually be zapped by
7331 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007332 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7333 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007334 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7335
7336 // The mask we constructed says what the trunc would do if occurring
7337 // between the shifts. We want to know the effect *after* the second
7338 // shift. We know that it is a logical shift by a constant, so adjust the
7339 // mask as appropriate.
7340 if (I.getOpcode() == Instruction::Shl)
7341 MaskV <<= Op1->getZExtValue();
7342 else {
7343 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7344 MaskV = MaskV.lshr(Op1->getZExtValue());
7345 }
7346
Chris Lattner74381062009-08-30 07:44:24 +00007347 // shift1 & 0x00FF
7348 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7349 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007350
7351 // Return the value truncated to the interesting size.
7352 return new TruncInst(And, I.getType());
7353 }
7354 }
7355
Chris Lattner4d5542c2006-01-06 07:12:35 +00007356 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007357 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7358 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7359 Value *V1, *V2;
7360 ConstantInt *CC;
7361 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007362 default: break;
7363 case Instruction::Add:
7364 case Instruction::And:
7365 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007366 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007367 // These operators commute.
7368 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007369 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007370 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007371 m_Specific(Op1)))) {
7372 Value *YS = // (Y << C)
7373 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7374 // (X + (Y << C))
7375 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7376 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007377 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007378 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007379 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007380 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007381
Chris Lattner150f12a2005-09-18 06:30:59 +00007382 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007383 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007384 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007385 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007386 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007387 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007388 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007389 Value *YS = // (Y << C)
7390 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7391 Op0BO->getName());
7392 // X & (CC << C)
7393 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7394 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007395 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007396 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007397 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007398
Reid Spencera07cb7d2007-02-02 14:41:37 +00007399 // FALL THROUGH.
7400 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007401 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007402 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007403 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007404 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007405 Value *YS = // (Y << C)
7406 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7407 // (X + (Y << C))
7408 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7409 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007410 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007411 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007412 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007413 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007414
Chris Lattner13d4ab42006-05-31 21:14:00 +00007415 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007416 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7417 match(Op0BO->getOperand(0),
7418 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007419 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007420 cast<BinaryOperator>(Op0BO->getOperand(0))
7421 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007422 Value *YS = // (Y << C)
7423 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7424 // X & (CC << C)
7425 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7426 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007427
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007428 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007429 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007430
Chris Lattner11021cb2005-09-18 05:12:10 +00007431 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007432 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007433 }
7434
7435
7436 // If the operand is an bitwise operator with a constant RHS, and the
7437 // shift is the only use, we can pull it out of the shift.
7438 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7439 bool isValid = true; // Valid only for And, Or, Xor
7440 bool highBitSet = false; // Transform if high bit of constant set?
7441
7442 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007443 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007444 case Instruction::Add:
7445 isValid = isLeftShift;
7446 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007447 case Instruction::Or:
7448 case Instruction::Xor:
7449 highBitSet = false;
7450 break;
7451 case Instruction::And:
7452 highBitSet = true;
7453 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007454 }
7455
7456 // If this is a signed shift right, and the high bit is modified
7457 // by the logical operation, do not perform the transformation.
7458 // The highBitSet boolean indicates the value of the high bit of
7459 // the constant which would cause it to be modified for this
7460 // operation.
7461 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007462 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007463 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007464
7465 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007466 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007467
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007468 Value *NewShift =
7469 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007470 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007471
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007472 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007473 NewRHS);
7474 }
7475 }
7476 }
7477 }
7478
Chris Lattnerad0124c2006-01-06 07:52:12 +00007479 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007480 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7481 if (ShiftOp && !ShiftOp->isShift())
7482 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007483
Reid Spencerb83eb642006-10-20 07:07:24 +00007484 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007485 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007486 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7487 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007488 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7489 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7490 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007491
Zhou Sheng4351c642007-04-02 08:20:41 +00007492 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007493
7494 const IntegerType *Ty = cast<IntegerType>(I.getType());
7495
7496 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007497 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007498 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7499 // saturates.
7500 if (AmtSum >= TypeBits) {
7501 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007502 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007503 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7504 }
7505
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007506 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007507 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007508 }
7509
7510 if (ShiftOp->getOpcode() == Instruction::LShr &&
7511 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007512 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007513 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007514
Chris Lattnerb87056f2007-02-05 00:57:54 +00007515 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007516 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007517 }
7518
7519 if (ShiftOp->getOpcode() == Instruction::AShr &&
7520 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007521 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007522 if (AmtSum >= TypeBits)
7523 AmtSum = TypeBits-1;
7524
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007525 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007526
Zhou Shenge9e03f62007-03-28 15:02:20 +00007527 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007528 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007529 }
7530
Chris Lattnerb87056f2007-02-05 00:57:54 +00007531 // Okay, if we get here, one shift must be left, and the other shift must be
7532 // right. See if the amounts are equal.
7533 if (ShiftAmt1 == ShiftAmt2) {
7534 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7535 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007536 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007537 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007538 }
7539 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7540 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007541 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007542 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007543 }
7544 // We can simplify ((X << C) >>s C) into a trunc + sext.
7545 // NOTE: we could do this for any C, but that would make 'unusual' integer
7546 // types. For now, just stick to ones well-supported by the code
7547 // generators.
7548 const Type *SExtType = 0;
7549 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007550 case 1 :
7551 case 8 :
7552 case 16 :
7553 case 32 :
7554 case 64 :
7555 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007556 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007557 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007558 default: break;
7559 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007560 if (SExtType)
7561 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007562 // Otherwise, we can't handle it yet.
7563 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007564 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007565
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007566 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007567 if (I.getOpcode() == Instruction::Shl) {
7568 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7569 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007570 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007571
Reid Spencer55702aa2007-03-25 21:11:44 +00007572 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007573 return BinaryOperator::CreateAnd(Shift,
7574 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007575 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007576
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007577 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007578 if (I.getOpcode() == Instruction::LShr) {
7579 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007580 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007581
Reid Spencerd5e30f02007-03-26 17:18:58 +00007582 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007583 return BinaryOperator::CreateAnd(Shift,
7584 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007585 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007586
7587 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7588 } else {
7589 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007590 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007591
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007592 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007593 if (I.getOpcode() == Instruction::Shl) {
7594 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7595 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007596 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7597 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007598
Reid Spencer55702aa2007-03-25 21:11:44 +00007599 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007600 return BinaryOperator::CreateAnd(Shift,
7601 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007602 }
7603
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007604 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007605 if (I.getOpcode() == Instruction::LShr) {
7606 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007607 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007608
Reid Spencer68d27cf2007-03-26 23:45:51 +00007609 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007610 return BinaryOperator::CreateAnd(Shift,
7611 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007612 }
7613
7614 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007615 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007616 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007617 return 0;
7618}
7619
Chris Lattnera1be5662002-05-02 17:06:02 +00007620
Chris Lattnercfd65102005-10-29 04:36:15 +00007621/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7622/// expression. If so, decompose it, returning some value X, such that Val is
7623/// X*Scale+Offset.
7624///
7625static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007626 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007627 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7628 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007629 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007630 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007631 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007632 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007633 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7634 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7635 if (I->getOpcode() == Instruction::Shl) {
7636 // This is a value scaled by '1 << the shift amt'.
7637 Scale = 1U << RHS->getZExtValue();
7638 Offset = 0;
7639 return I->getOperand(0);
7640 } else if (I->getOpcode() == Instruction::Mul) {
7641 // This value is scaled by 'RHS'.
7642 Scale = RHS->getZExtValue();
7643 Offset = 0;
7644 return I->getOperand(0);
7645 } else if (I->getOpcode() == Instruction::Add) {
7646 // We have X+C. Check to see if we really have (X*C2)+C1,
7647 // where C1 is divisible by C2.
7648 unsigned SubScale;
7649 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007650 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7651 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007652 Offset += RHS->getZExtValue();
7653 Scale = SubScale;
7654 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007655 }
7656 }
7657 }
7658
7659 // Otherwise, we can't look past this.
7660 Scale = 1;
7661 Offset = 0;
7662 return Val;
7663}
7664
7665
Chris Lattnerb3f83972005-10-24 06:03:58 +00007666/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7667/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007668Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007669 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007670 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007671
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007672 BuilderTy AllocaBuilder(*Builder);
7673 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7674
Chris Lattnerb53c2382005-10-24 06:22:12 +00007675 // Remove any uses of AI that are dead.
7676 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007677
Chris Lattnerb53c2382005-10-24 06:22:12 +00007678 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7679 Instruction *User = cast<Instruction>(*UI++);
7680 if (isInstructionTriviallyDead(User)) {
7681 while (UI != E && *UI == User)
7682 ++UI; // If this instruction uses AI more than once, don't break UI.
7683
Chris Lattnerb53c2382005-10-24 06:22:12 +00007684 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007685 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007686 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007687 }
7688 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007689
7690 // This requires TargetData to get the alloca alignment and size information.
7691 if (!TD) return 0;
7692
Chris Lattnerb3f83972005-10-24 06:03:58 +00007693 // Get the type really allocated and the type casted to.
7694 const Type *AllocElTy = AI.getAllocatedType();
7695 const Type *CastElTy = PTy->getElementType();
7696 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007697
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007698 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7699 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007700 if (CastElTyAlign < AllocElTyAlign) return 0;
7701
Chris Lattner39387a52005-10-24 06:35:18 +00007702 // If the allocation has multiple uses, only promote it if we are strictly
7703 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007704 // same, we open the door to infinite loops of various kinds. (A reference
7705 // from a dbg.declare doesn't count as a use for this purpose.)
7706 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7707 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007708
Duncan Sands777d2302009-05-09 07:06:46 +00007709 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7710 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007711 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007712
Chris Lattner455fcc82005-10-29 03:19:53 +00007713 // See if we can satisfy the modulus by pulling a scale out of the array
7714 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007715 unsigned ArraySizeScale;
7716 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007717 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007718 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7719 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007720
Chris Lattner455fcc82005-10-29 03:19:53 +00007721 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7722 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007723 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7724 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007725
Chris Lattner455fcc82005-10-29 03:19:53 +00007726 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7727 Value *Amt = 0;
7728 if (Scale == 1) {
7729 Amt = NumElements;
7730 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007731 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007732 // Insert before the alloca, not before the cast.
7733 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007734 }
7735
Jeff Cohen86796be2007-04-04 16:58:57 +00007736 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007737 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007738 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007739 }
7740
Chris Lattnerb3f83972005-10-24 06:03:58 +00007741 AllocationInst *New;
7742 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007743 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Chris Lattnerb3f83972005-10-24 06:03:58 +00007744 else
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007745 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7746 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007747 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007748
Dale Johannesena0a66372009-03-05 00:39:02 +00007749 // If the allocation has one real use plus a dbg.declare, just remove the
7750 // declare.
7751 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7752 EraseInstFromFunction(*DI);
7753 }
7754 // If the allocation has multiple real uses, insert a cast and change all
7755 // things that used it to use the new cast. This will also hack on CI, but it
7756 // will die soon.
7757 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007758 // New is the allocation instruction, pointer typed. AI is the original
7759 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007760 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007761 AI.replaceAllUsesWith(NewCast);
7762 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007763 return ReplaceInstUsesWith(CI, New);
7764}
7765
Chris Lattner70074e02006-05-13 02:06:03 +00007766/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007767/// and return it as type Ty without inserting any new casts and without
7768/// changing the computed value. This is used by code that tries to decide
7769/// whether promoting or shrinking integer operations to wider or smaller types
7770/// will allow us to eliminate a truncate or extend.
7771///
7772/// This is a truncation operation if Ty is smaller than V->getType(), or an
7773/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007774///
7775/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7776/// should return true if trunc(V) can be computed by computing V in the smaller
7777/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7778/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7779/// efficiently truncated.
7780///
7781/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7782/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7783/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007784bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007785 unsigned CastOpc,
7786 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007787 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007788 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007789 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007790
7791 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007792 if (!I) return false;
7793
Dan Gohman6de29f82009-06-15 22:12:54 +00007794 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007795
Chris Lattner951626b2007-08-02 06:11:14 +00007796 // If this is an extension or truncate, we can often eliminate it.
7797 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7798 // If this is a cast from the destination type, we can trivially eliminate
7799 // it, and this will remove a cast overall.
7800 if (I->getOperand(0)->getType() == Ty) {
7801 // If the first operand is itself a cast, and is eliminable, do not count
7802 // this as an eliminable cast. We would prefer to eliminate those two
7803 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007804 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007805 ++NumCastsRemoved;
7806 return true;
7807 }
7808 }
7809
7810 // We can't extend or shrink something that has multiple uses: doing so would
7811 // require duplicating the instruction in general, which isn't profitable.
7812 if (!I->hasOneUse()) return false;
7813
Evan Chengf35fd542009-01-15 17:01:23 +00007814 unsigned Opc = I->getOpcode();
7815 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007816 case Instruction::Add:
7817 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007818 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007819 case Instruction::And:
7820 case Instruction::Or:
7821 case Instruction::Xor:
7822 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007823 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007824 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007825 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007826 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007827
Eli Friedman070a9812009-07-13 22:46:01 +00007828 case Instruction::UDiv:
7829 case Instruction::URem: {
7830 // UDiv and URem can be truncated if all the truncated bits are zero.
7831 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7832 uint32_t BitWidth = Ty->getScalarSizeInBits();
7833 if (BitWidth < OrigBitWidth) {
7834 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7835 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7836 MaskedValueIsZero(I->getOperand(1), Mask)) {
7837 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7838 NumCastsRemoved) &&
7839 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7840 NumCastsRemoved);
7841 }
7842 }
7843 break;
7844 }
Chris Lattner46b96052006-11-29 07:18:39 +00007845 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007846 // If we are truncating the result of this SHL, and if it's a shift of a
7847 // constant amount, we can always perform a SHL in a smaller type.
7848 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007849 uint32_t BitWidth = Ty->getScalarSizeInBits();
7850 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007851 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007852 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007853 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007854 }
7855 break;
7856 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007857 // If this is a truncate of a logical shr, we can truncate it to a smaller
7858 // lshr iff we know that the bits we would otherwise be shifting in are
7859 // already zeros.
7860 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007861 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7862 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007863 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007864 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007865 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7866 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007867 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007868 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007869 }
7870 }
Chris Lattner46b96052006-11-29 07:18:39 +00007871 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007872 case Instruction::ZExt:
7873 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007874 case Instruction::Trunc:
7875 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007876 // can safely replace it. Note that replacing it does not reduce the number
7877 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007878 if (Opc == CastOpc)
7879 return true;
7880
7881 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007882 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007883 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007884 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007885 case Instruction::Select: {
7886 SelectInst *SI = cast<SelectInst>(I);
7887 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007888 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007889 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007890 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007891 }
Chris Lattner8114b712008-06-18 04:00:49 +00007892 case Instruction::PHI: {
7893 // We can change a phi if we can change all operands.
7894 PHINode *PN = cast<PHINode>(I);
7895 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7896 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007897 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007898 return false;
7899 return true;
7900 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007901 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007902 // TODO: Can handle more cases here.
7903 break;
7904 }
7905
7906 return false;
7907}
7908
7909/// EvaluateInDifferentType - Given an expression that
7910/// CanEvaluateInDifferentType returns true for, actually insert the code to
7911/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007912Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007913 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007914 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007915 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007916 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007917
7918 // Otherwise, it must be an instruction.
7919 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007920 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007921 unsigned Opc = I->getOpcode();
7922 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007923 case Instruction::Add:
7924 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007925 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007926 case Instruction::And:
7927 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007928 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007929 case Instruction::AShr:
7930 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00007931 case Instruction::Shl:
7932 case Instruction::UDiv:
7933 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007934 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007935 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007936 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007937 break;
7938 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007939 case Instruction::Trunc:
7940 case Instruction::ZExt:
7941 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007942 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007943 // just return the source. There's no need to insert it because it is not
7944 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007945 if (I->getOperand(0)->getType() == Ty)
7946 return I->getOperand(0);
7947
Chris Lattner8114b712008-06-18 04:00:49 +00007948 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007949 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007950 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007951 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007952 case Instruction::Select: {
7953 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7954 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7955 Res = SelectInst::Create(I->getOperand(0), True, False);
7956 break;
7957 }
Chris Lattner8114b712008-06-18 04:00:49 +00007958 case Instruction::PHI: {
7959 PHINode *OPN = cast<PHINode>(I);
7960 PHINode *NPN = PHINode::Create(Ty);
7961 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7962 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7963 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7964 }
7965 Res = NPN;
7966 break;
7967 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007968 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007969 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00007970 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00007971 break;
7972 }
7973
Chris Lattner8114b712008-06-18 04:00:49 +00007974 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007975 return InsertNewInstBefore(Res, *I);
7976}
7977
Reid Spencer3da59db2006-11-27 01:05:10 +00007978/// @brief Implement the transforms common to all CastInst visitors.
7979Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007980 Value *Src = CI.getOperand(0);
7981
Dan Gohman23d9d272007-05-11 21:10:54 +00007982 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007983 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007984 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007985 if (Instruction::CastOps opc =
7986 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7987 // The first cast (CSrc) is eliminable so we need to fix up or replace
7988 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007989 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007990 }
7991 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007992
Reid Spencer3da59db2006-11-27 01:05:10 +00007993 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007994 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7995 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7996 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007997
7998 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007999 if (isa<PHINode>(Src))
8000 if (Instruction *NV = FoldOpIntoPhi(CI))
8001 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008002
Reid Spencer3da59db2006-11-27 01:05:10 +00008003 return 0;
8004}
8005
Chris Lattner46cd5a12009-01-09 05:44:56 +00008006/// FindElementAtOffset - Given a type and a constant offset, determine whether
8007/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008008/// the specified offset. If so, fill them into NewIndices and return the
8009/// resultant element type, otherwise return null.
8010static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8011 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008012 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008013 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008014 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008015 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008016
8017 // Start with the index over the outer type. Note that the type size
8018 // might be zero (even if the offset isn't zero) if the indexed type
8019 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008020 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008021 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008022 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008023 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008024 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008025
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008026 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008027 if (Offset < 0) {
8028 --FirstIdx;
8029 Offset += TySize;
8030 assert(Offset >= 0);
8031 }
8032 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8033 }
8034
Owen Andersoneed707b2009-07-24 23:12:02 +00008035 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008036
8037 // Index into the types. If we fail, set OrigBase to null.
8038 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008039 // Indexing into tail padding between struct/array elements.
8040 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008041 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008042
Chris Lattner46cd5a12009-01-09 05:44:56 +00008043 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8044 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008045 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8046 "Offset must stay within the indexed type");
8047
Chris Lattner46cd5a12009-01-09 05:44:56 +00008048 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008049 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008050
8051 Offset -= SL->getElementOffset(Elt);
8052 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008053 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008054 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008055 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008056 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008057 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008058 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008059 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008060 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008061 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008062 }
8063 }
8064
Chris Lattner3914f722009-01-24 01:00:13 +00008065 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008066}
8067
Chris Lattnerd3e28342007-04-27 17:44:50 +00008068/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8069Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8070 Value *Src = CI.getOperand(0);
8071
Chris Lattnerd3e28342007-04-27 17:44:50 +00008072 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008073 // If casting the result of a getelementptr instruction with no offset, turn
8074 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008075 if (GEP->hasAllZeroIndices()) {
8076 // Changing the cast operand is usually not a good idea but it is safe
8077 // here because the pointer operand is being replaced with another
8078 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008079 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008080 CI.setOperand(0, GEP->getOperand(0));
8081 return &CI;
8082 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008083
8084 // If the GEP has a single use, and the base pointer is a bitcast, and the
8085 // GEP computes a constant offset, see if we can convert these three
8086 // instructions into fewer. This typically happens with unions and other
8087 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008088 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008089 if (GEP->hasAllConstantIndices()) {
8090 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008091 ConstantInt *OffsetV =
8092 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008093 int64_t Offset = OffsetV->getSExtValue();
8094
8095 // Get the base pointer input of the bitcast, and the type it points to.
8096 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8097 const Type *GEPIdxTy =
8098 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008099 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008100 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008101 // If we were able to index down into an element, create the GEP
8102 // and bitcast the result. This eliminates one bitcast, potentially
8103 // two.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008104 Value *NGEP = Builder->CreateGEP(OrigBase, NewIndices.begin(),
8105 NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008106 NGEP->takeName(GEP);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008107 if (isa<Instruction>(NGEP) && cast<GEPOperator>(GEP)->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008108 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner9bc14642007-04-28 00:57:34 +00008109
Chris Lattner46cd5a12009-01-09 05:44:56 +00008110 if (isa<BitCastInst>(CI))
8111 return new BitCastInst(NGEP, CI.getType());
8112 assert(isa<PtrToIntInst>(CI));
8113 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008114 }
8115 }
8116 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008117 }
8118
8119 return commonCastTransforms(CI);
8120}
8121
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008122/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8123/// type like i42. We don't want to introduce operations on random non-legal
8124/// integer types where they don't already exist in the code. In the future,
8125/// we should consider making this based off target-data, so that 32-bit targets
8126/// won't get i64 operations etc.
8127static bool isSafeIntegerType(const Type *Ty) {
8128 switch (Ty->getPrimitiveSizeInBits()) {
8129 case 8:
8130 case 16:
8131 case 32:
8132 case 64:
8133 return true;
8134 default:
8135 return false;
8136 }
8137}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008138
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008139/// commonIntCastTransforms - This function implements the common transforms
8140/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008141Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8142 if (Instruction *Result = commonCastTransforms(CI))
8143 return Result;
8144
8145 Value *Src = CI.getOperand(0);
8146 const Type *SrcTy = Src->getType();
8147 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008148 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8149 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008150
Reid Spencer3da59db2006-11-27 01:05:10 +00008151 // See if we can simplify any instructions used by the LHS whose sole
8152 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008153 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008154 return &CI;
8155
8156 // If the source isn't an instruction or has more than one use then we
8157 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008158 Instruction *SrcI = dyn_cast<Instruction>(Src);
8159 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008160 return 0;
8161
Chris Lattnerc739cd62007-03-03 05:27:34 +00008162 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008163 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008164 // Only do this if the dest type is a simple type, don't convert the
8165 // expression tree to something weird like i93 unless the source is also
8166 // strange.
8167 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008168 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8169 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008170 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008171 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008172 // eliminates the cast, so it is always a win. If this is a zero-extension,
8173 // we need to do an AND to maintain the clear top-part of the computation,
8174 // so we require that the input have eliminated at least one cast. If this
8175 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008176 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008177 bool DoXForm = false;
8178 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008179 switch (CI.getOpcode()) {
8180 default:
8181 // All the others use floating point so we shouldn't actually
8182 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008183 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008184 case Instruction::Trunc:
8185 DoXForm = true;
8186 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008187 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008188 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008189 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008190 // If it's unnecessary to issue an AND to clear the high bits, it's
8191 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008192 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008193 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8194 if (MaskedValueIsZero(TryRes, Mask))
8195 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008196
8197 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008198 if (TryI->use_empty())
8199 EraseInstFromFunction(*TryI);
8200 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008201 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008202 }
Evan Chengf35fd542009-01-15 17:01:23 +00008203 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008204 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008205 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008206 // If we do not have to emit the truncate + sext pair, then it's always
8207 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008208 //
8209 // It's not safe to eliminate the trunc + sext pair if one of the
8210 // eliminated cast is a truncate. e.g.
8211 // t2 = trunc i32 t1 to i16
8212 // t3 = sext i16 t2 to i32
8213 // !=
8214 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008215 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008216 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8217 if (NumSignBits > (DestBitSize - SrcBitSize))
8218 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008219
8220 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008221 if (TryI->use_empty())
8222 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008223 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008224 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008225 }
Evan Chengf35fd542009-01-15 17:01:23 +00008226 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008227
8228 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008229 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8230 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008231 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8232 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008233 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008234 // Just replace this cast with the result.
8235 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008236
Reid Spencer3da59db2006-11-27 01:05:10 +00008237 assert(Res->getType() == DestTy);
8238 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008239 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008240 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008241 // Just replace this cast with the result.
8242 return ReplaceInstUsesWith(CI, Res);
8243 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008244 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008245
8246 // If the high bits are already zero, just replace this cast with the
8247 // result.
8248 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8249 if (MaskedValueIsZero(Res, Mask))
8250 return ReplaceInstUsesWith(CI, Res);
8251
8252 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008253 Constant *C = ConstantInt::get(*Context,
8254 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008255 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008256 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008257 case Instruction::SExt: {
8258 // If the high bits are already filled with sign bit, just replace this
8259 // cast with the result.
8260 unsigned NumSignBits = ComputeNumSignBits(Res);
8261 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008262 return ReplaceInstUsesWith(CI, Res);
8263
Reid Spencer3da59db2006-11-27 01:05:10 +00008264 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008265 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008266 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8267 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008268 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008269 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008270 }
8271 }
8272
8273 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8274 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8275
8276 switch (SrcI->getOpcode()) {
8277 case Instruction::Add:
8278 case Instruction::Mul:
8279 case Instruction::And:
8280 case Instruction::Or:
8281 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008282 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008283 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8284 // Don't insert two casts unless at least one can be eliminated.
8285 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008286 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008287 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8288 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008289 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008290 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008291 }
8292 }
8293
8294 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8295 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8296 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008297 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008298 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008299 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008300 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008301 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008302 }
8303 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008304
Eli Friedman65445c52009-07-13 21:45:57 +00008305 case Instruction::Shl: {
8306 // Canonicalize trunc inside shl, if we can.
8307 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8308 if (CI && DestBitSize < SrcBitSize &&
8309 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8310 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8311 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008312 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008313 }
8314 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008315 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008316 }
8317 return 0;
8318}
8319
Chris Lattner8a9f5712007-04-11 06:57:46 +00008320Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008321 if (Instruction *Result = commonIntCastTransforms(CI))
8322 return Result;
8323
8324 Value *Src = CI.getOperand(0);
8325 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008326 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8327 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008328
8329 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008330 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008331 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008332 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008333 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008334 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008335 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008336
Chris Lattner4f9797d2009-03-24 18:15:30 +00008337 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8338 ConstantInt *ShAmtV = 0;
8339 Value *ShiftOp = 0;
8340 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008341 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008342 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8343
8344 // Get a mask for the bits shifting in.
8345 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8346 if (MaskedValueIsZero(ShiftOp, Mask)) {
8347 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008348 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008349
8350 // Okay, we can shrink this. Truncate the input, then return a new
8351 // shift.
8352 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008353 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008354 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008355 }
8356 }
8357
8358 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008359}
8360
Evan Chengb98a10e2008-03-24 00:21:34 +00008361/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8362/// in order to eliminate the icmp.
8363Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8364 bool DoXform) {
8365 // If we are just checking for a icmp eq of a single bit and zext'ing it
8366 // to an integer, then shift the bit to the appropriate place and then
8367 // cast to integer to avoid the comparison.
8368 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8369 const APInt &Op1CV = Op1C->getValue();
8370
8371 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8372 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8373 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8374 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8375 if (!DoXform) return ICI;
8376
8377 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008378 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008379 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008380 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008381 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008382 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008383
8384 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008385 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008386 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008387 }
8388
8389 return ReplaceInstUsesWith(CI, In);
8390 }
8391
8392
8393
8394 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8395 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8396 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8397 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8398 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8399 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8400 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8401 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8402 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8403 // This only works for EQ and NE
8404 ICI->isEquality()) {
8405 // If Op1C some other power of two, convert:
8406 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8407 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8408 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8409 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8410
8411 APInt KnownZeroMask(~KnownZero);
8412 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8413 if (!DoXform) return ICI;
8414
8415 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8416 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8417 // (X&4) == 2 --> false
8418 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008419 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008420 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008421 return ReplaceInstUsesWith(CI, Res);
8422 }
8423
8424 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8425 Value *In = ICI->getOperand(0);
8426 if (ShiftAmt) {
8427 // Perform a logical shr by shiftamt.
8428 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008429 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8430 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008431 }
8432
8433 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008434 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008435 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008436 }
8437
8438 if (CI.getType() == In->getType())
8439 return ReplaceInstUsesWith(CI, In);
8440 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008441 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008442 }
8443 }
8444 }
8445
8446 return 0;
8447}
8448
Chris Lattner8a9f5712007-04-11 06:57:46 +00008449Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008450 // If one of the common conversion will work ..
8451 if (Instruction *Result = commonIntCastTransforms(CI))
8452 return Result;
8453
8454 Value *Src = CI.getOperand(0);
8455
Chris Lattnera84f47c2009-02-17 20:47:23 +00008456 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8457 // types and if the sizes are just right we can convert this into a logical
8458 // 'and' which will be much cheaper than the pair of casts.
8459 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8460 // Get the sizes of the types involved. We know that the intermediate type
8461 // will be smaller than A or C, but don't know the relation between A and C.
8462 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008463 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8464 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8465 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008466 // If we're actually extending zero bits, then if
8467 // SrcSize < DstSize: zext(a & mask)
8468 // SrcSize == DstSize: a & mask
8469 // SrcSize > DstSize: trunc(a) & mask
8470 if (SrcSize < DstSize) {
8471 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008472 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008473 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008474 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008475 }
8476
8477 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008478 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008479 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008480 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008481 }
8482 if (SrcSize > DstSize) {
8483 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008484 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008485 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008486 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008487 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008488 }
8489 }
8490
Evan Chengb98a10e2008-03-24 00:21:34 +00008491 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8492 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008493
Evan Chengb98a10e2008-03-24 00:21:34 +00008494 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8495 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8496 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8497 // of the (zext icmp) will be transformed.
8498 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8499 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8500 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8501 (transformZExtICmp(LHS, CI, false) ||
8502 transformZExtICmp(RHS, CI, false))) {
8503 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8504 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008505 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008506 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008507 }
8508
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008509 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008510 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8511 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8512 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8513 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008514 if (TI0->getType() == CI.getType())
8515 return
8516 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008517 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008518 }
8519
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008520 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8521 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8522 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8523 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8524 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8525 And->getOperand(1) == C)
8526 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8527 Value *TI0 = TI->getOperand(0);
8528 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008529 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008530 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008531 return BinaryOperator::CreateXor(NewAnd, ZC);
8532 }
8533 }
8534
Reid Spencer3da59db2006-11-27 01:05:10 +00008535 return 0;
8536}
8537
Chris Lattner8a9f5712007-04-11 06:57:46 +00008538Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008539 if (Instruction *I = commonIntCastTransforms(CI))
8540 return I;
8541
Chris Lattner8a9f5712007-04-11 06:57:46 +00008542 Value *Src = CI.getOperand(0);
8543
Dan Gohman1975d032008-10-30 20:40:10 +00008544 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008545 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008546 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008547 Constant::getAllOnesValue(CI.getType()),
8548 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008549
8550 // See if the value being truncated is already sign extended. If so, just
8551 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008552 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008553 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008554 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8555 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8556 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008557 unsigned NumSignBits = ComputeNumSignBits(Op);
8558
8559 if (OpBits == DestBits) {
8560 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8561 // bits, it is already ready.
8562 if (NumSignBits > DestBits-MidBits)
8563 return ReplaceInstUsesWith(CI, Op);
8564 } else if (OpBits < DestBits) {
8565 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8566 // bits, just sext from i32.
8567 if (NumSignBits > OpBits-MidBits)
8568 return new SExtInst(Op, CI.getType(), "tmp");
8569 } else {
8570 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8571 // bits, just truncate to i32.
8572 if (NumSignBits > OpBits-MidBits)
8573 return new TruncInst(Op, CI.getType(), "tmp");
8574 }
8575 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008576
8577 // If the input is a shl/ashr pair of a same constant, then this is a sign
8578 // extension from a smaller value. If we could trust arbitrary bitwidth
8579 // integers, we could turn this into a truncate to the smaller bit and then
8580 // use a sext for the whole extension. Since we don't, look deeper and check
8581 // for a truncate. If the source and dest are the same type, eliminate the
8582 // trunc and extend and just do shifts. For example, turn:
8583 // %a = trunc i32 %i to i8
8584 // %b = shl i8 %a, 6
8585 // %c = ashr i8 %b, 6
8586 // %d = sext i8 %c to i32
8587 // into:
8588 // %a = shl i32 %i, 30
8589 // %d = ashr i32 %a, 30
8590 Value *A = 0;
8591 ConstantInt *BA = 0, *CA = 0;
8592 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008593 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008594 BA == CA && isa<TruncInst>(A)) {
8595 Value *I = cast<TruncInst>(A)->getOperand(0);
8596 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008597 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8598 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008599 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008600 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008601 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008602 return BinaryOperator::CreateAShr(I, ShAmtV);
8603 }
8604 }
8605
Chris Lattnerba417832007-04-11 06:12:58 +00008606 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008607}
8608
Chris Lattnerb7530652008-01-27 05:29:54 +00008609/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8610/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008611static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008612 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008613 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008614 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008615 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8616 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008617 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008618 return 0;
8619}
8620
8621/// LookThroughFPExtensions - If this is an fp extension instruction, look
8622/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008623static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008624 if (Instruction *I = dyn_cast<Instruction>(V))
8625 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008626 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008627
8628 // If this value is a constant, return the constant in the smallest FP type
8629 // that can accurately represent it. This allows us to turn
8630 // (float)((double)X+2.0) into x+2.0f.
8631 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008632 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008633 return V; // No constant folding of this.
8634 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008635 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008636 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008637 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008638 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008639 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008640 return V;
8641 // Don't try to shrink to various long double types.
8642 }
8643
8644 return V;
8645}
8646
8647Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8648 if (Instruction *I = commonCastTransforms(CI))
8649 return I;
8650
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008651 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008652 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008653 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008654 // many builtins (sqrt, etc).
8655 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8656 if (OpI && OpI->hasOneUse()) {
8657 switch (OpI->getOpcode()) {
8658 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008659 case Instruction::FAdd:
8660 case Instruction::FSub:
8661 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008662 case Instruction::FDiv:
8663 case Instruction::FRem:
8664 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008665 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8666 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008667 if (LHSTrunc->getType() != SrcTy &&
8668 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008669 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008670 // If the source types were both smaller than the destination type of
8671 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008672 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8673 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008674 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8675 CI.getType(), CI);
8676 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8677 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008678 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008679 }
8680 }
8681 break;
8682 }
8683 }
8684 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008685}
8686
8687Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8688 return commonCastTransforms(CI);
8689}
8690
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008691Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008692 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8693 if (OpI == 0)
8694 return commonCastTransforms(FI);
8695
8696 // fptoui(uitofp(X)) --> X
8697 // fptoui(sitofp(X)) --> X
8698 // This is safe if the intermediate type has enough bits in its mantissa to
8699 // accurately represent all values of X. For example, do not do this with
8700 // i64->float->i64. This is also safe for sitofp case, because any negative
8701 // 'X' value would cause an undefined result for the fptoui.
8702 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8703 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008704 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008705 OpI->getType()->getFPMantissaWidth())
8706 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008707
8708 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008709}
8710
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008711Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008712 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8713 if (OpI == 0)
8714 return commonCastTransforms(FI);
8715
8716 // fptosi(sitofp(X)) --> X
8717 // fptosi(uitofp(X)) --> X
8718 // This is safe if the intermediate type has enough bits in its mantissa to
8719 // accurately represent all values of X. For example, do not do this with
8720 // i64->float->i64. This is also safe for sitofp case, because any negative
8721 // 'X' value would cause an undefined result for the fptoui.
8722 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8723 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008724 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008725 OpI->getType()->getFPMantissaWidth())
8726 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008727
8728 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008729}
8730
8731Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8732 return commonCastTransforms(CI);
8733}
8734
8735Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8736 return commonCastTransforms(CI);
8737}
8738
Chris Lattnera0e69692009-03-24 18:35:40 +00008739Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8740 // If the destination integer type is smaller than the intptr_t type for
8741 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8742 // trunc to be exposed to other transforms. Don't do this for extending
8743 // ptrtoint's, because we don't know if the target sign or zero extends its
8744 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008745 if (TD &&
8746 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008747 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8748 TD->getIntPtrType(CI.getContext()),
8749 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008750 return new TruncInst(P, CI.getType());
8751 }
8752
Chris Lattnerd3e28342007-04-27 17:44:50 +00008753 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008754}
8755
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008756Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008757 // If the source integer type is larger than the intptr_t type for
8758 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8759 // allows the trunc to be exposed to other transforms. Don't do this for
8760 // extending inttoptr's, because we don't know if the target sign or zero
8761 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008762 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008763 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008764 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8765 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008766 return new IntToPtrInst(P, CI.getType());
8767 }
8768
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008769 if (Instruction *I = commonCastTransforms(CI))
8770 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008771
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008772 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008773}
8774
Chris Lattnerd3e28342007-04-27 17:44:50 +00008775Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008776 // If the operands are integer typed then apply the integer transforms,
8777 // otherwise just apply the common ones.
8778 Value *Src = CI.getOperand(0);
8779 const Type *SrcTy = Src->getType();
8780 const Type *DestTy = CI.getType();
8781
Eli Friedman7e25d452009-07-13 20:53:00 +00008782 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008783 if (Instruction *I = commonPointerCastTransforms(CI))
8784 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008785 } else {
8786 if (Instruction *Result = commonCastTransforms(CI))
8787 return Result;
8788 }
8789
8790
8791 // Get rid of casts from one type to the same type. These are useless and can
8792 // be replaced by the operand.
8793 if (DestTy == Src->getType())
8794 return ReplaceInstUsesWith(CI, Src);
8795
Reid Spencer3da59db2006-11-27 01:05:10 +00008796 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008797 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8798 const Type *DstElTy = DstPTy->getElementType();
8799 const Type *SrcElTy = SrcPTy->getElementType();
8800
Nate Begeman83ad90a2008-03-31 00:22:16 +00008801 // If the address spaces don't match, don't eliminate the bitcast, which is
8802 // required for changing types.
8803 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8804 return 0;
8805
Chris Lattnerd3e28342007-04-27 17:44:50 +00008806 // If we are casting a malloc or alloca to a pointer to a type of the same
8807 // size, rewrite the allocation instruction to allocate the "right" type.
8808 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8809 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8810 return V;
8811
Chris Lattnerd717c182007-05-05 22:32:24 +00008812 // If the source and destination are pointers, and this cast is equivalent
8813 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008814 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008815 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008816 unsigned NumZeros = 0;
8817 while (SrcElTy != DstElTy &&
8818 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8819 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8820 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8821 ++NumZeros;
8822 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008823
Chris Lattnerd3e28342007-04-27 17:44:50 +00008824 // If we found a path from the src to dest, create the getelementptr now.
8825 if (SrcElTy == DstElTy) {
8826 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008827 Instruction *GEP = GetElementPtrInst::Create(Src,
8828 Idxs.begin(), Idxs.end(), "",
8829 ((Instruction*) NULL));
8830 cast<GEPOperator>(GEP)->setIsInBounds(true);
8831 return GEP;
Chris Lattner9fb92132006-04-12 18:09:35 +00008832 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008833 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008834
Eli Friedman2451a642009-07-18 23:06:53 +00008835 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8836 if (DestVTy->getNumElements() == 1) {
8837 if (!isa<VectorType>(SrcTy)) {
8838 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8839 DestVTy->getElementType(), CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008840 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Owen Anderson1d0be152009-08-13 21:58:54 +00008841 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008842 }
8843 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8844 }
8845 }
8846
8847 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8848 if (SrcVTy->getNumElements() == 1) {
8849 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008850 Value *Elem =
8851 Builder->CreateExtractElement(Src,
8852 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008853 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8854 }
8855 }
8856 }
8857
Reid Spencer3da59db2006-11-27 01:05:10 +00008858 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8859 if (SVI->hasOneUse()) {
8860 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8861 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008862 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008863 cast<VectorType>(DestTy)->getNumElements() ==
8864 SVI->getType()->getNumElements() &&
8865 SVI->getType()->getNumElements() ==
8866 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008867 CastInst *Tmp;
8868 // If either of the operands is a cast from CI.getType(), then
8869 // evaluating the shuffle in the casted destination's type will allow
8870 // us to eliminate at least one cast.
8871 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8872 Tmp->getOperand(0)->getType() == DestTy) ||
8873 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8874 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008875 Value *LHS = InsertCastBefore(Instruction::BitCast,
8876 SVI->getOperand(0), DestTy, CI);
8877 Value *RHS = InsertCastBefore(Instruction::BitCast,
8878 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008879 // Return a new shuffle vector. Use the same element ID's, as we
8880 // know the vector types match #elts.
8881 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008882 }
8883 }
8884 }
8885 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008886 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008887}
8888
Chris Lattnere576b912004-04-09 23:46:01 +00008889/// GetSelectFoldableOperands - We want to turn code that looks like this:
8890/// %C = or %A, %B
8891/// %D = select %cond, %C, %A
8892/// into:
8893/// %C = select %cond, %B, 0
8894/// %D = or %A, %C
8895///
8896/// Assuming that the specified instruction is an operand to the select, return
8897/// a bitmask indicating which operands of this instruction are foldable if they
8898/// equal the other incoming value of the select.
8899///
8900static unsigned GetSelectFoldableOperands(Instruction *I) {
8901 switch (I->getOpcode()) {
8902 case Instruction::Add:
8903 case Instruction::Mul:
8904 case Instruction::And:
8905 case Instruction::Or:
8906 case Instruction::Xor:
8907 return 3; // Can fold through either operand.
8908 case Instruction::Sub: // Can only fold on the amount subtracted.
8909 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008910 case Instruction::LShr:
8911 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008912 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008913 default:
8914 return 0; // Cannot fold
8915 }
8916}
8917
8918/// GetSelectFoldableConstant - For the same transformation as the previous
8919/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008920static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008921 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008922 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008923 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008924 case Instruction::Add:
8925 case Instruction::Sub:
8926 case Instruction::Or:
8927 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008928 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008929 case Instruction::LShr:
8930 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008931 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008932 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008933 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008934 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008935 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008936 }
8937}
8938
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008939/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8940/// have the same opcode and only one use each. Try to simplify this.
8941Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8942 Instruction *FI) {
8943 if (TI->getNumOperands() == 1) {
8944 // If this is a non-volatile load or a cast from the same type,
8945 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008946 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008947 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8948 return 0;
8949 } else {
8950 return 0; // unknown unary op.
8951 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008952
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008953 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008954 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00008955 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008956 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008957 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008958 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008959 }
8960
Reid Spencer832254e2007-02-02 02:16:23 +00008961 // Only handle binary operators here.
8962 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008963 return 0;
8964
8965 // Figure out if the operations have any operands in common.
8966 Value *MatchOp, *OtherOpT, *OtherOpF;
8967 bool MatchIsOpZero;
8968 if (TI->getOperand(0) == FI->getOperand(0)) {
8969 MatchOp = TI->getOperand(0);
8970 OtherOpT = TI->getOperand(1);
8971 OtherOpF = FI->getOperand(1);
8972 MatchIsOpZero = true;
8973 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8974 MatchOp = TI->getOperand(1);
8975 OtherOpT = TI->getOperand(0);
8976 OtherOpF = FI->getOperand(0);
8977 MatchIsOpZero = false;
8978 } else if (!TI->isCommutative()) {
8979 return 0;
8980 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8981 MatchOp = TI->getOperand(0);
8982 OtherOpT = TI->getOperand(1);
8983 OtherOpF = FI->getOperand(0);
8984 MatchIsOpZero = true;
8985 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8986 MatchOp = TI->getOperand(1);
8987 OtherOpT = TI->getOperand(0);
8988 OtherOpF = FI->getOperand(1);
8989 MatchIsOpZero = true;
8990 } else {
8991 return 0;
8992 }
8993
8994 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008995 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8996 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008997 InsertNewInstBefore(NewSI, SI);
8998
8999 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9000 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009001 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009002 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009003 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009004 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009005 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009006 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009007}
9008
Evan Chengde621922009-03-31 20:42:45 +00009009static bool isSelect01(Constant *C1, Constant *C2) {
9010 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9011 if (!C1I)
9012 return false;
9013 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9014 if (!C2I)
9015 return false;
9016 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9017}
9018
9019/// FoldSelectIntoOp - Try fold the select into one of the operands to
9020/// facilitate further optimization.
9021Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9022 Value *FalseVal) {
9023 // See the comment above GetSelectFoldableOperands for a description of the
9024 // transformation we are doing here.
9025 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9026 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9027 !isa<Constant>(FalseVal)) {
9028 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9029 unsigned OpToFold = 0;
9030 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9031 OpToFold = 1;
9032 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9033 OpToFold = 2;
9034 }
9035
9036 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009037 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009038 Value *OOp = TVI->getOperand(2-OpToFold);
9039 // Avoid creating select between 2 constants unless it's selecting
9040 // between 0 and 1.
9041 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9042 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9043 InsertNewInstBefore(NewSel, SI);
9044 NewSel->takeName(TVI);
9045 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9046 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009047 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009048 }
9049 }
9050 }
9051 }
9052 }
9053
9054 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9055 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9056 !isa<Constant>(TrueVal)) {
9057 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9058 unsigned OpToFold = 0;
9059 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9060 OpToFold = 1;
9061 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9062 OpToFold = 2;
9063 }
9064
9065 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009066 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009067 Value *OOp = FVI->getOperand(2-OpToFold);
9068 // Avoid creating select between 2 constants unless it's selecting
9069 // between 0 and 1.
9070 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9071 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9072 InsertNewInstBefore(NewSel, SI);
9073 NewSel->takeName(FVI);
9074 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9075 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009076 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009077 }
9078 }
9079 }
9080 }
9081 }
9082
9083 return 0;
9084}
9085
Dan Gohman81b28ce2008-09-16 18:46:06 +00009086/// visitSelectInstWithICmp - Visit a SelectInst that has an
9087/// ICmpInst as its first operand.
9088///
9089Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9090 ICmpInst *ICI) {
9091 bool Changed = false;
9092 ICmpInst::Predicate Pred = ICI->getPredicate();
9093 Value *CmpLHS = ICI->getOperand(0);
9094 Value *CmpRHS = ICI->getOperand(1);
9095 Value *TrueVal = SI.getTrueValue();
9096 Value *FalseVal = SI.getFalseValue();
9097
9098 // Check cases where the comparison is with a constant that
9099 // can be adjusted to fit the min/max idiom. We may edit ICI in
9100 // place here, so make sure the select is the only user.
9101 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009102 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009103 switch (Pred) {
9104 default: break;
9105 case ICmpInst::ICMP_ULT:
9106 case ICmpInst::ICMP_SLT: {
9107 // X < MIN ? T : F --> F
9108 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9109 return ReplaceInstUsesWith(SI, FalseVal);
9110 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009111 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009112 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9113 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9114 Pred = ICmpInst::getSwappedPredicate(Pred);
9115 CmpRHS = AdjustedRHS;
9116 std::swap(FalseVal, TrueVal);
9117 ICI->setPredicate(Pred);
9118 ICI->setOperand(1, CmpRHS);
9119 SI.setOperand(1, TrueVal);
9120 SI.setOperand(2, FalseVal);
9121 Changed = true;
9122 }
9123 break;
9124 }
9125 case ICmpInst::ICMP_UGT:
9126 case ICmpInst::ICMP_SGT: {
9127 // X > MAX ? T : F --> F
9128 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9129 return ReplaceInstUsesWith(SI, FalseVal);
9130 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009131 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009132 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9133 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9134 Pred = ICmpInst::getSwappedPredicate(Pred);
9135 CmpRHS = AdjustedRHS;
9136 std::swap(FalseVal, TrueVal);
9137 ICI->setPredicate(Pred);
9138 ICI->setOperand(1, CmpRHS);
9139 SI.setOperand(1, TrueVal);
9140 SI.setOperand(2, FalseVal);
9141 Changed = true;
9142 }
9143 break;
9144 }
9145 }
9146
Dan Gohman1975d032008-10-30 20:40:10 +00009147 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9148 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009149 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009150 if (match(TrueVal, m_ConstantInt<-1>()) &&
9151 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009152 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009153 else if (match(TrueVal, m_ConstantInt<0>()) &&
9154 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009155 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9156
Dan Gohman1975d032008-10-30 20:40:10 +00009157 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9158 // If we are just checking for a icmp eq of a single bit and zext'ing it
9159 // to an integer, then shift the bit to the appropriate place and then
9160 // cast to integer to avoid the comparison.
9161 const APInt &Op1CV = CI->getValue();
9162
9163 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9164 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9165 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009166 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009167 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009168 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009169 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009170 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009171 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009172 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009173 if (In->getType() != SI.getType())
9174 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009175 true/*SExt*/, "tmp", ICI);
9176
9177 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009178 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009179 In->getName()+".not"), *ICI);
9180
9181 return ReplaceInstUsesWith(SI, In);
9182 }
9183 }
9184 }
9185
Dan Gohman81b28ce2008-09-16 18:46:06 +00009186 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9187 // Transform (X == Y) ? X : Y -> Y
9188 if (Pred == ICmpInst::ICMP_EQ)
9189 return ReplaceInstUsesWith(SI, FalseVal);
9190 // Transform (X != Y) ? X : Y -> X
9191 if (Pred == ICmpInst::ICMP_NE)
9192 return ReplaceInstUsesWith(SI, TrueVal);
9193 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9194
9195 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9196 // Transform (X == Y) ? Y : X -> X
9197 if (Pred == ICmpInst::ICMP_EQ)
9198 return ReplaceInstUsesWith(SI, FalseVal);
9199 // Transform (X != Y) ? Y : X -> Y
9200 if (Pred == ICmpInst::ICMP_NE)
9201 return ReplaceInstUsesWith(SI, TrueVal);
9202 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9203 }
9204
9205 /// NOTE: if we wanted to, this is where to detect integer ABS
9206
9207 return Changed ? &SI : 0;
9208}
9209
Chris Lattner3d69f462004-03-12 05:52:32 +00009210Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009211 Value *CondVal = SI.getCondition();
9212 Value *TrueVal = SI.getTrueValue();
9213 Value *FalseVal = SI.getFalseValue();
9214
9215 // select true, X, Y -> X
9216 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009217 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009218 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009219
9220 // select C, X, X -> X
9221 if (TrueVal == FalseVal)
9222 return ReplaceInstUsesWith(SI, TrueVal);
9223
Chris Lattnere87597f2004-10-16 18:11:37 +00009224 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9225 return ReplaceInstUsesWith(SI, FalseVal);
9226 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9227 return ReplaceInstUsesWith(SI, TrueVal);
9228 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9229 if (isa<Constant>(TrueVal))
9230 return ReplaceInstUsesWith(SI, TrueVal);
9231 else
9232 return ReplaceInstUsesWith(SI, FalseVal);
9233 }
9234
Owen Anderson1d0be152009-08-13 21:58:54 +00009235 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009236 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009237 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009238 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009239 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009240 } else {
9241 // Change: A = select B, false, C --> A = and !B, C
9242 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009243 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009244 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009245 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009246 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009247 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009248 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009249 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009250 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009251 } else {
9252 // Change: A = select B, C, true --> A = or !B, C
9253 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009254 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009255 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009256 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009257 }
9258 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009259
9260 // select a, b, a -> a&b
9261 // select a, a, b -> a|b
9262 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009263 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009264 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009265 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009266 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009267
Chris Lattner2eefe512004-04-09 19:05:30 +00009268 // Selecting between two integer constants?
9269 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9270 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009271 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009272 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009273 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009274 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009275 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009276 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009277 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009278 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009279 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009280 }
Chris Lattner457dd822004-06-09 07:59:58 +00009281
Reid Spencere4d87aa2006-12-23 06:05:41 +00009282 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009283 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009284 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009285 // non-constant value, eliminate this whole mess. This corresponds to
9286 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009287 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009288 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009289 cast<Constant>(IC->getOperand(1))->isNullValue())
9290 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9291 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009292 isa<ConstantInt>(ICA->getOperand(1)) &&
9293 (ICA->getOperand(1) == TrueValC ||
9294 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009295 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9296 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009297 // know whether we have a icmp_ne or icmp_eq and whether the
9298 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009299 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009300 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009301 Value *V = ICA;
9302 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009303 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009304 Instruction::Xor, V, ICA->getOperand(1)), SI);
9305 return ReplaceInstUsesWith(SI, V);
9306 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009307 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009308 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009309
9310 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009311 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9312 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009313 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009314 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9315 // This is not safe in general for floating point:
9316 // consider X== -0, Y== +0.
9317 // It becomes safe if either operand is a nonzero constant.
9318 ConstantFP *CFPt, *CFPf;
9319 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9320 !CFPt->getValueAPF().isZero()) ||
9321 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9322 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009323 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009324 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009325 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009326 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009327 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009328 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009329
Reid Spencere4d87aa2006-12-23 06:05:41 +00009330 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009331 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009332 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9333 // This is not safe in general for floating point:
9334 // consider X== -0, Y== +0.
9335 // It becomes safe if either operand is a nonzero constant.
9336 ConstantFP *CFPt, *CFPf;
9337 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9338 !CFPt->getValueAPF().isZero()) ||
9339 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9340 !CFPf->getValueAPF().isZero()))
9341 return ReplaceInstUsesWith(SI, FalseVal);
9342 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009343 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009344 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9345 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009346 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009347 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009348 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009349 }
9350
9351 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009352 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9353 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9354 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009355
Chris Lattner87875da2005-01-13 22:52:24 +00009356 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9357 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9358 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009359 Instruction *AddOp = 0, *SubOp = 0;
9360
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009361 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9362 if (TI->getOpcode() == FI->getOpcode())
9363 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9364 return IV;
9365
9366 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9367 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009368 if ((TI->getOpcode() == Instruction::Sub &&
9369 FI->getOpcode() == Instruction::Add) ||
9370 (TI->getOpcode() == Instruction::FSub &&
9371 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009372 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009373 } else if ((FI->getOpcode() == Instruction::Sub &&
9374 TI->getOpcode() == Instruction::Add) ||
9375 (FI->getOpcode() == Instruction::FSub &&
9376 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009377 AddOp = TI; SubOp = FI;
9378 }
9379
9380 if (AddOp) {
9381 Value *OtherAddOp = 0;
9382 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9383 OtherAddOp = AddOp->getOperand(1);
9384 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9385 OtherAddOp = AddOp->getOperand(0);
9386 }
9387
9388 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009389 // So at this point we know we have (Y -> OtherAddOp):
9390 // select C, (add X, Y), (sub X, Z)
9391 Value *NegVal; // Compute -Z
9392 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009393 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009394 } else {
9395 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009396 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009397 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009398 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009399
9400 Value *NewTrueOp = OtherAddOp;
9401 Value *NewFalseOp = NegVal;
9402 if (AddOp != TI)
9403 std::swap(NewTrueOp, NewFalseOp);
9404 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009405 SelectInst::Create(CondVal, NewTrueOp,
9406 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009407
9408 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009409 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009410 }
9411 }
9412 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009413
Chris Lattnere576b912004-04-09 23:46:01 +00009414 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009415 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009416 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9417 if (FoldI)
9418 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009419 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009420
9421 if (BinaryOperator::isNot(CondVal)) {
9422 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9423 SI.setOperand(1, FalseVal);
9424 SI.setOperand(2, TrueVal);
9425 return &SI;
9426 }
9427
Chris Lattner3d69f462004-03-12 05:52:32 +00009428 return 0;
9429}
9430
Dan Gohmaneee962e2008-04-10 18:43:06 +00009431/// EnforceKnownAlignment - If the specified pointer points to an object that
9432/// we control, modify the object's alignment to PrefAlign. This isn't
9433/// often possible though. If alignment is important, a more reliable approach
9434/// is to simply align all global variables and allocation instructions to
9435/// their preferred alignment from the beginning.
9436///
9437static unsigned EnforceKnownAlignment(Value *V,
9438 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009439
Dan Gohmaneee962e2008-04-10 18:43:06 +00009440 User *U = dyn_cast<User>(V);
9441 if (!U) return Align;
9442
Dan Gohmanca178902009-07-17 20:47:02 +00009443 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009444 default: break;
9445 case Instruction::BitCast:
9446 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9447 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009448 // If all indexes are zero, it is just the alignment of the base pointer.
9449 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009450 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009451 if (!isa<Constant>(*i) ||
9452 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009453 AllZeroOperands = false;
9454 break;
9455 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009456
9457 if (AllZeroOperands) {
9458 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009459 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009460 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009461 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009462 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009463 }
9464
9465 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9466 // If there is a large requested alignment and we can, bump up the alignment
9467 // of the global.
9468 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009469 if (GV->getAlignment() >= PrefAlign)
9470 Align = GV->getAlignment();
9471 else {
9472 GV->setAlignment(PrefAlign);
9473 Align = PrefAlign;
9474 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009475 }
9476 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9477 // If there is a requested alignment and if this is an alloca, round up. We
9478 // don't do this for malloc, because some systems can't respect the request.
9479 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009480 if (AI->getAlignment() >= PrefAlign)
9481 Align = AI->getAlignment();
9482 else {
9483 AI->setAlignment(PrefAlign);
9484 Align = PrefAlign;
9485 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009486 }
9487 }
9488
9489 return Align;
9490}
9491
9492/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9493/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9494/// and it is more than the alignment of the ultimate object, see if we can
9495/// increase the alignment of the ultimate object, making this check succeed.
9496unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9497 unsigned PrefAlign) {
9498 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9499 sizeof(PrefAlign) * CHAR_BIT;
9500 APInt Mask = APInt::getAllOnesValue(BitWidth);
9501 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9502 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9503 unsigned TrailZ = KnownZero.countTrailingOnes();
9504 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9505
9506 if (PrefAlign > Align)
9507 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9508
9509 // We don't need to make any adjustment.
9510 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009511}
9512
Chris Lattnerf497b022008-01-13 23:50:23 +00009513Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009514 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009515 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009516 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009517 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009518
9519 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009520 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009521 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009522 return MI;
9523 }
9524
9525 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9526 // load/store.
9527 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9528 if (MemOpLength == 0) return 0;
9529
Chris Lattner37ac6082008-01-14 00:28:35 +00009530 // Source and destination pointer types are always "i8*" for intrinsic. See
9531 // if the size is something we can handle with a single primitive load/store.
9532 // A single load+store correctly handles overlapping memory in the memmove
9533 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009534 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009535 if (Size == 0) return MI; // Delete this mem transfer.
9536
9537 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009538 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009539
Chris Lattner37ac6082008-01-14 00:28:35 +00009540 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009541 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009542 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009543
9544 // Memcpy forces the use of i8* for the source and destination. That means
9545 // that if you're using memcpy to move one double around, you'll get a cast
9546 // from double* to i8*. We'd much rather use a double load+store rather than
9547 // an i64 load+store, here because this improves the odds that the source or
9548 // dest address will be promotable. See if we can find a better type than the
9549 // integer datatype.
9550 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9551 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009552 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009553 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9554 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009555 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009556 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9557 if (STy->getNumElements() == 1)
9558 SrcETy = STy->getElementType(0);
9559 else
9560 break;
9561 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9562 if (ATy->getNumElements() == 1)
9563 SrcETy = ATy->getElementType();
9564 else
9565 break;
9566 } else
9567 break;
9568 }
9569
Dan Gohman8f8e2692008-05-23 01:52:21 +00009570 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009571 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009572 }
9573 }
9574
9575
Chris Lattnerf497b022008-01-13 23:50:23 +00009576 // If the memcpy/memmove provides better alignment info than we can
9577 // infer, use it.
9578 SrcAlign = std::max(SrcAlign, CopyAlign);
9579 DstAlign = std::max(DstAlign, CopyAlign);
9580
Chris Lattner08142f22009-08-30 19:47:22 +00009581 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9582 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009583 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9584 InsertNewInstBefore(L, *MI);
9585 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9586
9587 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009588 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009589 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009590}
Chris Lattner3d69f462004-03-12 05:52:32 +00009591
Chris Lattner69ea9d22008-04-30 06:39:11 +00009592Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9593 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009594 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009595 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009596 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009597 return MI;
9598 }
9599
9600 // Extract the length and alignment and fill if they are constant.
9601 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9602 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009603 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009604 return 0;
9605 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009606 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009607
9608 // If the length is zero, this is a no-op
9609 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9610
9611 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9612 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009613 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009614
9615 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009616 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009617
9618 // Alignment 0 is identity for alignment 1 for memset, but not store.
9619 if (Alignment == 0) Alignment = 1;
9620
9621 // Extract the fill value and store.
9622 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009623 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009624 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009625
9626 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009627 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009628 return MI;
9629 }
9630
9631 return 0;
9632}
9633
9634
Chris Lattner8b0ea312006-01-13 20:11:04 +00009635/// visitCallInst - CallInst simplification. This mostly only handles folding
9636/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9637/// the heavy lifting.
9638///
Chris Lattner9fe38862003-06-19 17:00:31 +00009639Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009640 // If the caller function is nounwind, mark the call as nounwind, even if the
9641 // callee isn't.
9642 if (CI.getParent()->getParent()->doesNotThrow() &&
9643 !CI.doesNotThrow()) {
9644 CI.setDoesNotThrow();
9645 return &CI;
9646 }
9647
Chris Lattner8b0ea312006-01-13 20:11:04 +00009648 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9649 if (!II) return visitCallSite(&CI);
9650
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009651 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9652 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009653 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009654 bool Changed = false;
9655
9656 // memmove/cpy/set of zero bytes is a noop.
9657 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9658 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9659
Chris Lattner35b9e482004-10-12 04:52:52 +00009660 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009661 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009662 // Replace the instruction with just byte operations. We would
9663 // transform other cases to loads/stores, but we don't know if
9664 // alignment is sufficient.
9665 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009666 }
9667
Chris Lattner35b9e482004-10-12 04:52:52 +00009668 // If we have a memmove and the source operation is a constant global,
9669 // then the source and dest pointers can't alias, so we can change this
9670 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009671 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009672 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9673 if (GVSrc->isConstant()) {
9674 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009675 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9676 const Type *Tys[1];
9677 Tys[0] = CI.getOperand(3)->getType();
9678 CI.setOperand(0,
9679 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009680 Changed = true;
9681 }
Chris Lattnera935db82008-05-28 05:30:41 +00009682
9683 // memmove(x,x,size) -> noop.
9684 if (MMI->getSource() == MMI->getDest())
9685 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009686 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009687
Chris Lattner95a959d2006-03-06 20:18:44 +00009688 // If we can determine a pointer alignment that is bigger than currently
9689 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009690 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009691 if (Instruction *I = SimplifyMemTransfer(MI))
9692 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009693 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9694 if (Instruction *I = SimplifyMemSet(MSI))
9695 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009696 }
9697
Chris Lattner8b0ea312006-01-13 20:11:04 +00009698 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009699 }
9700
9701 switch (II->getIntrinsicID()) {
9702 default: break;
9703 case Intrinsic::bswap:
9704 // bswap(bswap(x)) -> x
9705 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9706 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9707 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9708 break;
9709 case Intrinsic::ppc_altivec_lvx:
9710 case Intrinsic::ppc_altivec_lvxl:
9711 case Intrinsic::x86_sse_loadu_ps:
9712 case Intrinsic::x86_sse2_loadu_pd:
9713 case Intrinsic::x86_sse2_loadu_dq:
9714 // Turn PPC lvx -> load if the pointer is known aligned.
9715 // Turn X86 loadups -> load if the pointer is known aligned.
9716 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009717 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9718 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009719 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009720 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009721 break;
9722 case Intrinsic::ppc_altivec_stvx:
9723 case Intrinsic::ppc_altivec_stvxl:
9724 // Turn stvx -> store if the pointer is known aligned.
9725 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9726 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009727 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009728 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009729 return new StoreInst(II->getOperand(1), Ptr);
9730 }
9731 break;
9732 case Intrinsic::x86_sse_storeu_ps:
9733 case Intrinsic::x86_sse2_storeu_pd:
9734 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009735 // Turn X86 storeu -> store if the pointer is known aligned.
9736 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9737 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009738 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009739 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009740 return new StoreInst(II->getOperand(2), Ptr);
9741 }
9742 break;
9743
9744 case Intrinsic::x86_sse_cvttss2si: {
9745 // These intrinsics only demands the 0th element of its input vector. If
9746 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009747 unsigned VWidth =
9748 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9749 APInt DemandedElts(VWidth, 1);
9750 APInt UndefElts(VWidth, 0);
9751 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009752 UndefElts)) {
9753 II->setOperand(1, V);
9754 return II;
9755 }
9756 break;
9757 }
9758
9759 case Intrinsic::ppc_altivec_vperm:
9760 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9761 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9762 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009763
Chris Lattner0521e3c2008-06-18 04:33:20 +00009764 // Check that all of the elements are integer constants or undefs.
9765 bool AllEltsOk = true;
9766 for (unsigned i = 0; i != 16; ++i) {
9767 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9768 !isa<UndefValue>(Mask->getOperand(i))) {
9769 AllEltsOk = false;
9770 break;
9771 }
9772 }
9773
9774 if (AllEltsOk) {
9775 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009776 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9777 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009778 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009779
Chris Lattner0521e3c2008-06-18 04:33:20 +00009780 // Only extract each element once.
9781 Value *ExtractedElts[32];
9782 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9783
Chris Lattnere2ed0572006-04-06 19:19:17 +00009784 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009785 if (isa<UndefValue>(Mask->getOperand(i)))
9786 continue;
9787 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9788 Idx &= 31; // Match the hardware behavior.
9789
9790 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009791 ExtractedElts[Idx] =
9792 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9793 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9794 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009795 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009796
Chris Lattner0521e3c2008-06-18 04:33:20 +00009797 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009798 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9799 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9800 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009801 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009802 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009803 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009804 }
9805 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009806
Chris Lattner0521e3c2008-06-18 04:33:20 +00009807 case Intrinsic::stackrestore: {
9808 // If the save is right next to the restore, remove the restore. This can
9809 // happen when variable allocas are DCE'd.
9810 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9811 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9812 BasicBlock::iterator BI = SS;
9813 if (&*++BI == II)
9814 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009815 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009816 }
9817
9818 // Scan down this block to see if there is another stack restore in the
9819 // same block without an intervening call/alloca.
9820 BasicBlock::iterator BI = II;
9821 TerminatorInst *TI = II->getParent()->getTerminator();
9822 bool CannotRemove = false;
9823 for (++BI; &*BI != TI; ++BI) {
9824 if (isa<AllocaInst>(BI)) {
9825 CannotRemove = true;
9826 break;
9827 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009828 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9829 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9830 // If there is a stackrestore below this one, remove this one.
9831 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9832 return EraseInstFromFunction(CI);
9833 // Otherwise, ignore the intrinsic.
9834 } else {
9835 // If we found a non-intrinsic call, we can't remove the stack
9836 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009837 CannotRemove = true;
9838 break;
9839 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009840 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009841 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009842
9843 // If the stack restore is in a return/unwind block and if there are no
9844 // allocas or calls between the restore and the return, nuke the restore.
9845 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9846 return EraseInstFromFunction(CI);
9847 break;
9848 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009849 }
9850
Chris Lattner8b0ea312006-01-13 20:11:04 +00009851 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009852}
9853
9854// InvokeInst simplification
9855//
9856Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009857 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009858}
9859
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009860/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9861/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009862static bool isSafeToEliminateVarargsCast(const CallSite CS,
9863 const CastInst * const CI,
9864 const TargetData * const TD,
9865 const int ix) {
9866 if (!CI->isLosslessCast())
9867 return false;
9868
9869 // The size of ByVal arguments is derived from the type, so we
9870 // can't change to a type with a different size. If the size were
9871 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009872 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009873 return true;
9874
9875 const Type* SrcTy =
9876 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9877 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9878 if (!SrcTy->isSized() || !DstTy->isSized())
9879 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009880 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009881 return false;
9882 return true;
9883}
9884
Chris Lattnera44d8a22003-10-07 22:32:43 +00009885// visitCallSite - Improvements for call and invoke instructions.
9886//
9887Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009888 bool Changed = false;
9889
9890 // If the callee is a constexpr cast of a function, attempt to move the cast
9891 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009892 if (transformConstExprCastCall(CS)) return 0;
9893
Chris Lattner6c266db2003-10-07 22:54:13 +00009894 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009895
Chris Lattner08b22ec2005-05-13 07:09:09 +00009896 if (Function *CalleeF = dyn_cast<Function>(Callee))
9897 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9898 Instruction *OldCall = CS.getInstruction();
9899 // If the call and callee calling conventions don't match, this call must
9900 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +00009901 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009902 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Andersond672ecb2009-07-03 00:17:18 +00009903 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009904 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009905 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009906 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9907 return EraseInstFromFunction(*OldCall);
9908 return 0;
9909 }
9910
Chris Lattner17be6352004-10-18 02:59:09 +00009911 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9912 // This instruction is not reachable, just remove it. We insert a store to
9913 // undef so that we know that this code is not reachable, despite the fact
9914 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +00009915 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009916 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Chris Lattner17be6352004-10-18 02:59:09 +00009917 CS.getInstruction());
9918
9919 if (!CS.getInstruction()->use_empty())
9920 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009921 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009922
9923 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9924 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009925 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +00009926 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009927 }
Chris Lattner17be6352004-10-18 02:59:09 +00009928 return EraseInstFromFunction(*CS.getInstruction());
9929 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009930
Duncan Sandscdb6d922007-09-17 10:26:40 +00009931 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9932 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9933 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9934 return transformCallThroughTrampoline(CS);
9935
Chris Lattner6c266db2003-10-07 22:54:13 +00009936 const PointerType *PTy = cast<PointerType>(Callee->getType());
9937 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9938 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009939 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009940 // See if we can optimize any arguments passed through the varargs area of
9941 // the call.
9942 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009943 E = CS.arg_end(); I != E; ++I, ++ix) {
9944 CastInst *CI = dyn_cast<CastInst>(*I);
9945 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9946 *I = CI->getOperand(0);
9947 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009948 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009949 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009950 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009951
Duncan Sandsf0c33542007-12-19 21:13:37 +00009952 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009953 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009954 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009955 Changed = true;
9956 }
9957
Chris Lattner6c266db2003-10-07 22:54:13 +00009958 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009959}
9960
Chris Lattner9fe38862003-06-19 17:00:31 +00009961// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9962// attempt to move the cast to the arguments of the call/invoke.
9963//
9964bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9965 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9966 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009967 if (CE->getOpcode() != Instruction::BitCast ||
9968 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009969 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009970 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009971 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009972 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009973
9974 // Okay, this is a cast from a function to a different type. Unless doing so
9975 // would cause a type conversion of one of our arguments, change this call to
9976 // be a direct call with arguments casted to the appropriate types.
9977 //
9978 const FunctionType *FT = Callee->getFunctionType();
9979 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009980 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009981
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009982 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009983 return false; // TODO: Handle multiple return values.
9984
Chris Lattnerf78616b2004-01-14 06:06:08 +00009985 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009986 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009987 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009988 // Conversion is ok if changing from one pointer type to another or from
9989 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009990 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00009991 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009992 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00009993 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +00009994 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009995
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009996 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009997 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +00009998 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009999 return false; // Cannot transform this return value.
10000
Chris Lattner58d74912008-03-12 17:45:29 +000010001 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010002 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010003 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010004 return false; // Attribute not compatible with transformed value.
10005 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010006
Chris Lattnerf78616b2004-01-14 06:06:08 +000010007 // If the callsite is an invoke instruction, and the return value is used by
10008 // a PHI node in a successor, we cannot change the return type of the call
10009 // because there is no place to put the cast instruction (without breaking
10010 // the critical edge). Bail out in this case.
10011 if (!Caller->use_empty())
10012 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10013 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10014 UI != E; ++UI)
10015 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10016 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010017 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010018 return false;
10019 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010020
10021 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10022 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010023
Chris Lattner9fe38862003-06-19 17:00:31 +000010024 CallSite::arg_iterator AI = CS.arg_begin();
10025 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10026 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010027 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010028
10029 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010030 return false; // Cannot transform this parameter value.
10031
Devang Patel19c87462008-09-26 22:53:05 +000010032 if (CallerPAL.getParamAttributes(i + 1)
10033 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010034 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010035
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010036 // Converting from one pointer type to another or between a pointer and an
10037 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010038 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010039 (TD && ((isa<PointerType>(ParamTy) ||
10040 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10041 (isa<PointerType>(ActTy) ||
10042 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010043 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010044 }
10045
10046 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010047 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010048 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010049
Chris Lattner58d74912008-03-12 17:45:29 +000010050 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10051 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010052 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010053 // won't be dropping them. Check that these extra arguments have attributes
10054 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010055 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10056 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010057 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010058 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010059 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010060 return false;
10061 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010062
Chris Lattner9fe38862003-06-19 17:00:31 +000010063 // Okay, we decided that this is a safe thing to do: go ahead and start
10064 // inserting cast instructions as necessary...
10065 std::vector<Value*> Args;
10066 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010067 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010068 attrVec.reserve(NumCommonArgs);
10069
10070 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010071 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010072
10073 // If the return value is not being used, the type may not be compatible
10074 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010075 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010076
10077 // Add the new return attributes.
10078 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010079 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010080
10081 AI = CS.arg_begin();
10082 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10083 const Type *ParamTy = FT->getParamType(i);
10084 if ((*AI)->getType() == ParamTy) {
10085 Args.push_back(*AI);
10086 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010087 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010088 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010089 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010090 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010091
10092 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010093 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010094 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010095 }
10096
10097 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010098 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010099 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010100 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010101
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010102 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010103 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010104 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010105 errs() << "WARNING: While resolving call to function '"
10106 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010107 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010108 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010109 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10110 const Type *PTy = getPromotedType((*AI)->getType());
10111 if (PTy != (*AI)->getType()) {
10112 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010113 Instruction::CastOps opcode =
10114 CastInst::getCastOpcode(*AI, false, PTy, false);
10115 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010116 } else {
10117 Args.push_back(*AI);
10118 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010119
Duncan Sandse1e520f2008-01-13 08:02:44 +000010120 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010121 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010122 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010123 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010124 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010125 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010126
Devang Patel19c87462008-09-26 22:53:05 +000010127 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10128 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10129
Owen Anderson1d0be152009-08-13 21:58:54 +000010130 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010131 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010132
Eric Christophera66297a2009-07-25 02:45:27 +000010133 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10134 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010135
Chris Lattner9fe38862003-06-19 17:00:31 +000010136 Instruction *NC;
10137 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010138 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010139 Args.begin(), Args.end(),
10140 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010141 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010142 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010143 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010144 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10145 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010146 CallInst *CI = cast<CallInst>(Caller);
10147 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010148 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010149 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010150 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010151 }
10152
Chris Lattner6934a042007-02-11 01:23:03 +000010153 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010154 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010155 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010156 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010157 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010158 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010159 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010160
10161 // If this is an invoke instruction, we should insert it after the first
10162 // non-phi, instruction in the normal successor block.
10163 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010164 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010165 InsertNewInstBefore(NC, *I);
10166 } else {
10167 // Otherwise, it's a call, just insert cast right after the call instr
10168 InsertNewInstBefore(NC, *Caller);
10169 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010170 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010171 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010172 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010173 }
10174 }
10175
Owen Anderson1d0be152009-08-13 21:58:54 +000010176 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010177 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010178 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010179 Worklist.Remove(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010180 return true;
10181}
10182
Duncan Sandscdb6d922007-09-17 10:26:40 +000010183// transformCallThroughTrampoline - Turn a call to a function created by the
10184// init_trampoline intrinsic into a direct call to the underlying function.
10185//
10186Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10187 Value *Callee = CS.getCalledValue();
10188 const PointerType *PTy = cast<PointerType>(Callee->getType());
10189 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010190 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010191
10192 // If the call already has the 'nest' attribute somewhere then give up -
10193 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010194 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010195 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010196
10197 IntrinsicInst *Tramp =
10198 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10199
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010200 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010201 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10202 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10203
Devang Patel05988662008-09-25 21:00:45 +000010204 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010205 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010206 unsigned NestIdx = 1;
10207 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010208 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010209
10210 // Look for a parameter marked with the 'nest' attribute.
10211 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10212 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010213 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010214 // Record the parameter type and any other attributes.
10215 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010216 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010217 break;
10218 }
10219
10220 if (NestTy) {
10221 Instruction *Caller = CS.getInstruction();
10222 std::vector<Value*> NewArgs;
10223 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10224
Devang Patel05988662008-09-25 21:00:45 +000010225 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010226 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010227
Duncan Sandscdb6d922007-09-17 10:26:40 +000010228 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010229 // mean appending it. Likewise for attributes.
10230
Devang Patel19c87462008-09-26 22:53:05 +000010231 // Add any result attributes.
10232 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010233 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010234
Duncan Sandscdb6d922007-09-17 10:26:40 +000010235 {
10236 unsigned Idx = 1;
10237 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10238 do {
10239 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010240 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010241 Value *NestVal = Tramp->getOperand(3);
10242 if (NestVal->getType() != NestTy)
10243 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10244 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010245 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010246 }
10247
10248 if (I == E)
10249 break;
10250
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010251 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010252 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010253 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010254 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010255 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010256
10257 ++Idx, ++I;
10258 } while (1);
10259 }
10260
Devang Patel19c87462008-09-26 22:53:05 +000010261 // Add any function attributes.
10262 if (Attributes Attr = Attrs.getFnAttributes())
10263 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10264
Duncan Sandscdb6d922007-09-17 10:26:40 +000010265 // The trampoline may have been bitcast to a bogus type (FTy).
10266 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010267 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010268
Duncan Sandscdb6d922007-09-17 10:26:40 +000010269 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010270 NewTypes.reserve(FTy->getNumParams()+1);
10271
Duncan Sandscdb6d922007-09-17 10:26:40 +000010272 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010273 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010274 {
10275 unsigned Idx = 1;
10276 FunctionType::param_iterator I = FTy->param_begin(),
10277 E = FTy->param_end();
10278
10279 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010280 if (Idx == NestIdx)
10281 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010282 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010283
10284 if (I == E)
10285 break;
10286
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010287 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010288 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010289
10290 ++Idx, ++I;
10291 } while (1);
10292 }
10293
10294 // Replace the trampoline call with a direct call. Let the generic
10295 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010296 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010297 FTy->isVarArg());
10298 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010299 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010300 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010301 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010302 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10303 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010304
10305 Instruction *NewCaller;
10306 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010307 NewCaller = InvokeInst::Create(NewCallee,
10308 II->getNormalDest(), II->getUnwindDest(),
10309 NewArgs.begin(), NewArgs.end(),
10310 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010311 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010312 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010313 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010314 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10315 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010316 if (cast<CallInst>(Caller)->isTailCall())
10317 cast<CallInst>(NewCaller)->setTailCall();
10318 cast<CallInst>(NewCaller)->
10319 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010320 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010321 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010322 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010323 Caller->replaceAllUsesWith(NewCaller);
10324 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010325 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010326 return 0;
10327 }
10328 }
10329
10330 // Replace the trampoline call with a direct call. Since there is no 'nest'
10331 // parameter, there is no need to adjust the argument list. Let the generic
10332 // code sort out any function type mismatches.
10333 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010334 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010335 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010336 CS.setCalledFunction(NewCallee);
10337 return CS.getInstruction();
10338}
10339
Chris Lattner7da52b22006-11-01 04:51:18 +000010340/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10341/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10342/// and a single binop.
10343Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10344 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010345 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010346 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010347 Value *LHSVal = FirstInst->getOperand(0);
10348 Value *RHSVal = FirstInst->getOperand(1);
10349
10350 const Type *LHSType = LHSVal->getType();
10351 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010352
10353 // Scan to see if all operands are the same opcode, all have one use, and all
10354 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010355 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010356 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010357 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010358 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010359 // types or GEP's with different index types.
10360 I->getOperand(0)->getType() != LHSType ||
10361 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010362 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010363
10364 // If they are CmpInst instructions, check their predicates
10365 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10366 if (cast<CmpInst>(I)->getPredicate() !=
10367 cast<CmpInst>(FirstInst)->getPredicate())
10368 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010369
10370 // Keep track of which operand needs a phi node.
10371 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10372 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010373 }
10374
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010375 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010376
Chris Lattner7da52b22006-11-01 04:51:18 +000010377 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010378 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010379 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010380 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010381 NewLHS = PHINode::Create(LHSType,
10382 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010383 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10384 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010385 InsertNewInstBefore(NewLHS, PN);
10386 LHSVal = NewLHS;
10387 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010388
10389 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010390 NewRHS = PHINode::Create(RHSType,
10391 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010392 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10393 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010394 InsertNewInstBefore(NewRHS, PN);
10395 RHSVal = NewRHS;
10396 }
10397
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010398 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010399 if (NewLHS || NewRHS) {
10400 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10401 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10402 if (NewLHS) {
10403 Value *NewInLHS = InInst->getOperand(0);
10404 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10405 }
10406 if (NewRHS) {
10407 Value *NewInRHS = InInst->getOperand(1);
10408 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10409 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010410 }
10411 }
10412
Chris Lattner7da52b22006-11-01 04:51:18 +000010413 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010414 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010415 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010416 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010417 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010418}
10419
Chris Lattner05f18922008-12-01 02:34:36 +000010420Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10421 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10422
10423 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10424 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010425 // This is true if all GEP bases are allocas and if all indices into them are
10426 // constants.
10427 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010428
10429 // Scan to see if all operands are the same opcode, all have one use, and all
10430 // kill their operands (i.e. the operands have one use).
10431 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10432 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10433 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10434 GEP->getNumOperands() != FirstInst->getNumOperands())
10435 return 0;
10436
Chris Lattner36d3e322009-02-21 00:46:50 +000010437 // Keep track of whether or not all GEPs are of alloca pointers.
10438 if (AllBasePointersAreAllocas &&
10439 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10440 !GEP->hasAllConstantIndices()))
10441 AllBasePointersAreAllocas = false;
10442
Chris Lattner05f18922008-12-01 02:34:36 +000010443 // Compare the operand lists.
10444 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10445 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10446 continue;
10447
10448 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10449 // if one of the PHIs has a constant for the index. The index may be
10450 // substantially cheaper to compute for the constants, so making it a
10451 // variable index could pessimize the path. This also handles the case
10452 // for struct indices, which must always be constant.
10453 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10454 isa<ConstantInt>(GEP->getOperand(op)))
10455 return 0;
10456
10457 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10458 return 0;
10459 FixedOperands[op] = 0; // Needs a PHI.
10460 }
10461 }
10462
Chris Lattner36d3e322009-02-21 00:46:50 +000010463 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010464 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010465 // offset calculation, but all the predecessors will have to materialize the
10466 // stack address into a register anyway. We'd actually rather *clone* the
10467 // load up into the predecessors so that we have a load of a gep of an alloca,
10468 // which can usually all be folded into the load.
10469 if (AllBasePointersAreAllocas)
10470 return 0;
10471
Chris Lattner05f18922008-12-01 02:34:36 +000010472 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10473 // that is variable.
10474 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10475
10476 bool HasAnyPHIs = false;
10477 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10478 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10479 Value *FirstOp = FirstInst->getOperand(i);
10480 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10481 FirstOp->getName()+".pn");
10482 InsertNewInstBefore(NewPN, PN);
10483
10484 NewPN->reserveOperandSpace(e);
10485 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10486 OperandPhis[i] = NewPN;
10487 FixedOperands[i] = NewPN;
10488 HasAnyPHIs = true;
10489 }
10490
10491
10492 // Add all operands to the new PHIs.
10493 if (HasAnyPHIs) {
10494 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10495 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10496 BasicBlock *InBB = PN.getIncomingBlock(i);
10497
10498 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10499 if (PHINode *OpPhi = OperandPhis[op])
10500 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10501 }
10502 }
10503
10504 Value *Base = FixedOperands[0];
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010505 GetElementPtrInst *GEP =
10506 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10507 FixedOperands.end());
10508 if (cast<GEPOperator>(FirstInst)->isInBounds())
10509 cast<GEPOperator>(GEP)->setIsInBounds(true);
10510 return GEP;
Chris Lattner05f18922008-12-01 02:34:36 +000010511}
10512
10513
Chris Lattner21550882009-02-23 05:56:17 +000010514/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10515/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010516/// obvious the value of the load is not changed from the point of the load to
10517/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010518///
10519/// Finally, it is safe, but not profitable, to sink a load targetting a
10520/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10521/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010522static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010523 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10524
10525 for (++BBI; BBI != E; ++BBI)
10526 if (BBI->mayWriteToMemory())
10527 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010528
10529 // Check for non-address taken alloca. If not address-taken already, it isn't
10530 // profitable to do this xform.
10531 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10532 bool isAddressTaken = false;
10533 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10534 UI != E; ++UI) {
10535 if (isa<LoadInst>(UI)) continue;
10536 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10537 // If storing TO the alloca, then the address isn't taken.
10538 if (SI->getOperand(1) == AI) continue;
10539 }
10540 isAddressTaken = true;
10541 break;
10542 }
10543
Chris Lattner36d3e322009-02-21 00:46:50 +000010544 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010545 return false;
10546 }
10547
Chris Lattner36d3e322009-02-21 00:46:50 +000010548 // If this load is a load from a GEP with a constant offset from an alloca,
10549 // then we don't want to sink it. In its present form, it will be
10550 // load [constant stack offset]. Sinking it will cause us to have to
10551 // materialize the stack addresses in each predecessor in a register only to
10552 // do a shared load from register in the successor.
10553 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10554 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10555 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10556 return false;
10557
Chris Lattner76c73142006-11-01 07:13:54 +000010558 return true;
10559}
10560
Chris Lattner9fe38862003-06-19 17:00:31 +000010561
Chris Lattnerbac32862004-11-14 19:13:23 +000010562// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10563// operator and they all are only used by the PHI, PHI together their
10564// inputs, and do the operation once, to the result of the PHI.
10565Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10566 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10567
10568 // Scan the instruction, looking for input operations that can be folded away.
10569 // If all input operands to the phi are the same instruction (e.g. a cast from
10570 // the same type or "+42") we can pull the operation through the PHI, reducing
10571 // code size and simplifying code.
10572 Constant *ConstantOp = 0;
10573 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010574 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010575 if (isa<CastInst>(FirstInst)) {
10576 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010577 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010578 // Can fold binop, compare or shift here if the RHS is a constant,
10579 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010580 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010581 if (ConstantOp == 0)
10582 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010583 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10584 isVolatile = LI->isVolatile();
10585 // We can't sink the load if the loaded value could be modified between the
10586 // load and the PHI.
10587 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010588 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010589 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010590
10591 // If the PHI is of volatile loads and the load block has multiple
10592 // successors, sinking it would remove a load of the volatile value from
10593 // the path through the other successor.
10594 if (isVolatile &&
10595 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10596 return 0;
10597
Chris Lattner9c080502006-11-01 07:43:41 +000010598 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010599 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010600 } else {
10601 return 0; // Cannot fold this operation.
10602 }
10603
10604 // Check to see if all arguments are the same operation.
10605 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10606 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10607 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010608 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010609 return 0;
10610 if (CastSrcTy) {
10611 if (I->getOperand(0)->getType() != CastSrcTy)
10612 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010613 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010614 // We can't sink the load if the loaded value could be modified between
10615 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010616 if (LI->isVolatile() != isVolatile ||
10617 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010618 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010619 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010620
Chris Lattner71042962008-07-08 17:18:32 +000010621 // If the PHI is of volatile loads and the load block has multiple
10622 // successors, sinking it would remove a load of the volatile value from
10623 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010624 if (isVolatile &&
10625 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10626 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010627
Chris Lattnerbac32862004-11-14 19:13:23 +000010628 } else if (I->getOperand(1) != ConstantOp) {
10629 return 0;
10630 }
10631 }
10632
10633 // Okay, they are all the same operation. Create a new PHI node of the
10634 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010635 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10636 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010637 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010638
10639 Value *InVal = FirstInst->getOperand(0);
10640 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010641
10642 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010643 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10644 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10645 if (NewInVal != InVal)
10646 InVal = 0;
10647 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10648 }
10649
10650 Value *PhiVal;
10651 if (InVal) {
10652 // The new PHI unions all of the same values together. This is really
10653 // common, so we handle it intelligently here for compile-time speed.
10654 PhiVal = InVal;
10655 delete NewPN;
10656 } else {
10657 InsertNewInstBefore(NewPN, PN);
10658 PhiVal = NewPN;
10659 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010660
Chris Lattnerbac32862004-11-14 19:13:23 +000010661 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010662 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010663 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010664 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010665 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010666 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010667 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010668 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010669 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10670
10671 // If this was a volatile load that we are merging, make sure to loop through
10672 // and mark all the input loads as non-volatile. If we don't do this, we will
10673 // insert a new volatile load and the old ones will not be deletable.
10674 if (isVolatile)
10675 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10676 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10677
10678 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010679}
Chris Lattnera1be5662002-05-02 17:06:02 +000010680
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010681/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10682/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010683static bool DeadPHICycle(PHINode *PN,
10684 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010685 if (PN->use_empty()) return true;
10686 if (!PN->hasOneUse()) return false;
10687
10688 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010689 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010690 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010691
10692 // Don't scan crazily complex things.
10693 if (PotentiallyDeadPHIs.size() == 16)
10694 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010695
10696 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10697 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010698
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010699 return false;
10700}
10701
Chris Lattnercf5008a2007-11-06 21:52:06 +000010702/// PHIsEqualValue - Return true if this phi node is always equal to
10703/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10704/// z = some value; x = phi (y, z); y = phi (x, z)
10705static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10706 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10707 // See if we already saw this PHI node.
10708 if (!ValueEqualPHIs.insert(PN))
10709 return true;
10710
10711 // Don't scan crazily complex things.
10712 if (ValueEqualPHIs.size() == 16)
10713 return false;
10714
10715 // Scan the operands to see if they are either phi nodes or are equal to
10716 // the value.
10717 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10718 Value *Op = PN->getIncomingValue(i);
10719 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10720 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10721 return false;
10722 } else if (Op != NonPhiInVal)
10723 return false;
10724 }
10725
10726 return true;
10727}
10728
10729
Chris Lattner473945d2002-05-06 18:06:38 +000010730// PHINode simplification
10731//
Chris Lattner7e708292002-06-25 16:13:24 +000010732Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010733 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010734 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010735
Owen Anderson7e057142006-07-10 22:03:18 +000010736 if (Value *V = PN.hasConstantValue())
10737 return ReplaceInstUsesWith(PN, V);
10738
Owen Anderson7e057142006-07-10 22:03:18 +000010739 // If all PHI operands are the same operation, pull them through the PHI,
10740 // reducing code size.
10741 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010742 isa<Instruction>(PN.getIncomingValue(1)) &&
10743 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10744 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10745 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10746 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010747 PN.getIncomingValue(0)->hasOneUse())
10748 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10749 return Result;
10750
10751 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10752 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10753 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010754 if (PN.hasOneUse()) {
10755 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10756 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010757 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010758 PotentiallyDeadPHIs.insert(&PN);
10759 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010760 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010761 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010762
10763 // If this phi has a single use, and if that use just computes a value for
10764 // the next iteration of a loop, delete the phi. This occurs with unused
10765 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10766 // common case here is good because the only other things that catch this
10767 // are induction variable analysis (sometimes) and ADCE, which is only run
10768 // late.
10769 if (PHIUser->hasOneUse() &&
10770 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10771 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010772 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010773 }
10774 }
Owen Anderson7e057142006-07-10 22:03:18 +000010775
Chris Lattnercf5008a2007-11-06 21:52:06 +000010776 // We sometimes end up with phi cycles that non-obviously end up being the
10777 // same value, for example:
10778 // z = some value; x = phi (y, z); y = phi (x, z)
10779 // where the phi nodes don't necessarily need to be in the same block. Do a
10780 // quick check to see if the PHI node only contains a single non-phi value, if
10781 // so, scan to see if the phi cycle is actually equal to that value.
10782 {
10783 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10784 // Scan for the first non-phi operand.
10785 while (InValNo != NumOperandVals &&
10786 isa<PHINode>(PN.getIncomingValue(InValNo)))
10787 ++InValNo;
10788
10789 if (InValNo != NumOperandVals) {
10790 Value *NonPhiInVal = PN.getOperand(InValNo);
10791
10792 // Scan the rest of the operands to see if there are any conflicts, if so
10793 // there is no need to recursively scan other phis.
10794 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10795 Value *OpVal = PN.getIncomingValue(InValNo);
10796 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10797 break;
10798 }
10799
10800 // If we scanned over all operands, then we have one unique value plus
10801 // phi values. Scan PHI nodes to see if they all merge in each other or
10802 // the value.
10803 if (InValNo == NumOperandVals) {
10804 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10805 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10806 return ReplaceInstUsesWith(PN, NonPhiInVal);
10807 }
10808 }
10809 }
Chris Lattner60921c92003-12-19 05:58:40 +000010810 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010811}
10812
Chris Lattner7e708292002-06-25 16:13:24 +000010813Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010814 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010815 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010816 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010817 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010818 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010819
Chris Lattnere87597f2004-10-16 18:11:37 +000010820 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010821 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010822
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010823 bool HasZeroPointerIndex = false;
10824 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10825 HasZeroPointerIndex = C->isNullValue();
10826
10827 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010828 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010829
Chris Lattner28977af2004-04-05 01:30:19 +000010830 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010831 if (TD) {
10832 bool MadeChange = false;
10833 unsigned PtrSize = TD->getPointerSizeInBits();
10834
10835 gep_type_iterator GTI = gep_type_begin(GEP);
10836 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10837 I != E; ++I, ++GTI) {
10838 if (!isa<SequentialType>(*GTI)) continue;
10839
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010840 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010841 // to what we need. If narrower, sign-extend it to what we need. This
10842 // explicit cast can make subsequent optimizations more obvious.
10843 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10844
10845 if (OpBits == PtrSize)
10846 continue;
10847
10848 Instruction::CastOps Opc =
10849 OpBits > PtrSize ? Instruction::Trunc : Instruction::SExt;
10850 *I = InsertCastBefore(Opc, *I, TD->getIntPtrType(GEP.getContext()), GEP);
10851 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010852 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010853 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010854 }
Chris Lattner28977af2004-04-05 01:30:19 +000010855
Chris Lattner90ac28c2002-08-02 19:29:35 +000010856 // Combine Indices - If the source pointer to this getelementptr instruction
10857 // is a getelementptr instruction, combine the indices of the two
10858 // getelementptr instructions into a single instruction.
10859 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010860 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010861 // Note that if our source is a gep chain itself that we wait for that
10862 // chain to be resolved before we perform this transformation. This
10863 // avoids us creating a TON of code in some cases.
10864 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010865 if (GetElementPtrInst *SrcGEP =
10866 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10867 if (SrcGEP->getNumOperands() == 2)
10868 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010869
Chris Lattner72588fc2007-02-15 22:48:32 +000010870 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010871
10872 // Find out whether the last index in the source GEP is a sequential idx.
10873 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010874 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10875 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010876 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010877
Chris Lattner90ac28c2002-08-02 19:29:35 +000010878 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010879 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010880 // Replace: gep (gep %P, long B), long A, ...
10881 // With: T = long A+B; gep %P, T, ...
10882 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010883 Value *Sum;
10884 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10885 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010886 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010887 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010888 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010889 Sum = SO1;
10890 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010891 // If they aren't the same type, then the input hasn't been processed
10892 // by the loop above yet (which canonicalizes sequential index types to
10893 // intptr_t). Just avoid transforming this until the input has been
10894 // normalized.
10895 if (SO1->getType() != GO1->getType())
10896 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010897 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000010898 }
Chris Lattner620ce142004-05-07 22:09:22 +000010899
Chris Lattnerab984842009-08-30 05:30:55 +000010900 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010901 if (Src->getNumOperands() == 2) {
10902 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000010903 GEP.setOperand(1, Sum);
10904 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000010905 }
Chris Lattnerab984842009-08-30 05:30:55 +000010906 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010907 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000010908 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000010909 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010910 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010911 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010912 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000010913 Indices.append(Src->op_begin()+1, Src->op_end());
10914 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010915 }
10916
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010917 if (!Indices.empty()) {
Chris Lattnerccf4b342009-08-30 04:49:01 +000010918 GetElementPtrInst *NewGEP =
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010919 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000010920 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000010921 if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010922 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10923 return NewGEP;
10924 }
Chris Lattner6e24d832009-08-30 05:00:50 +000010925 }
10926
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010927 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10928 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000010929 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
10930
10931 if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010932 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10933 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010934 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010935 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10936 // into : GEP i8* X, ...
10937 //
Chris Lattnereed48272005-09-13 00:40:14 +000010938 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000010939 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10940 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010941 if (const ArrayType *CATy =
10942 dyn_cast<ArrayType>(CPTy->getElementType())) {
10943 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10944 if (CATy->getElementType() == XTy->getElementType()) {
10945 // -> GEP i8* X, ...
10946 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010947 GetElementPtrInst *NewGEP =
10948 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10949 GEP.getName());
10950 if (cast<GEPOperator>(&GEP)->isInBounds())
10951 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10952 return NewGEP;
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010953 } else if (const ArrayType *XATy =
10954 dyn_cast<ArrayType>(XTy->getElementType())) {
10955 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000010956 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010957 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010958 // At this point, we know that the cast source type is a pointer
10959 // to an array of the same type as the destination pointer
10960 // array. Because the array type is never stepped over (there
10961 // is a leading zero) we can fold the cast into this GEP.
10962 GEP.setOperand(0, X);
10963 return &GEP;
10964 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010965 }
10966 }
Chris Lattnereed48272005-09-13 00:40:14 +000010967 } else if (GEP.getNumOperands() == 2) {
10968 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010969 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10970 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010971 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10972 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010973 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000010974 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10975 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010976 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000010977 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000010978 Idx[1] = GEP.getOperand(1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010979 Value *NewGEP =
10980 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010981 if (cast<GEPOperator>(&GEP)->isInBounds())
10982 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000010983 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010984 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010985 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010986
10987 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010988 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010989 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010990 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010991
Owen Anderson1d0be152009-08-13 21:58:54 +000010992 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010993 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000010994 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010995
10996 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10997 // allow either a mul, shift, or constant here.
10998 Value *NewIdx = 0;
10999 ConstantInt *Scale = 0;
11000 if (ArrayEltSize == 1) {
11001 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011002 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011003 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011004 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011005 Scale = CI;
11006 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11007 if (Inst->getOpcode() == Instruction::Shl &&
11008 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011009 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11010 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011011 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011012 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011013 NewIdx = Inst->getOperand(0);
11014 } else if (Inst->getOpcode() == Instruction::Mul &&
11015 isa<ConstantInt>(Inst->getOperand(1))) {
11016 Scale = cast<ConstantInt>(Inst->getOperand(1));
11017 NewIdx = Inst->getOperand(0);
11018 }
11019 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011020
Chris Lattner7835cdd2005-09-13 18:36:04 +000011021 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011022 // out, perform the transformation. Note, we don't know whether Scale is
11023 // signed or not. We'll use unsigned version of division/modulo
11024 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011025 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011026 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011027 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011028 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011029 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011030 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11031 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011032 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011033 }
11034
11035 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011036 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011037 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011038 Idx[1] = NewIdx;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011039 Value *NewGEP = Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011040 if (cast<GEPOperator>(&GEP)->isInBounds())
11041 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000011042 // The NewGEP must be pointer typed, so must the old one -> BitCast
11043 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011044 }
11045 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011046 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011047 }
Chris Lattner58407792009-01-09 04:53:57 +000011048
Chris Lattner46cd5a12009-01-09 05:44:56 +000011049 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011050 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011051 /// Y = gep X, <...constant indices...>
11052 /// into a gep of the original struct. This is important for SROA and alias
11053 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011054 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011055 if (TD &&
11056 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011057 // Determine how much the GEP moves the pointer. We are guaranteed to get
11058 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011059 ConstantInt *OffsetV =
11060 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011061 int64_t Offset = OffsetV->getSExtValue();
11062
11063 // If this GEP instruction doesn't move the pointer, just replace the GEP
11064 // with a bitcast of the real input to the dest type.
11065 if (Offset == 0) {
11066 // If the bitcast is of an allocation, and the allocation will be
11067 // converted to match the type of the cast, don't touch this.
11068 if (isa<AllocationInst>(BCI->getOperand(0))) {
11069 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11070 if (Instruction *I = visitBitCast(*BCI)) {
11071 if (I != BCI) {
11072 I->takeName(BCI);
11073 BCI->getParent()->getInstList().insert(BCI, I);
11074 ReplaceInstUsesWith(*BCI, I);
11075 }
11076 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011077 }
Chris Lattner58407792009-01-09 04:53:57 +000011078 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011079 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011080 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011081
11082 // Otherwise, if the offset is non-zero, we need to find out if there is a
11083 // field at Offset in 'A's type. If so, we can pull the cast through the
11084 // GEP.
11085 SmallVector<Value*, 8> NewIndices;
11086 const Type *InTy =
11087 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011088 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011089 Value *NGEP = Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11090 NewIndices.end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011091 if (cast<GEPOperator>(&GEP)->isInBounds())
11092 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011093
11094 if (NGEP->getType() == GEP.getType())
11095 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011096 NGEP->takeName(&GEP);
11097 return new BitCastInst(NGEP, GEP.getType());
11098 }
Chris Lattner58407792009-01-09 04:53:57 +000011099 }
11100 }
11101
Chris Lattner8a2a3112001-12-14 16:52:21 +000011102 return 0;
11103}
11104
Chris Lattner0864acf2002-11-04 16:18:53 +000011105Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11106 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011107 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011108 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11109 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011110 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011111 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011112
11113 // Create and insert the replacement instruction...
11114 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011115 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011116 else {
11117 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011118 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011119 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011120 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011121
Chris Lattner0864acf2002-11-04 16:18:53 +000011122 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011123 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011124 //
11125 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011126 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011127
11128 // Now that I is pointing to the first non-allocation-inst in the block,
11129 // insert our getelementptr instruction...
11130 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011131 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011132 Value *Idx[2];
11133 Idx[0] = NullIdx;
11134 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011135 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11136 New->getName()+".sub", It);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011137 cast<GEPOperator>(V)->setIsInBounds(true);
Chris Lattner0864acf2002-11-04 16:18:53 +000011138
11139 // Now make everything use the getelementptr instead of the original
11140 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011141 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011142 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011143 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011144 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011145 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011146
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011147 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011148 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011149 // Note that we only do this for alloca's, because malloc should allocate
11150 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011151 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011152 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011153
11154 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11155 if (AI.getAlignment() == 0)
11156 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11157 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011158
Chris Lattner0864acf2002-11-04 16:18:53 +000011159 return 0;
11160}
11161
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011162Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11163 Value *Op = FI.getOperand(0);
11164
Chris Lattner17be6352004-10-18 02:59:09 +000011165 // free undef -> unreachable.
11166 if (isa<UndefValue>(Op)) {
11167 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011168 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000011169 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011170 return EraseInstFromFunction(FI);
11171 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011172
Chris Lattner6160e852004-02-28 04:57:37 +000011173 // If we have 'free null' delete the instruction. This can happen in stl code
11174 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011175 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011176 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011177
11178 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11179 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11180 FI.setOperand(0, CI->getOperand(0));
11181 return &FI;
11182 }
11183
11184 // Change free (gep X, 0,0,0,0) into free(X)
11185 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11186 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011187 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011188 FI.setOperand(0, GEPI->getOperand(0));
11189 return &FI;
11190 }
11191 }
11192
11193 // Change free(malloc) into nothing, if the malloc has a single use.
11194 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11195 if (MI->hasOneUse()) {
11196 EraseInstFromFunction(FI);
11197 return EraseInstFromFunction(*MI);
11198 }
Chris Lattner6160e852004-02-28 04:57:37 +000011199
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011200 return 0;
11201}
11202
11203
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011204/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011205static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011206 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011207 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011208 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011209 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011210
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011211 if (TD) {
11212 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11213 // Instead of loading constant c string, use corresponding integer value
11214 // directly if string length is small enough.
11215 std::string Str;
11216 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11217 unsigned len = Str.length();
11218 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11219 unsigned numBits = Ty->getPrimitiveSizeInBits();
11220 // Replace LI with immediate integer store.
11221 if ((numBits >> 3) == len + 1) {
11222 APInt StrVal(numBits, 0);
11223 APInt SingleChar(numBits, 0);
11224 if (TD->isLittleEndian()) {
11225 for (signed i = len-1; i >= 0; i--) {
11226 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11227 StrVal = (StrVal << 8) | SingleChar;
11228 }
11229 } else {
11230 for (unsigned i = 0; i < len; i++) {
11231 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11232 StrVal = (StrVal << 8) | SingleChar;
11233 }
11234 // Append NULL at the end.
11235 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011236 StrVal = (StrVal << 8) | SingleChar;
11237 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011238 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011239 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011240 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011241 }
11242 }
11243 }
11244
Mon P Wang6753f952009-02-07 22:19:29 +000011245 const PointerType *DestTy = cast<PointerType>(CI->getType());
11246 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011247 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011248
11249 // If the address spaces don't match, don't eliminate the cast.
11250 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11251 return 0;
11252
Chris Lattnerb89e0712004-07-13 01:49:43 +000011253 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011254
Reid Spencer42230162007-01-22 05:51:25 +000011255 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011256 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011257 // If the source is an array, the code below will not succeed. Check to
11258 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11259 // constants.
11260 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11261 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11262 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011263 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011264 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011265 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011266 SrcTy = cast<PointerType>(CastOp->getType());
11267 SrcPTy = SrcTy->getElementType();
11268 }
11269
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011270 if (IC.getTargetData() &&
11271 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011272 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011273 // Do not allow turning this into a load of an integer, which is then
11274 // casted to a pointer, this pessimizes pointer analysis a lot.
11275 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011276 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11277 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011278
Chris Lattnerf9527852005-01-31 04:50:46 +000011279 // Okay, we are casting from one integer or pointer type to another of
11280 // the same size. Instead of casting the pointer before the load, cast
11281 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011282 Value *NewLoad =
11283 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011284 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011285 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011286 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011287 }
11288 }
11289 return 0;
11290}
11291
Chris Lattner833b8a42003-06-26 05:06:25 +000011292Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11293 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011294
Dan Gohman9941f742007-07-20 16:34:21 +000011295 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011296 if (TD) {
11297 unsigned KnownAlign =
11298 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11299 if (KnownAlign >
11300 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11301 LI.getAlignment()))
11302 LI.setAlignment(KnownAlign);
11303 }
Dan Gohman9941f742007-07-20 16:34:21 +000011304
Chris Lattner37366c12005-05-01 04:24:53 +000011305 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011306 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011307 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011308 return Res;
11309
11310 // None of the following transforms are legal for volatile loads.
11311 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011312
Dan Gohman2276a7b2008-10-15 23:19:35 +000011313 // Do really simple store-to-load forwarding and load CSE, to catch cases
11314 // where there are several consequtive memory accesses to the same location,
11315 // separated by a few arithmetic operations.
11316 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011317 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11318 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011319
Christopher Lambb15147e2007-12-29 07:56:53 +000011320 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11321 const Value *GEPI0 = GEPI->getOperand(0);
11322 // TODO: Consider a target hook for valid address spaces for this xform.
11323 if (isa<ConstantPointerNull>(GEPI0) &&
11324 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011325 // Insert a new store to null instruction before the load to indicate
11326 // that this code is not reachable. We do this instead of inserting
11327 // an unreachable instruction directly because we cannot modify the
11328 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011329 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011330 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011331 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011332 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011333 }
Chris Lattner37366c12005-05-01 04:24:53 +000011334
Chris Lattnere87597f2004-10-16 18:11:37 +000011335 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011336 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011337 // TODO: Consider a target hook for valid address spaces for this xform.
11338 if (isa<UndefValue>(C) || (C->isNullValue() &&
11339 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011340 // Insert a new store to null instruction before the load to indicate that
11341 // this code is not reachable. We do this instead of inserting an
11342 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011343 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011344 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011345 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011346 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011347
Chris Lattnere87597f2004-10-16 18:11:37 +000011348 // Instcombine load (constant global) into the value loaded.
11349 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011350 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011351 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011352
Chris Lattnere87597f2004-10-16 18:11:37 +000011353 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011354 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011355 if (CE->getOpcode() == Instruction::GetElementPtr) {
11356 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011357 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011358 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011359 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011360 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011361 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011362 if (CE->getOperand(0)->isNullValue()) {
11363 // Insert a new store to null instruction before the load to indicate
11364 // that this code is not reachable. We do this instead of inserting
11365 // an unreachable instruction directly because we cannot modify the
11366 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011367 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011368 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011369 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011370 }
11371
Reid Spencer3da59db2006-11-27 01:05:10 +000011372 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011373 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011374 return Res;
11375 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011376 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011377 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011378
11379 // If this load comes from anywhere in a constant global, and if the global
11380 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011381 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011382 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011383 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011384 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011385 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011386 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011387 }
11388 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011389
Chris Lattner37366c12005-05-01 04:24:53 +000011390 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011391 // Change select and PHI nodes to select values instead of addresses: this
11392 // helps alias analysis out a lot, allows many others simplifications, and
11393 // exposes redundancy in the code.
11394 //
11395 // Note that we cannot do the transformation unless we know that the
11396 // introduced loads cannot trap! Something like this is valid as long as
11397 // the condition is always false: load (select bool %C, int* null, int* %G),
11398 // but it would not be valid if we transformed it to load from null
11399 // unconditionally.
11400 //
11401 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11402 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011403 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11404 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011405 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11406 SI->getOperand(1)->getName()+".val");
11407 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11408 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011409 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011410 }
11411
Chris Lattner684fe212004-09-23 15:46:00 +000011412 // load (select (cond, null, P)) -> load P
11413 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11414 if (C->isNullValue()) {
11415 LI.setOperand(0, SI->getOperand(2));
11416 return &LI;
11417 }
11418
11419 // load (select (cond, P, null)) -> load P
11420 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11421 if (C->isNullValue()) {
11422 LI.setOperand(0, SI->getOperand(1));
11423 return &LI;
11424 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011425 }
11426 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011427 return 0;
11428}
11429
Reid Spencer55af2b52007-01-19 21:20:31 +000011430/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011431/// when possible. This makes it generally easy to do alias analysis and/or
11432/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011433static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11434 User *CI = cast<User>(SI.getOperand(1));
11435 Value *CastOp = CI->getOperand(0);
11436
11437 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011438 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11439 if (SrcTy == 0) return 0;
11440
11441 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011442
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011443 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11444 return 0;
11445
Chris Lattner3914f722009-01-24 01:00:13 +000011446 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11447 /// to its first element. This allows us to handle things like:
11448 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11449 /// on 32-bit hosts.
11450 SmallVector<Value*, 4> NewGEPIndices;
11451
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011452 // If the source is an array, the code below will not succeed. Check to
11453 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11454 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011455 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11456 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011457 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011458 NewGEPIndices.push_back(Zero);
11459
11460 while (1) {
11461 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011462 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011463 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011464 NewGEPIndices.push_back(Zero);
11465 SrcPTy = STy->getElementType(0);
11466 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11467 NewGEPIndices.push_back(Zero);
11468 SrcPTy = ATy->getElementType();
11469 } else {
11470 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011471 }
Chris Lattner3914f722009-01-24 01:00:13 +000011472 }
11473
Owen Andersondebcb012009-07-29 22:17:13 +000011474 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011475 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011476
11477 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11478 return 0;
11479
Chris Lattner71759c42009-01-16 20:12:52 +000011480 // If the pointers point into different address spaces or if they point to
11481 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011482 if (!IC.getTargetData() ||
11483 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011484 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011485 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11486 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011487 return 0;
11488
11489 // Okay, we are casting from one integer or pointer type to another of
11490 // the same size. Instead of casting the pointer before
11491 // the store, cast the value to be stored.
11492 Value *NewCast;
11493 Value *SIOp0 = SI.getOperand(0);
11494 Instruction::CastOps opcode = Instruction::BitCast;
11495 const Type* CastSrcTy = SIOp0->getType();
11496 const Type* CastDstTy = SrcPTy;
11497 if (isa<PointerType>(CastDstTy)) {
11498 if (CastSrcTy->isInteger())
11499 opcode = Instruction::IntToPtr;
11500 } else if (isa<IntegerType>(CastDstTy)) {
11501 if (isa<PointerType>(SIOp0->getType()))
11502 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011503 }
Chris Lattner3914f722009-01-24 01:00:13 +000011504
11505 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11506 // emit a GEP to index into its first field.
11507 if (!NewGEPIndices.empty()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011508 CastOp = IC.Builder->CreateGEP(CastOp, NewGEPIndices.begin(),
11509 NewGEPIndices.end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011510 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner3914f722009-01-24 01:00:13 +000011511 }
11512
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011513 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11514 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011515 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011516}
11517
Chris Lattner4aebaee2008-11-27 08:56:30 +000011518/// equivalentAddressValues - Test if A and B will obviously have the same
11519/// value. This includes recognizing that %t0 and %t1 will have the same
11520/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011521/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011522/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011523/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011524/// %t2 = load i32* %t1
11525///
11526static bool equivalentAddressValues(Value *A, Value *B) {
11527 // Test if the values are trivially equivalent.
11528 if (A == B) return true;
11529
11530 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011531 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11532 // its only used to compare two uses within the same basic block, which
11533 // means that they'll always either have the same value or one of them
11534 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011535 if (isa<BinaryOperator>(A) ||
11536 isa<CastInst>(A) ||
11537 isa<PHINode>(A) ||
11538 isa<GetElementPtrInst>(A))
11539 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011540 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011541 return true;
11542
11543 // Otherwise they may not be equivalent.
11544 return false;
11545}
11546
Dale Johannesen4945c652009-03-03 21:26:39 +000011547// If this instruction has two uses, one of which is a llvm.dbg.declare,
11548// return the llvm.dbg.declare.
11549DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11550 if (!V->hasNUses(2))
11551 return 0;
11552 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11553 UI != E; ++UI) {
11554 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11555 return DI;
11556 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11557 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11558 return DI;
11559 }
11560 }
11561 return 0;
11562}
11563
Chris Lattner2f503e62005-01-31 05:36:43 +000011564Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11565 Value *Val = SI.getOperand(0);
11566 Value *Ptr = SI.getOperand(1);
11567
11568 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011569 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011570 ++NumCombined;
11571 return 0;
11572 }
Chris Lattner836692d2007-01-15 06:51:56 +000011573
11574 // If the RHS is an alloca with a single use, zapify the store, making the
11575 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011576 // If the RHS is an alloca with a two uses, the other one being a
11577 // llvm.dbg.declare, zapify the store and the declare, making the
11578 // alloca dead. We must do this to prevent declare's from affecting
11579 // codegen.
11580 if (!SI.isVolatile()) {
11581 if (Ptr->hasOneUse()) {
11582 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011583 EraseInstFromFunction(SI);
11584 ++NumCombined;
11585 return 0;
11586 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011587 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11588 if (isa<AllocaInst>(GEP->getOperand(0))) {
11589 if (GEP->getOperand(0)->hasOneUse()) {
11590 EraseInstFromFunction(SI);
11591 ++NumCombined;
11592 return 0;
11593 }
11594 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11595 EraseInstFromFunction(*DI);
11596 EraseInstFromFunction(SI);
11597 ++NumCombined;
11598 return 0;
11599 }
11600 }
11601 }
11602 }
11603 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11604 EraseInstFromFunction(*DI);
11605 EraseInstFromFunction(SI);
11606 ++NumCombined;
11607 return 0;
11608 }
Chris Lattner836692d2007-01-15 06:51:56 +000011609 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011610
Dan Gohman9941f742007-07-20 16:34:21 +000011611 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011612 if (TD) {
11613 unsigned KnownAlign =
11614 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11615 if (KnownAlign >
11616 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11617 SI.getAlignment()))
11618 SI.setAlignment(KnownAlign);
11619 }
Dan Gohman9941f742007-07-20 16:34:21 +000011620
Dale Johannesenacb51a32009-03-03 01:43:03 +000011621 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011622 // stores to the same location, separated by a few arithmetic operations. This
11623 // situation often occurs with bitfield accesses.
11624 BasicBlock::iterator BBI = &SI;
11625 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11626 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011627 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011628 // Don't count debug info directives, lest they affect codegen,
11629 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11630 // It is necessary for correctness to skip those that feed into a
11631 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011632 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011633 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011634 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011635 continue;
11636 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011637
11638 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11639 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011640 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11641 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011642 ++NumDeadStore;
11643 ++BBI;
11644 EraseInstFromFunction(*PrevSI);
11645 continue;
11646 }
11647 break;
11648 }
11649
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011650 // If this is a load, we have to stop. However, if the loaded value is from
11651 // the pointer we're loading and is producing the pointer we're storing,
11652 // then *this* store is dead (X = load P; store X -> P).
11653 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011654 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11655 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011656 EraseInstFromFunction(SI);
11657 ++NumCombined;
11658 return 0;
11659 }
11660 // Otherwise, this is a load from some other location. Stores before it
11661 // may not be dead.
11662 break;
11663 }
11664
Chris Lattner9ca96412006-02-08 03:25:32 +000011665 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011666 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011667 break;
11668 }
11669
11670
11671 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011672
11673 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011674 if (isa<ConstantPointerNull>(Ptr) &&
11675 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011676 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011677 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011678 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011679 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011680 ++NumCombined;
11681 }
11682 return 0; // Do not modify these!
11683 }
11684
11685 // store undef, Ptr -> noop
11686 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011687 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011688 ++NumCombined;
11689 return 0;
11690 }
11691
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011692 // If the pointer destination is a cast, see if we can fold the cast into the
11693 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011694 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011695 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11696 return Res;
11697 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011698 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011699 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11700 return Res;
11701
Chris Lattner408902b2005-09-12 23:23:25 +000011702
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011703 // If this store is the last instruction in the basic block (possibly
11704 // excepting debug info instructions and the pointer bitcasts that feed
11705 // into them), and if the block ends with an unconditional branch, try
11706 // to move it to the successor block.
11707 BBI = &SI;
11708 do {
11709 ++BBI;
11710 } while (isa<DbgInfoIntrinsic>(BBI) ||
11711 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011712 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011713 if (BI->isUnconditional())
11714 if (SimplifyStoreAtEndOfBlock(SI))
11715 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011716
Chris Lattner2f503e62005-01-31 05:36:43 +000011717 return 0;
11718}
11719
Chris Lattner3284d1f2007-04-15 00:07:55 +000011720/// SimplifyStoreAtEndOfBlock - Turn things like:
11721/// if () { *P = v1; } else { *P = v2 }
11722/// into a phi node with a store in the successor.
11723///
Chris Lattner31755a02007-04-15 01:02:18 +000011724/// Simplify things like:
11725/// *P = v1; if () { *P = v2; }
11726/// into a phi node with a store in the successor.
11727///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011728bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11729 BasicBlock *StoreBB = SI.getParent();
11730
11731 // Check to see if the successor block has exactly two incoming edges. If
11732 // so, see if the other predecessor contains a store to the same location.
11733 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011734 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011735
11736 // Determine whether Dest has exactly two predecessors and, if so, compute
11737 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011738 pred_iterator PI = pred_begin(DestBB);
11739 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011740 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011741 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011742 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011743 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011744 return false;
11745
11746 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011747 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011748 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011749 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011750 }
Chris Lattner31755a02007-04-15 01:02:18 +000011751 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011752 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011753
11754 // Bail out if all the relevant blocks aren't distinct (this can happen,
11755 // for example, if SI is in an infinite loop)
11756 if (StoreBB == DestBB || OtherBB == DestBB)
11757 return false;
11758
Chris Lattner31755a02007-04-15 01:02:18 +000011759 // Verify that the other block ends in a branch and is not otherwise empty.
11760 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011761 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011762 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011763 return false;
11764
Chris Lattner31755a02007-04-15 01:02:18 +000011765 // If the other block ends in an unconditional branch, check for the 'if then
11766 // else' case. there is an instruction before the branch.
11767 StoreInst *OtherStore = 0;
11768 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011769 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011770 // Skip over debugging info.
11771 while (isa<DbgInfoIntrinsic>(BBI) ||
11772 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11773 if (BBI==OtherBB->begin())
11774 return false;
11775 --BBI;
11776 }
11777 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011778 OtherStore = dyn_cast<StoreInst>(BBI);
11779 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11780 return false;
11781 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011782 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011783 // destinations is StoreBB, then we have the if/then case.
11784 if (OtherBr->getSuccessor(0) != StoreBB &&
11785 OtherBr->getSuccessor(1) != StoreBB)
11786 return false;
11787
11788 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011789 // if/then triangle. See if there is a store to the same ptr as SI that
11790 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011791 for (;; --BBI) {
11792 // Check to see if we find the matching store.
11793 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11794 if (OtherStore->getOperand(1) != SI.getOperand(1))
11795 return false;
11796 break;
11797 }
Eli Friedman6903a242008-06-13 22:02:12 +000011798 // If we find something that may be using or overwriting the stored
11799 // value, or if we run out of instructions, we can't do the xform.
11800 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011801 BBI == OtherBB->begin())
11802 return false;
11803 }
11804
11805 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011806 // make sure nothing reads or overwrites the stored value in
11807 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011808 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11809 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011810 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011811 return false;
11812 }
11813 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011814
Chris Lattner31755a02007-04-15 01:02:18 +000011815 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011816 Value *MergedVal = OtherStore->getOperand(0);
11817 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011818 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011819 PN->reserveOperandSpace(2);
11820 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011821 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11822 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011823 }
11824
11825 // Advance to a place where it is safe to insert the new store and
11826 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011827 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011828 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11829 OtherStore->isVolatile()), *BBI);
11830
11831 // Nuke the old stores.
11832 EraseInstFromFunction(SI);
11833 EraseInstFromFunction(*OtherStore);
11834 ++NumCombined;
11835 return true;
11836}
11837
Chris Lattner2f503e62005-01-31 05:36:43 +000011838
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011839Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11840 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011841 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011842 BasicBlock *TrueDest;
11843 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011844 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011845 !isa<Constant>(X)) {
11846 // Swap Destinations and condition...
11847 BI.setCondition(X);
11848 BI.setSuccessor(0, FalseDest);
11849 BI.setSuccessor(1, TrueDest);
11850 return &BI;
11851 }
11852
Reid Spencere4d87aa2006-12-23 06:05:41 +000011853 // Cannonicalize fcmp_one -> fcmp_oeq
11854 FCmpInst::Predicate FPred; Value *Y;
11855 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011856 TrueDest, FalseDest)) &&
11857 BI.getCondition()->hasOneUse())
11858 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11859 FPred == FCmpInst::FCMP_OGE) {
11860 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11861 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11862
11863 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011864 BI.setSuccessor(0, FalseDest);
11865 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011866 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011867 return &BI;
11868 }
11869
11870 // Cannonicalize icmp_ne -> icmp_eq
11871 ICmpInst::Predicate IPred;
11872 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011873 TrueDest, FalseDest)) &&
11874 BI.getCondition()->hasOneUse())
11875 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11876 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11877 IPred == ICmpInst::ICMP_SGE) {
11878 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11879 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11880 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011881 BI.setSuccessor(0, FalseDest);
11882 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011883 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011884 return &BI;
11885 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011886
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011887 return 0;
11888}
Chris Lattner0864acf2002-11-04 16:18:53 +000011889
Chris Lattner46238a62004-07-03 00:26:11 +000011890Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11891 Value *Cond = SI.getCondition();
11892 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11893 if (I->getOpcode() == Instruction::Add)
11894 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11895 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11896 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011897 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000011898 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011899 AddRHS));
11900 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000011901 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011902 return &SI;
11903 }
11904 }
11905 return 0;
11906}
11907
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011908Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011909 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011910
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011911 if (!EV.hasIndices())
11912 return ReplaceInstUsesWith(EV, Agg);
11913
11914 if (Constant *C = dyn_cast<Constant>(Agg)) {
11915 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011916 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011917
11918 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000011919 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011920
11921 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11922 // Extract the element indexed by the first index out of the constant
11923 Value *V = C->getOperand(*EV.idx_begin());
11924 if (EV.getNumIndices() > 1)
11925 // Extract the remaining indices out of the constant indexed by the
11926 // first index
11927 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11928 else
11929 return ReplaceInstUsesWith(EV, V);
11930 }
11931 return 0; // Can't handle other constants
11932 }
11933 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11934 // We're extracting from an insertvalue instruction, compare the indices
11935 const unsigned *exti, *exte, *insi, *inse;
11936 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11937 exte = EV.idx_end(), inse = IV->idx_end();
11938 exti != exte && insi != inse;
11939 ++exti, ++insi) {
11940 if (*insi != *exti)
11941 // The insert and extract both reference distinctly different elements.
11942 // This means the extract is not influenced by the insert, and we can
11943 // replace the aggregate operand of the extract with the aggregate
11944 // operand of the insert. i.e., replace
11945 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11946 // %E = extractvalue { i32, { i32 } } %I, 0
11947 // with
11948 // %E = extractvalue { i32, { i32 } } %A, 0
11949 return ExtractValueInst::Create(IV->getAggregateOperand(),
11950 EV.idx_begin(), EV.idx_end());
11951 }
11952 if (exti == exte && insi == inse)
11953 // Both iterators are at the end: Index lists are identical. Replace
11954 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11955 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11956 // with "i32 42"
11957 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11958 if (exti == exte) {
11959 // The extract list is a prefix of the insert list. i.e. replace
11960 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11961 // %E = extractvalue { i32, { i32 } } %I, 1
11962 // with
11963 // %X = extractvalue { i32, { i32 } } %A, 1
11964 // %E = insertvalue { i32 } %X, i32 42, 0
11965 // by switching the order of the insert and extract (though the
11966 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011967 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
11968 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011969 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11970 insi, inse);
11971 }
11972 if (insi == inse)
11973 // The insert list is a prefix of the extract list
11974 // We can simply remove the common indices from the extract and make it
11975 // operate on the inserted value instead of the insertvalue result.
11976 // i.e., replace
11977 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11978 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11979 // with
11980 // %E extractvalue { i32 } { i32 42 }, 0
11981 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11982 exti, exte);
11983 }
11984 // Can't simplify extracts from other values. Note that nested extracts are
11985 // already simplified implicitely by the above (extract ( extract (insert) )
11986 // will be translated into extract ( insert ( extract ) ) first and then just
11987 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011988 return 0;
11989}
11990
Chris Lattner220b0cf2006-03-05 00:22:33 +000011991/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11992/// is to leave as a vector operation.
11993static bool CheapToScalarize(Value *V, bool isConstant) {
11994 if (isa<ConstantAggregateZero>(V))
11995 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011996 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011997 if (isConstant) return true;
11998 // If all elts are the same, we can extract.
11999 Constant *Op0 = C->getOperand(0);
12000 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12001 if (C->getOperand(i) != Op0)
12002 return false;
12003 return true;
12004 }
12005 Instruction *I = dyn_cast<Instruction>(V);
12006 if (!I) return false;
12007
12008 // Insert element gets simplified to the inserted element or is deleted if
12009 // this is constant idx extract element and its a constant idx insertelt.
12010 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12011 isa<ConstantInt>(I->getOperand(2)))
12012 return true;
12013 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12014 return true;
12015 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12016 if (BO->hasOneUse() &&
12017 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12018 CheapToScalarize(BO->getOperand(1), isConstant)))
12019 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012020 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12021 if (CI->hasOneUse() &&
12022 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12023 CheapToScalarize(CI->getOperand(1), isConstant)))
12024 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012025
12026 return false;
12027}
12028
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012029/// Read and decode a shufflevector mask.
12030///
12031/// It turns undef elements into values that are larger than the number of
12032/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012033static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12034 unsigned NElts = SVI->getType()->getNumElements();
12035 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12036 return std::vector<unsigned>(NElts, 0);
12037 if (isa<UndefValue>(SVI->getOperand(2)))
12038 return std::vector<unsigned>(NElts, 2*NElts);
12039
12040 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012041 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012042 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12043 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012044 Result.push_back(NElts*2); // undef -> 8
12045 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012046 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012047 return Result;
12048}
12049
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012050/// FindScalarElement - Given a vector and an element number, see if the scalar
12051/// value is already around as a register, for example if it were inserted then
12052/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012053static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012054 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012055 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12056 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012057 unsigned Width = PTy->getNumElements();
12058 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012059 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012060
12061 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012062 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012063 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012064 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012065 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012066 return CP->getOperand(EltNo);
12067 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12068 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012069 if (!isa<ConstantInt>(III->getOperand(2)))
12070 return 0;
12071 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012072
12073 // If this is an insert to the element we are looking for, return the
12074 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012075 if (EltNo == IIElt)
12076 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012077
12078 // Otherwise, the insertelement doesn't modify the value, recurse on its
12079 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012080 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012081 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012082 unsigned LHSWidth =
12083 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012084 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012085 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012086 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012087 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012088 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012089 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012090 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012091 }
12092
12093 // Otherwise, we don't know.
12094 return 0;
12095}
12096
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012097Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012098 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012099 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012100 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012101
Dan Gohman07a96762007-07-16 14:29:03 +000012102 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012103 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012104 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012105
Reid Spencer9d6565a2007-02-15 02:26:10 +000012106 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012107 // If vector val is constant with all elements the same, replace EI with
12108 // that element. When the elements are not identical, we cannot replace yet
12109 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012110 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012111 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012112 if (C->getOperand(i) != op0) {
12113 op0 = 0;
12114 break;
12115 }
12116 if (op0)
12117 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012118 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012119
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012120 // If extracting a specified index from the vector, see if we can recursively
12121 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012122 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012123 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012124 unsigned VectorWidth =
12125 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012126
12127 // If this is extracting an invalid index, turn this into undef, to avoid
12128 // crashing the code below.
12129 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012130 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012131
Chris Lattner867b99f2006-10-05 06:55:50 +000012132 // This instruction only demands the single element from the input vector.
12133 // If the input vector has a single use, simplify it based on this use
12134 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012135 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012136 APInt UndefElts(VectorWidth, 0);
12137 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012138 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012139 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012140 EI.setOperand(0, V);
12141 return &EI;
12142 }
12143 }
12144
Owen Andersond672ecb2009-07-03 00:17:18 +000012145 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012146 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012147
12148 // If the this extractelement is directly using a bitcast from a vector of
12149 // the same number of elements, see if we can find the source element from
12150 // it. In this case, we will end up needing to bitcast the scalars.
12151 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12152 if (const VectorType *VT =
12153 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12154 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012155 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12156 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012157 return new BitCastInst(Elt, EI.getType());
12158 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012159 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012160
Chris Lattner73fa49d2006-05-25 22:53:38 +000012161 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012162 if (I->hasOneUse()) {
12163 // Push extractelement into predecessor operation if legal and
12164 // profitable to do so
12165 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012166 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12167 if (CheapToScalarize(BO, isConstantElt)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012168 Value *newEI0 =
12169 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12170 EI.getName()+".lhs");
12171 Value *newEI1 =
12172 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12173 EI.getName()+".rhs");
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012174 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012175 }
Chris Lattner08142f22009-08-30 19:47:22 +000012176 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
12177 unsigned AS = LI->getPointerAddressSpace();
12178 Value *Ptr = Builder->CreateBitCast(I->getOperand(0),
12179 PointerType::get(EI.getType(), AS),
12180 I->getOperand(0)->getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012181 Value *GEP =
12182 Builder->CreateGEP(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012183 cast<GEPOperator>(GEP)->setIsInBounds(true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012184
12185 LoadInst *Load = Builder->CreateLoad(GEP, "tmp");
12186
12187 // Make sure the Load goes before the load instruction in the source,
12188 // not wherever the extract happens to be.
Chris Lattner08142f22009-08-30 19:47:22 +000012189 if (Instruction *P = dyn_cast<Instruction>(Ptr))
12190 P->moveBefore(I);
12191 if (Instruction *G = dyn_cast<Instruction>(GEP))
12192 G->moveBefore(I);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012193 Load->moveBefore(I);
12194
Mon P Wang7c4efa62009-08-13 05:12:13 +000012195 return ReplaceInstUsesWith(EI, Load);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012196 }
12197 }
12198 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12199 // Extracting the inserted element?
12200 if (IE->getOperand(2) == EI.getOperand(1))
12201 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12202 // If the inserted and extracted elements are constants, they must not
12203 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012204 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012205 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012206 EI.setOperand(0, IE->getOperand(0));
12207 return &EI;
12208 }
12209 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12210 // If this is extracting an element from a shufflevector, figure out where
12211 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012212 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12213 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012214 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012215 unsigned LHSWidth =
12216 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12217
12218 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012219 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012220 else if (SrcIdx < LHSWidth*2) {
12221 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012222 Src = SVI->getOperand(1);
12223 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012224 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012225 }
Eric Christophera3500da2009-07-25 02:28:41 +000012226 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012227 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12228 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012229 }
12230 }
Eli Friedman2451a642009-07-18 23:06:53 +000012231 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012232 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012233 return 0;
12234}
12235
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012236/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12237/// elements from either LHS or RHS, return the shuffle mask and true.
12238/// Otherwise, return false.
12239static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012240 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012241 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012242 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12243 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012244 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012245
12246 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012247 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012248 return true;
12249 } else if (V == LHS) {
12250 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012251 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012252 return true;
12253 } else if (V == RHS) {
12254 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012255 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012256 return true;
12257 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12258 // If this is an insert of an extract from some other vector, include it.
12259 Value *VecOp = IEI->getOperand(0);
12260 Value *ScalarOp = IEI->getOperand(1);
12261 Value *IdxOp = IEI->getOperand(2);
12262
Chris Lattnerd929f062006-04-27 21:14:21 +000012263 if (!isa<ConstantInt>(IdxOp))
12264 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012265 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012266
12267 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12268 // Okay, we can handle this if the vector we are insertinting into is
12269 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012270 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012271 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012272 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012273 return true;
12274 }
12275 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12276 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012277 EI->getOperand(0)->getType() == V->getType()) {
12278 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012279 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012280
12281 // This must be extracting from either LHS or RHS.
12282 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12283 // Okay, we can handle this if the vector we are insertinting into is
12284 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012285 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012286 // If so, update the mask to reflect the inserted value.
12287 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012288 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012289 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012290 } else {
12291 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012292 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012293 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012294
12295 }
12296 return true;
12297 }
12298 }
12299 }
12300 }
12301 }
12302 // TODO: Handle shufflevector here!
12303
12304 return false;
12305}
12306
12307/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12308/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12309/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012310static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012311 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012312 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012313 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012314 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012315 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012316
12317 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012318 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012319 return V;
12320 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012321 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012322 return V;
12323 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12324 // If this is an insert of an extract from some other vector, include it.
12325 Value *VecOp = IEI->getOperand(0);
12326 Value *ScalarOp = IEI->getOperand(1);
12327 Value *IdxOp = IEI->getOperand(2);
12328
12329 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12330 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12331 EI->getOperand(0)->getType() == V->getType()) {
12332 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012333 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12334 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012335
12336 // Either the extracted from or inserted into vector must be RHSVec,
12337 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012338 if (EI->getOperand(0) == RHS || RHS == 0) {
12339 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012340 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012341 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012342 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012343 return V;
12344 }
12345
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012346 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012347 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12348 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012349 // Everything but the extracted element is replaced with the RHS.
12350 for (unsigned i = 0; i != NumElts; ++i) {
12351 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012352 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012353 }
12354 return V;
12355 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012356
12357 // If this insertelement is a chain that comes from exactly these two
12358 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012359 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12360 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012361 return EI->getOperand(0);
12362
Chris Lattnerefb47352006-04-15 01:39:45 +000012363 }
12364 }
12365 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012366 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012367
12368 // Otherwise, can't do anything fancy. Return an identity vector.
12369 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012370 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012371 return V;
12372}
12373
12374Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12375 Value *VecOp = IE.getOperand(0);
12376 Value *ScalarOp = IE.getOperand(1);
12377 Value *IdxOp = IE.getOperand(2);
12378
Chris Lattner599ded12007-04-09 01:11:16 +000012379 // Inserting an undef or into an undefined place, remove this.
12380 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12381 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012382
Chris Lattnerefb47352006-04-15 01:39:45 +000012383 // If the inserted element was extracted from some other vector, and if the
12384 // indexes are constant, try to turn this into a shufflevector operation.
12385 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12386 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12387 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012388 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012389 unsigned ExtractedIdx =
12390 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012391 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012392
12393 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12394 return ReplaceInstUsesWith(IE, VecOp);
12395
12396 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012397 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012398
12399 // If we are extracting a value from a vector, then inserting it right
12400 // back into the same place, just use the input vector.
12401 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12402 return ReplaceInstUsesWith(IE, VecOp);
12403
12404 // We could theoretically do this for ANY input. However, doing so could
12405 // turn chains of insertelement instructions into a chain of shufflevector
12406 // instructions, and right now we do not merge shufflevectors. As such,
12407 // only do this in a situation where it is clear that there is benefit.
12408 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12409 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12410 // the values of VecOp, except then one read from EIOp0.
12411 // Build a new shuffle mask.
12412 std::vector<Constant*> Mask;
12413 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012414 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012415 else {
12416 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012417 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012418 NumVectorElts));
12419 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012420 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012421 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012422 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012423 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012424 }
12425
12426 // If this insertelement isn't used by some other insertelement, turn it
12427 // (and any insertelements it points to), into one big shuffle.
12428 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12429 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012430 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012431 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012432 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012433 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012434 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012435 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012436 }
12437 }
12438 }
12439
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012440 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12441 APInt UndefElts(VWidth, 0);
12442 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12443 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12444 return &IE;
12445
Chris Lattnerefb47352006-04-15 01:39:45 +000012446 return 0;
12447}
12448
12449
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012450Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12451 Value *LHS = SVI.getOperand(0);
12452 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012453 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012454
12455 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012456
Chris Lattner867b99f2006-10-05 06:55:50 +000012457 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012458 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012459 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012460
Dan Gohman488fbfc2008-09-09 18:11:14 +000012461 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012462
12463 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12464 return 0;
12465
Evan Cheng388df622009-02-03 10:05:09 +000012466 APInt UndefElts(VWidth, 0);
12467 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12468 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012469 LHS = SVI.getOperand(0);
12470 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012471 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012472 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012473
Chris Lattner863bcff2006-05-25 23:48:38 +000012474 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12475 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12476 if (LHS == RHS || isa<UndefValue>(LHS)) {
12477 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012478 // shuffle(undef,undef,mask) -> undef.
12479 return ReplaceInstUsesWith(SVI, LHS);
12480 }
12481
Chris Lattner863bcff2006-05-25 23:48:38 +000012482 // Remap any references to RHS to use LHS.
12483 std::vector<Constant*> Elts;
12484 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012485 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012486 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012487 else {
12488 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012489 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012490 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012491 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012492 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012493 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012494 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012495 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012496 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012497 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012498 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012499 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012500 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012501 LHS = SVI.getOperand(0);
12502 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012503 MadeChange = true;
12504 }
12505
Chris Lattner7b2e27922006-05-26 00:29:06 +000012506 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012507 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012508
Chris Lattner863bcff2006-05-25 23:48:38 +000012509 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12510 if (Mask[i] >= e*2) continue; // Ignore undef values.
12511 // Is this an identity shuffle of the LHS value?
12512 isLHSID &= (Mask[i] == i);
12513
12514 // Is this an identity shuffle of the RHS value?
12515 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012516 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012517
Chris Lattner863bcff2006-05-25 23:48:38 +000012518 // Eliminate identity shuffles.
12519 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12520 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012521
Chris Lattner7b2e27922006-05-26 00:29:06 +000012522 // If the LHS is a shufflevector itself, see if we can combine it with this
12523 // one without producing an unusual shuffle. Here we are really conservative:
12524 // we are absolutely afraid of producing a shuffle mask not in the input
12525 // program, because the code gen may not be smart enough to turn a merged
12526 // shuffle into two specific shuffles: it may produce worse code. As such,
12527 // we only merge two shuffles if the result is one of the two input shuffle
12528 // masks. In this case, merging the shuffles just removes one instruction,
12529 // which we know is safe. This is good for things like turning:
12530 // (splat(splat)) -> splat.
12531 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12532 if (isa<UndefValue>(RHS)) {
12533 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12534
12535 std::vector<unsigned> NewMask;
12536 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12537 if (Mask[i] >= 2*e)
12538 NewMask.push_back(2*e);
12539 else
12540 NewMask.push_back(LHSMask[Mask[i]]);
12541
12542 // If the result mask is equal to the src shuffle or this shuffle mask, do
12543 // the replacement.
12544 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012545 unsigned LHSInNElts =
12546 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012547 std::vector<Constant*> Elts;
12548 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012549 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012550 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012551 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012552 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012553 }
12554 }
12555 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12556 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012557 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012558 }
12559 }
12560 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012561
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012562 return MadeChange ? &SVI : 0;
12563}
12564
12565
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012566
Chris Lattnerea1c4542004-12-08 23:43:58 +000012567
12568/// TryToSinkInstruction - Try to move the specified instruction from its
12569/// current block into the beginning of DestBlock, which can only happen if it's
12570/// safe to move the instruction past all of the instructions between it and the
12571/// end of its block.
12572static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12573 assert(I->hasOneUse() && "Invariants didn't hold!");
12574
Chris Lattner108e9022005-10-27 17:13:11 +000012575 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012576 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012577 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012578
Chris Lattnerea1c4542004-12-08 23:43:58 +000012579 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012580 if (isa<AllocaInst>(I) && I->getParent() ==
12581 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012582 return false;
12583
Chris Lattner96a52a62004-12-09 07:14:34 +000012584 // We can only sink load instructions if there is nothing between the load and
12585 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012586 if (I->mayReadFromMemory()) {
12587 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012588 Scan != E; ++Scan)
12589 if (Scan->mayWriteToMemory())
12590 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012591 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012592
Dan Gohman02dea8b2008-05-23 21:05:58 +000012593 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012594
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012595 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012596 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012597 ++NumSunkInst;
12598 return true;
12599}
12600
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012601
12602/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12603/// all reachable code to the worklist.
12604///
12605/// This has a couple of tricks to make the code faster and more powerful. In
12606/// particular, we constant fold and DCE instructions as we go, to avoid adding
12607/// them to the worklist (this significantly speeds up instcombine on code where
12608/// many instructions are dead or constant). Additionally, if we find a branch
12609/// whose condition is a known constant, we only visit the reachable successors.
12610///
12611static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012612 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012613 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012614 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012615 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012616 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012617
Chris Lattner2c7718a2007-03-23 19:17:18 +000012618 while (!Worklist.empty()) {
12619 BB = Worklist.back();
12620 Worklist.pop_back();
12621
12622 // We have now visited this block! If we've already been here, ignore it.
12623 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012624
12625 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012626 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12627 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012628
Chris Lattner2c7718a2007-03-23 19:17:18 +000012629 // DCE instruction if trivially dead.
12630 if (isInstructionTriviallyDead(Inst)) {
12631 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012632 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012633 Inst->eraseFromParent();
12634 continue;
12635 }
12636
12637 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012638 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012639 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12640 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012641 Inst->replaceAllUsesWith(C);
12642 ++NumConstProp;
12643 Inst->eraseFromParent();
12644 continue;
12645 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012646
Devang Patel7fe1dec2008-11-19 18:56:50 +000012647 // If there are two consecutive llvm.dbg.stoppoint calls then
12648 // it is likely that the optimizer deleted code in between these
12649 // two intrinsics.
12650 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12651 if (DBI_Next) {
12652 if (DBI_Prev
12653 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12654 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012655 IC.Worklist.Remove(DBI_Prev);
Devang Patel7fe1dec2008-11-19 18:56:50 +000012656 DBI_Prev->eraseFromParent();
12657 }
12658 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012659 } else {
12660 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012661 }
12662
Chris Lattner7a1e9242009-08-30 06:13:40 +000012663 IC.Worklist.Add(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012664 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012665
12666 // Recursively visit successors. If this is a branch or switch on a
12667 // constant, only visit the reachable successor.
12668 TerminatorInst *TI = BB->getTerminator();
12669 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12670 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12671 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012672 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012673 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012674 continue;
12675 }
12676 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12677 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12678 // See if this is an explicit destination.
12679 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12680 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012681 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012682 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012683 continue;
12684 }
12685
12686 // Otherwise it is the default destination.
12687 Worklist.push_back(SI->getSuccessor(0));
12688 continue;
12689 }
12690 }
12691
12692 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12693 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012694 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012695}
12696
Chris Lattnerec9c3582007-03-03 02:04:50 +000012697bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012698 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012699 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012700
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012701 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12702 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012703
Chris Lattnerb3d59702005-07-07 20:40:38 +000012704 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012705 // Do a depth-first traversal of the function, populate the worklist with
12706 // the reachable instructions. Ignore blocks that are not reachable. Keep
12707 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012708 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012709 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012710
Chris Lattnerb3d59702005-07-07 20:40:38 +000012711 // Do a quick scan over the function. If we find any blocks that are
12712 // unreachable, remove any instructions inside of them. This prevents
12713 // the instcombine code from having to deal with some bad special cases.
12714 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12715 if (!Visited.count(BB)) {
12716 Instruction *Term = BB->getTerminator();
12717 while (Term != BB->begin()) { // Remove instrs bottom-up
12718 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012719
Chris Lattnerbdff5482009-08-23 04:37:46 +000012720 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012721 // A debug intrinsic shouldn't force another iteration if we weren't
12722 // going to do one without it.
12723 if (!isa<DbgInfoIntrinsic>(I)) {
12724 ++NumDeadInst;
12725 Changed = true;
12726 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012727 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012728 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012729 I->eraseFromParent();
12730 }
12731 }
12732 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012733
Chris Lattner873ff012009-08-30 05:55:36 +000012734 while (!Worklist.isEmpty()) {
12735 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012736 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012737
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012738 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012739 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012740 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012741 EraseInstFromFunction(*I);
12742 ++NumDeadInst;
Chris Lattner1e19d602009-01-31 07:04:22 +000012743 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012744 continue;
12745 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012746
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012747 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012748 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012749 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012750
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012751 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012752 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012753 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012754 EraseInstFromFunction(*I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012755 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012756 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012757 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012758
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012759 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012760 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012761 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12762 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012763 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12764 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012765 if (NewC != CE) {
12766 i->set(NewC);
12767 Changed = true;
12768 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012769 }
12770
Chris Lattnerea1c4542004-12-08 23:43:58 +000012771 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012772 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012773 BasicBlock *BB = I->getParent();
12774 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12775 if (UserParent != BB) {
12776 bool UserIsSuccessor = false;
12777 // See if the user is one of our successors.
12778 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12779 if (*SI == UserParent) {
12780 UserIsSuccessor = true;
12781 break;
12782 }
12783
12784 // If the user is one of our immediate successors, and if that successor
12785 // only has us as a predecessors (we'd have to split the critical edge
12786 // otherwise), we can keep going.
12787 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12788 next(pred_begin(UserParent)) == pred_end(UserParent))
12789 // Okay, the CFG is simple enough, try to sink this instruction.
12790 Changed |= TryToSinkInstruction(I, UserParent);
12791 }
12792 }
12793
Chris Lattner74381062009-08-30 07:44:24 +000012794 // Now that we have an instruction, try combining it to simplify it.
12795 Builder->SetInsertPoint(I->getParent(), I);
12796
Reid Spencera9b81012007-03-26 17:44:01 +000012797#ifndef NDEBUG
12798 std::string OrigI;
12799#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012800 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattner74381062009-08-30 07:44:24 +000012801
Chris Lattner90ac28c2002-08-02 19:29:35 +000012802 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012803 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012804 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012805 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012806 DEBUG(errs() << "IC: Old = " << *I << '\n'
12807 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012808
Chris Lattnerf523d062004-06-09 05:08:07 +000012809 // Everything uses the new instruction now.
12810 I->replaceAllUsesWith(Result);
12811
12812 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012813 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012814 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012815
Chris Lattner6934a042007-02-11 01:23:03 +000012816 // Move the name to the new instruction first.
12817 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012818
12819 // Insert the new instruction into the basic block...
12820 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012821 BasicBlock::iterator InsertPos = I;
12822
12823 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12824 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12825 ++InsertPos;
12826
12827 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012828
Chris Lattner7a1e9242009-08-30 06:13:40 +000012829 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012830 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012831#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012832 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12833 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012834#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012835
Chris Lattner90ac28c2002-08-02 19:29:35 +000012836 // If the instruction was modified, it's possible that it is now dead.
12837 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012838 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012839 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012840 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012841 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012842 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012843 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012844 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012845 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012846 }
12847 }
12848
Chris Lattner873ff012009-08-30 05:55:36 +000012849 Worklist.Zap();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012850 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012851}
12852
Chris Lattnerec9c3582007-03-03 02:04:50 +000012853
12854bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012855 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012856 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000012857
Chris Lattner74381062009-08-30 07:44:24 +000012858
12859 /// Builder - This is an IRBuilder that automatically inserts new
12860 /// instructions into the worklist when they are created.
12861 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12862 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12863 InstCombineIRInserter(Worklist));
12864 Builder = &TheBuilder;
12865
Chris Lattnerec9c3582007-03-03 02:04:50 +000012866 bool EverMadeChange = false;
12867
12868 // Iterate while there is work to do.
12869 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012870 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012871 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012872
12873 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012874 return EverMadeChange;
12875}
12876
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012877FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012878 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012879}