blob: 58a30d6bf4ea4750d3582f14be1141e798d9ae5b [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner173234a2008-06-02 01:18:21 +000047#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000048#include "llvm/Target/TargetData.h"
49#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000051#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000052#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000053#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000054#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000055#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000056#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000057#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000058#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000059#include "llvm/Support/PatternMatch.h"
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000060#include "llvm/Support/TargetFolder.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000061#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000062#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000063#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000064#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000065#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000066#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000067#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000068#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000069using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000070using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072STATISTIC(NumCombined , "Number of insts combined");
73STATISTIC(NumConstProp, "Number of constant folds");
74STATISTIC(NumDeadInst , "Number of dead inst eliminated");
75STATISTIC(NumDeadStore, "Number of dead stores eliminated");
76STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000077
Chris Lattner0e5f4992006-12-19 21:40:18 +000078namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000079 /// InstCombineWorklist - This is the worklist management logic for
80 /// InstCombine.
81 class InstCombineWorklist {
82 SmallVector<Instruction*, 256> Worklist;
83 DenseMap<Instruction*, unsigned> WorklistMap;
84
85 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
86 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
87 public:
88 InstCombineWorklist() {}
89
90 bool isEmpty() const { return Worklist.empty(); }
91
92 /// Add - Add the specified instruction to the worklist if it isn't already
93 /// in it.
94 void Add(Instruction *I) {
Jeffrey Yasskin43069632009-10-08 00:12:24 +000095 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
96 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +000097 Worklist.push_back(I);
Jeffrey Yasskin43069632009-10-08 00:12:24 +000098 }
Chris Lattner873ff012009-08-30 05:55:36 +000099 }
100
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000101 void AddValue(Value *V) {
102 if (Instruction *I = dyn_cast<Instruction>(V))
103 Add(I);
104 }
105
Chris Lattner67f7d542009-10-12 03:58:40 +0000106 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
107 /// which should only be done when the worklist is empty and when the group
108 /// has no duplicates.
109 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
110 assert(Worklist.empty() && "Worklist must be empty to add initial group");
111 Worklist.reserve(NumEntries+16);
112 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
113 for (; NumEntries; --NumEntries) {
114 Instruction *I = List[NumEntries-1];
115 WorklistMap.insert(std::make_pair(I, Worklist.size()));
116 Worklist.push_back(I);
117 }
118 }
119
Chris Lattner7a1e9242009-08-30 06:13:40 +0000120 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000121 void Remove(Instruction *I) {
122 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
123 if (It == WorklistMap.end()) return; // Not in worklist.
124
125 // Don't bother moving everything down, just null out the slot.
126 Worklist[It->second] = 0;
127
128 WorklistMap.erase(It);
129 }
130
131 Instruction *RemoveOne() {
132 Instruction *I = Worklist.back();
133 Worklist.pop_back();
134 WorklistMap.erase(I);
135 return I;
136 }
137
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000138 /// AddUsersToWorkList - When an instruction is simplified, add all users of
139 /// the instruction to the work lists because they might get more simplified
140 /// now.
141 ///
142 void AddUsersToWorkList(Instruction &I) {
143 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
144 UI != UE; ++UI)
145 Add(cast<Instruction>(*UI));
146 }
147
Chris Lattner873ff012009-08-30 05:55:36 +0000148
149 /// Zap - check that the worklist is empty and nuke the backing store for
150 /// the map if it is large.
151 void Zap() {
152 assert(WorklistMap.empty() && "Worklist empty, but map not?");
153
154 // Do an explicit clear, this shrinks the map if needed.
155 WorklistMap.clear();
156 }
157 };
158} // end anonymous namespace.
159
160
161namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000162 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
163 /// just like the normal insertion helper, but also adds any new instructions
164 /// to the instcombine worklist.
165 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
166 InstCombineWorklist &Worklist;
167 public:
168 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
169
170 void InsertHelper(Instruction *I, const Twine &Name,
171 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
172 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
173 Worklist.Add(I);
174 }
175 };
176} // end anonymous namespace
177
178
179namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000180 class InstCombiner : public FunctionPass,
181 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000182 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000183 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000184 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000185 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000186 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000187 InstCombineWorklist Worklist;
188
Chris Lattner74381062009-08-30 07:44:24 +0000189 /// Builder - This is an IRBuilder that automatically inserts new
190 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +0000191 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000192 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000193
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000194 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000195 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000196
Owen Andersone922c022009-07-22 00:24:57 +0000197 LLVMContext *Context;
198 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000199
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000200 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000201 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000202
203 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000204
Chris Lattner97e52e42002-04-28 21:27:06 +0000205 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000206 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000207 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000208 }
209
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000210 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000211
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000212 // Visitation implementation - Implement instruction combining for different
213 // instruction types. The semantics are as follows:
214 // Return Value:
215 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000216 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000217 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000218 //
Chris Lattner7e708292002-06-25 16:13:24 +0000219 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000220 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner092543c2009-11-04 08:05:20 +0000221 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Chris Lattner7e708292002-06-25 16:13:24 +0000222 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000223 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000224 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000225 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000226 Instruction *visitURem(BinaryOperator &I);
227 Instruction *visitSRem(BinaryOperator &I);
228 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000229 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000230 Instruction *commonRemTransforms(BinaryOperator &I);
231 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000232 Instruction *commonDivTransforms(BinaryOperator &I);
233 Instruction *commonIDivTransforms(BinaryOperator &I);
234 Instruction *visitUDiv(BinaryOperator &I);
235 Instruction *visitSDiv(BinaryOperator &I);
236 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000237 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000238 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000239 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000240 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000241 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000242 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000243 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000244 Instruction *visitOr (BinaryOperator &I);
245 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000246 Instruction *visitShl(BinaryOperator &I);
247 Instruction *visitAShr(BinaryOperator &I);
248 Instruction *visitLShr(BinaryOperator &I);
249 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000250 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
251 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000252 Instruction *visitFCmpInst(FCmpInst &I);
253 Instruction *visitICmpInst(ICmpInst &I);
254 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000255 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
256 Instruction *LHS,
257 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000258 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
259 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000260
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000261 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000262 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000263 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000264 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000265 Instruction *commonCastTransforms(CastInst &CI);
266 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000267 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000268 Instruction *visitTrunc(TruncInst &CI);
269 Instruction *visitZExt(ZExtInst &CI);
270 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000271 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000272 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000273 Instruction *visitFPToUI(FPToUIInst &FI);
274 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000275 Instruction *visitUIToFP(CastInst &CI);
276 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000277 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000278 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000279 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000280 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
281 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000282 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000283 Instruction *visitSelectInst(SelectInst &SI);
284 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000285 Instruction *visitCallInst(CallInst &CI);
286 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner9956c052009-11-08 19:23:30 +0000287
288 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Chris Lattner7e708292002-06-25 16:13:24 +0000289 Instruction *visitPHINode(PHINode &PN);
290 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000291 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000292 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000293 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000294 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000295 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000296 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000297 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000298 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000299 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000300 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000301
302 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000303 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000304
Chris Lattner9fe38862003-06-19 17:00:31 +0000305 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000306 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000307 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000308 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000309 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
310 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000311 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000312 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
313
Chris Lattner9fe38862003-06-19 17:00:31 +0000314
Chris Lattner28977af2004-04-05 01:30:19 +0000315 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000316 // InsertNewInstBefore - insert an instruction New before instruction Old
317 // in the program. Add the new instruction to the worklist.
318 //
Chris Lattner955f3312004-09-28 21:48:02 +0000319 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000320 assert(New && New->getParent() == 0 &&
321 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000322 BasicBlock *BB = Old.getParent();
323 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000324 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000325 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000326 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000327
Chris Lattner8b170942002-08-09 23:47:40 +0000328 // ReplaceInstUsesWith - This method is to be used when an instruction is
329 // found to be dead, replacable with another preexisting expression. Here
330 // we add all uses of I to the worklist, replace all uses of I with the new
331 // value, then return I, so that the inst combiner will know that I was
332 // modified.
333 //
334 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000335 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000336
337 // If we are replacing the instruction with itself, this must be in a
338 // segment of unreachable code, so just clobber the instruction.
339 if (&I == V)
340 V = UndefValue::get(I.getType());
341
342 I.replaceAllUsesWith(V);
343 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000344 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000345
346 // EraseInstFromFunction - When dealing with an instruction that has side
347 // effects or produces a void value, we can't rely on DCE to delete the
348 // instruction. Instead, visit methods should return the value returned by
349 // this function.
350 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000351 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000352
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000353 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000354 // Make sure that we reprocess all operands now that we reduced their
355 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000356 if (I.getNumOperands() < 8) {
357 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
358 if (Instruction *Op = dyn_cast<Instruction>(*i))
359 Worklist.Add(Op);
360 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000361 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000362 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000363 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000364 return 0; // Don't do anything with FI
365 }
Chris Lattner173234a2008-06-02 01:18:21 +0000366
367 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
368 APInt &KnownOne, unsigned Depth = 0) const {
369 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
370 }
371
372 bool MaskedValueIsZero(Value *V, const APInt &Mask,
373 unsigned Depth = 0) const {
374 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
375 }
376 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
377 return llvm::ComputeNumSignBits(Op, TD, Depth);
378 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000379
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000380 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000381
Reid Spencere4d87aa2006-12-23 06:05:41 +0000382 /// SimplifyCommutative - This performs a few simplifications for
383 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000384 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000385
Chris Lattner886ab6c2009-01-31 08:15:18 +0000386 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
387 /// based on the demanded bits.
388 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
389 APInt& KnownZero, APInt& KnownOne,
390 unsigned Depth);
391 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000392 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000393 unsigned Depth=0);
394
395 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
396 /// SimplifyDemandedBits knows about. See if the instruction has any
397 /// properties that allow us to simplify its operands.
398 bool SimplifyDemandedInstructionBits(Instruction &Inst);
399
Evan Cheng388df622009-02-03 10:05:09 +0000400 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
401 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000402
Chris Lattner5d1704d2009-09-27 19:57:57 +0000403 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
404 // which has a PHI node as operand #0, see if we can fold the instruction
405 // into the PHI (which is only possible if all operands to the PHI are
406 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000407 //
408 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
409 // that would normally be unprofitable because they strongly encourage jump
410 // threading.
411 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000412
Chris Lattnerbac32862004-11-14 19:13:23 +0000413 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
414 // operator and they all are only used by the PHI, PHI together their
415 // inputs, and do the operation once, to the result of the PHI.
416 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000417 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000418 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner751a3622009-11-01 20:04:24 +0000419 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000420
Chris Lattner7da52b22006-11-01 04:51:18 +0000421
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000422 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
423 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000424
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000425 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000426 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000427 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000428 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000429 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000430 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000431 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000432 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000433 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000434
Chris Lattnerafe91a52006-06-15 19:07:26 +0000435
Reid Spencerc55b2432006-12-13 18:21:21 +0000436 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000437
Dan Gohman6de29f82009-06-15 22:12:54 +0000438 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000439 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000440 unsigned GetOrEnforceKnownAlignment(Value *V,
441 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000442
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000443 };
Chris Lattner873ff012009-08-30 05:55:36 +0000444} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000445
Dan Gohman844731a2008-05-13 00:00:25 +0000446char InstCombiner::ID = 0;
447static RegisterPass<InstCombiner>
448X("instcombine", "Combine redundant instructions");
449
Chris Lattner4f98c562003-03-10 21:43:22 +0000450// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000451// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000452static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000453 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000454 if (BinaryOperator::isNeg(V) ||
455 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000456 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000457 return 3;
458 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000459 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000460 if (isa<Argument>(V)) return 3;
461 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000462}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000463
Chris Lattnerc8802d22003-03-11 00:12:48 +0000464// isOnlyUse - Return true if this instruction will be deleted if we stop using
465// it.
466static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000467 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000468}
469
Chris Lattner4cb170c2004-02-23 06:38:22 +0000470// getPromotedType - Return the specified type promoted as it would be to pass
471// though a va_arg area...
472static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000473 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
474 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000475 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000476 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000477 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000478}
479
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000480/// getBitCastOperand - If the specified operand is a CastInst, a constant
481/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
482/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000483static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000484 if (Operator *O = dyn_cast<Operator>(V)) {
485 if (O->getOpcode() == Instruction::BitCast)
486 return O->getOperand(0);
487 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
488 if (GEP->hasAllZeroIndices())
489 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000490 }
Chris Lattnereed48272005-09-13 00:40:14 +0000491 return 0;
492}
493
Reid Spencer3da59db2006-11-27 01:05:10 +0000494/// This function is a wrapper around CastInst::isEliminableCastPair. It
495/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000496static Instruction::CastOps
497isEliminableCastPair(
498 const CastInst *CI, ///< The first cast instruction
499 unsigned opcode, ///< The opcode of the second cast instruction
500 const Type *DstTy, ///< The target type for the second cast instruction
501 TargetData *TD ///< The target data for pointer size
502) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000503
Reid Spencer3da59db2006-11-27 01:05:10 +0000504 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
505 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000506
Reid Spencer3da59db2006-11-27 01:05:10 +0000507 // Get the opcodes of the two Cast instructions
508 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
509 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000510
Chris Lattnera0e69692009-03-24 18:35:40 +0000511 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000512 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000513 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000514
515 // We don't want to form an inttoptr or ptrtoint that converts to an integer
516 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000517 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000518 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000519 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000520 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000521 Res = 0;
522
523 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000524}
525
526/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
527/// in any code being generated. It does not require codegen if V is simple
528/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000529static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
530 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000531 if (V->getType() == Ty || isa<Constant>(V)) return false;
532
Chris Lattner01575b72006-05-25 23:24:33 +0000533 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000534 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000535 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000536 return false;
537 return true;
538}
539
Chris Lattner4f98c562003-03-10 21:43:22 +0000540// SimplifyCommutative - This performs a few simplifications for commutative
541// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000542//
Chris Lattner4f98c562003-03-10 21:43:22 +0000543// 1. Order operands such that they are listed from right (least complex) to
544// left (most complex). This puts constants before unary operators before
545// binary operators.
546//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000547// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
548// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000549//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000551 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000552 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000553 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000554
Chris Lattner4f98c562003-03-10 21:43:22 +0000555 if (!I.isAssociative()) return Changed;
556 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000557 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
558 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
559 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000560 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000561 cast<Constant>(I.getOperand(1)),
562 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000563 I.setOperand(0, Op->getOperand(0));
564 I.setOperand(1, Folded);
565 return true;
566 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
567 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
568 isOnlyUse(Op) && isOnlyUse(Op1)) {
569 Constant *C1 = cast<Constant>(Op->getOperand(1));
570 Constant *C2 = cast<Constant>(Op1->getOperand(1));
571
572 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000573 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000574 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000575 Op1->getOperand(0),
576 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000577 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000578 I.setOperand(0, New);
579 I.setOperand(1, Folded);
580 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000581 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000582 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000583 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000584}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000585
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
Chris Lattner48b59ec2009-10-26 15:40:07 +0000623/// isFreeToInvert - Return true if the specified value is free to invert (apply
624/// ~ to). This happens in cases where the ~ can be eliminated.
625static inline bool isFreeToInvert(Value *V) {
626 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000627 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000628 return true;
629
630 // Constants can be considered to be not'ed values.
631 if (isa<ConstantInt>(V))
632 return true;
633
634 // Compares can be inverted if they have a single use.
635 if (CmpInst *CI = dyn_cast<CmpInst>(V))
636 return CI->hasOneUse();
637
638 return false;
639}
640
641static inline Value *dyn_castNotVal(Value *V) {
642 // If this is not(not(x)) don't return that this is a not: we want the two
643 // not's to be folded first.
644 if (BinaryOperator::isNot(V)) {
645 Value *Operand = BinaryOperator::getNotArgument(V);
646 if (!isFreeToInvert(Operand))
647 return Operand;
648 }
Chris Lattner8d969642003-03-10 23:06:50 +0000649
650 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000651 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000652 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000653 return 0;
654}
655
Chris Lattner48b59ec2009-10-26 15:40:07 +0000656
657
Chris Lattnerc8802d22003-03-11 00:12:48 +0000658// dyn_castFoldableMul - If this value is a multiply that can be folded into
659// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000660// non-constant operand of the multiply, and set CST to point to the multiplier.
661// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000662//
Dan Gohman186a6362009-08-12 16:04:34 +0000663static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000664 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000665 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000666 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000667 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000668 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000669 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000670 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000671 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000672 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000673 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000674 CST = ConstantInt::get(V->getType()->getContext(),
675 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000676 return I->getOperand(0);
677 }
678 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000679 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000680}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000681
Reid Spencer7177c3a2007-03-25 05:33:51 +0000682/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000683static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000684 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000685 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000686}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000687/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000688static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000689 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000690 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000691}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000692/// MultiplyOverflows - True if the multiply can not be expressed in an int
693/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000694static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000695 uint32_t W = C1->getBitWidth();
696 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
697 if (sign) {
698 LHSExt.sext(W * 2);
699 RHSExt.sext(W * 2);
700 } else {
701 LHSExt.zext(W * 2);
702 RHSExt.zext(W * 2);
703 }
704
705 APInt MulExt = LHSExt * RHSExt;
706
707 if (sign) {
708 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
709 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
710 return MulExt.slt(Min) || MulExt.sgt(Max);
711 } else
712 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
713}
Chris Lattner955f3312004-09-28 21:48:02 +0000714
Reid Spencere7816b52007-03-08 01:52:58 +0000715
Chris Lattner255d8912006-02-11 09:31:47 +0000716/// ShrinkDemandedConstant - Check to see if the specified operand of the
717/// specified instruction is a constant integer. If so, check to see if there
718/// are any bits set in the constant that are not demanded. If so, shrink the
719/// constant and return true.
720static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000721 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000722 assert(I && "No instruction?");
723 assert(OpNo < I->getNumOperands() && "Operand index too large");
724
725 // If the operand is not a constant integer, nothing to do.
726 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
727 if (!OpC) return false;
728
729 // If there are no bits set that aren't demanded, nothing to do.
730 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
731 if ((~Demanded & OpC->getValue()) == 0)
732 return false;
733
734 // This instruction is producing bits that are not demanded. Shrink the RHS.
735 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000736 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000737 return true;
738}
739
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000740// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
741// set of known zero and one bits, compute the maximum and minimum values that
742// could have the specified known zero and known one bits, returning them in
743// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000744static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000745 const APInt& KnownOne,
746 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000747 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
748 KnownZero.getBitWidth() == Min.getBitWidth() &&
749 KnownZero.getBitWidth() == Max.getBitWidth() &&
750 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000751 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000752
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000753 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
754 // bit if it is unknown.
755 Min = KnownOne;
756 Max = KnownOne|UnknownBits;
757
Dan Gohman1c8491e2009-04-25 17:12:48 +0000758 if (UnknownBits.isNegative()) { // Sign bit is unknown
759 Min.set(Min.getBitWidth()-1);
760 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000761 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000762}
763
764// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
765// a set of known zero and one bits, compute the maximum and minimum values that
766// could have the specified known zero and known one bits, returning them in
767// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000768static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000769 const APInt &KnownOne,
770 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000771 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
772 KnownZero.getBitWidth() == Min.getBitWidth() &&
773 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000774 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000775 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000776
777 // The minimum value is when the unknown bits are all zeros.
778 Min = KnownOne;
779 // The maximum value is when the unknown bits are all ones.
780 Max = KnownOne|UnknownBits;
781}
Chris Lattner255d8912006-02-11 09:31:47 +0000782
Chris Lattner886ab6c2009-01-31 08:15:18 +0000783/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
784/// SimplifyDemandedBits knows about. See if the instruction has any
785/// properties that allow us to simplify its operands.
786bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000787 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000788 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
789 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
790
791 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
792 KnownZero, KnownOne, 0);
793 if (V == 0) return false;
794 if (V == &Inst) return true;
795 ReplaceInstUsesWith(Inst, V);
796 return true;
797}
798
799/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
800/// specified instruction operand if possible, updating it in place. It returns
801/// true if it made any change and false otherwise.
802bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
803 APInt &KnownZero, APInt &KnownOne,
804 unsigned Depth) {
805 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
806 KnownZero, KnownOne, Depth);
807 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000808 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000809 return true;
810}
811
812
813/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
814/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000815/// that only the bits set in DemandedMask of the result of V are ever used
816/// downstream. Consequently, depending on the mask and V, it may be possible
817/// to replace V with a constant or one of its operands. In such cases, this
818/// function does the replacement and returns true. In all other cases, it
819/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000820/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000821/// to be zero in the expression. These are provided to potentially allow the
822/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
823/// the expression. KnownOne and KnownZero always follow the invariant that
824/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
825/// the bits in KnownOne and KnownZero may only be accurate for those bits set
826/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
827/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000828///
829/// This returns null if it did not change anything and it permits no
830/// simplification. This returns V itself if it did some simplification of V's
831/// operands based on the information about what bits are demanded. This returns
832/// some other non-null value if it found out that V is equal to another value
833/// in the context where the specified bits are demanded, but not for all users.
834Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
835 APInt &KnownZero, APInt &KnownOne,
836 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000837 assert(V != 0 && "Null pointer of Value???");
838 assert(Depth <= 6 && "Limit Search Depth");
839 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000840 const Type *VTy = V->getType();
841 assert((TD || !isa<PointerType>(VTy)) &&
842 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000843 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
844 (!VTy->isIntOrIntVector() ||
845 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000846 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000847 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000848 "Value *V, DemandedMask, KnownZero and KnownOne "
849 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000850 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
851 // We know all of the bits for a constant!
852 KnownOne = CI->getValue() & DemandedMask;
853 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000854 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000855 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000856 if (isa<ConstantPointerNull>(V)) {
857 // We know all of the bits for a constant!
858 KnownOne.clear();
859 KnownZero = DemandedMask;
860 return 0;
861 }
862
Chris Lattner08d2cc72009-01-31 07:26:06 +0000863 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000864 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000865 if (DemandedMask == 0) { // Not demanding any bits from V.
866 if (isa<UndefValue>(V))
867 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000868 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000869 }
870
Chris Lattner4598c942009-01-31 08:24:16 +0000871 if (Depth == 6) // Limit search depth.
872 return 0;
873
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000874 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
875 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
876
Dan Gohman1c8491e2009-04-25 17:12:48 +0000877 Instruction *I = dyn_cast<Instruction>(V);
878 if (!I) {
879 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
880 return 0; // Only analyze instructions.
881 }
882
Chris Lattner4598c942009-01-31 08:24:16 +0000883 // If there are multiple uses of this value and we aren't at the root, then
884 // we can't do any simplifications of the operands, because DemandedMask
885 // only reflects the bits demanded by *one* of the users.
886 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000887 // Despite the fact that we can't simplify this instruction in all User's
888 // context, we can at least compute the knownzero/knownone bits, and we can
889 // do simplifications that apply to *just* the one user if we know that
890 // this instruction has a simpler value in that context.
891 if (I->getOpcode() == Instruction::And) {
892 // If either the LHS or the RHS are Zero, the result is zero.
893 ComputeMaskedBits(I->getOperand(1), DemandedMask,
894 RHSKnownZero, RHSKnownOne, Depth+1);
895 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
896 LHSKnownZero, LHSKnownOne, Depth+1);
897
898 // If all of the demanded bits are known 1 on one side, return the other.
899 // These bits cannot contribute to the result of the 'and' in this
900 // context.
901 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
902 (DemandedMask & ~LHSKnownZero))
903 return I->getOperand(0);
904 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
905 (DemandedMask & ~RHSKnownZero))
906 return I->getOperand(1);
907
908 // If all of the demanded bits in the inputs are known zeros, return zero.
909 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000910 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000911
912 } else if (I->getOpcode() == Instruction::Or) {
913 // We can simplify (X|Y) -> X or Y in the user's context if we know that
914 // only bits from X or Y are demanded.
915
916 // If either the LHS or the RHS are One, the result is One.
917 ComputeMaskedBits(I->getOperand(1), DemandedMask,
918 RHSKnownZero, RHSKnownOne, Depth+1);
919 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
920 LHSKnownZero, LHSKnownOne, Depth+1);
921
922 // If all of the demanded bits are known zero on one side, return the
923 // other. These bits cannot contribute to the result of the 'or' in this
924 // context.
925 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
926 (DemandedMask & ~LHSKnownOne))
927 return I->getOperand(0);
928 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
929 (DemandedMask & ~RHSKnownOne))
930 return I->getOperand(1);
931
932 // If all of the potentially set bits on one side are known to be set on
933 // the other side, just use the 'other' side.
934 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
935 (DemandedMask & (~RHSKnownZero)))
936 return I->getOperand(0);
937 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
938 (DemandedMask & (~LHSKnownZero)))
939 return I->getOperand(1);
940 }
941
Chris Lattner4598c942009-01-31 08:24:16 +0000942 // Compute the KnownZero/KnownOne bits to simplify things downstream.
943 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
944 return 0;
945 }
946
947 // If this is the root being simplified, allow it to have multiple uses,
948 // just set the DemandedMask to all bits so that we can try to simplify the
949 // operands. This allows visitTruncInst (for example) to simplify the
950 // operand of a trunc without duplicating all the logic below.
951 if (Depth == 0 && !V->hasOneUse())
952 DemandedMask = APInt::getAllOnesValue(BitWidth);
953
Reid Spencer8cb68342007-03-12 17:25:59 +0000954 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000955 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000956 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000957 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000958 case Instruction::And:
959 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000960 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
961 RHSKnownZero, RHSKnownOne, Depth+1) ||
962 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000963 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000964 return I;
965 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
966 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000967
968 // If all of the demanded bits are known 1 on one side, return the other.
969 // These bits cannot contribute to the result of the 'and'.
970 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
971 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000972 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000973 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
974 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000975 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000976
977 // If all of the demanded bits in the inputs are known zeros, return zero.
978 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000979 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000980
981 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000982 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000983 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000984
985 // Output known-1 bits are only known if set in both the LHS & RHS.
986 RHSKnownOne &= LHSKnownOne;
987 // Output known-0 are known to be clear if zero in either the LHS | RHS.
988 RHSKnownZero |= LHSKnownZero;
989 break;
990 case Instruction::Or:
991 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000992 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
993 RHSKnownZero, RHSKnownOne, Depth+1) ||
994 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000995 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000996 return I;
997 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
998 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000999
1000 // If all of the demanded bits are known zero on one side, return the other.
1001 // These bits cannot contribute to the result of the 'or'.
1002 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1003 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001004 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001005 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1006 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001007 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001008
1009 // If all of the potentially set bits on one side are known to be set on
1010 // the other side, just use the 'other' side.
1011 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1012 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001013 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001014 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1015 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001016 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001017
1018 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001019 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001020 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001021
1022 // Output known-0 bits are only known if clear in both the LHS & RHS.
1023 RHSKnownZero &= LHSKnownZero;
1024 // Output known-1 are known to be set if set in either the LHS | RHS.
1025 RHSKnownOne |= LHSKnownOne;
1026 break;
1027 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001028 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1029 RHSKnownZero, RHSKnownOne, Depth+1) ||
1030 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001031 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001032 return I;
1033 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1034 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001035
1036 // If all of the demanded bits are known zero on one side, return the other.
1037 // These bits cannot contribute to the result of the 'xor'.
1038 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001039 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001040 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001041 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001042
1043 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1044 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1045 (RHSKnownOne & LHSKnownOne);
1046 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1047 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1048 (RHSKnownOne & LHSKnownZero);
1049
1050 // If all of the demanded bits are known to be zero on one side or the
1051 // other, turn this into an *inclusive* or.
1052 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001053 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1054 Instruction *Or =
1055 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1056 I->getName());
1057 return InsertNewInstBefore(Or, *I);
1058 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001059
1060 // If all of the demanded bits on one side are known, and all of the set
1061 // bits on that side are also known to be set on the other side, turn this
1062 // into an AND, as we know the bits will be cleared.
1063 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1064 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1065 // all known
1066 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001067 Constant *AndC = Constant::getIntegerValue(VTy,
1068 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001069 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001070 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001071 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001072 }
1073 }
1074
1075 // If the RHS is a constant, see if we can simplify it.
1076 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001077 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001079
Chris Lattnerd0883142009-10-11 22:22:13 +00001080 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1081 // are flipping are known to be set, then the xor is just resetting those
1082 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1083 // simplifying both of them.
1084 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1085 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1086 isa<ConstantInt>(I->getOperand(1)) &&
1087 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1088 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1089 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1090 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1091 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1092
1093 Constant *AndC =
1094 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1095 Instruction *NewAnd =
1096 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1097 InsertNewInstBefore(NewAnd, *I);
1098
1099 Constant *XorC =
1100 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1101 Instruction *NewXor =
1102 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1103 return InsertNewInstBefore(NewXor, *I);
1104 }
1105
1106
Reid Spencer8cb68342007-03-12 17:25:59 +00001107 RHSKnownZero = KnownZeroOut;
1108 RHSKnownOne = KnownOneOut;
1109 break;
1110 }
1111 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001112 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1113 RHSKnownZero, RHSKnownOne, Depth+1) ||
1114 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001115 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001116 return I;
1117 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1118 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001119
1120 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001121 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1122 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001123 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001124
1125 // Only known if known in both the LHS and RHS.
1126 RHSKnownOne &= LHSKnownOne;
1127 RHSKnownZero &= LHSKnownZero;
1128 break;
1129 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001130 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001131 DemandedMask.zext(truncBf);
1132 RHSKnownZero.zext(truncBf);
1133 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001134 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001135 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001136 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001137 DemandedMask.trunc(BitWidth);
1138 RHSKnownZero.trunc(BitWidth);
1139 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001140 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001141 break;
1142 }
1143 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001144 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001145 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001146
1147 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1148 if (const VectorType *SrcVTy =
1149 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1150 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1151 // Don't touch a bitcast between vectors of different element counts.
1152 return false;
1153 } else
1154 // Don't touch a scalar-to-vector bitcast.
1155 return false;
1156 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1157 // Don't touch a vector-to-scalar bitcast.
1158 return false;
1159
Chris Lattner886ab6c2009-01-31 08:15:18 +00001160 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001161 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001162 return I;
1163 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001164 break;
1165 case Instruction::ZExt: {
1166 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001167 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001168
Zhou Shengd48653a2007-03-29 04:45:55 +00001169 DemandedMask.trunc(SrcBitWidth);
1170 RHSKnownZero.trunc(SrcBitWidth);
1171 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001172 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001173 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001174 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001175 DemandedMask.zext(BitWidth);
1176 RHSKnownZero.zext(BitWidth);
1177 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001178 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001179 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001180 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001181 break;
1182 }
1183 case Instruction::SExt: {
1184 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001185 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001186
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001188 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001189
Zhou Sheng01542f32007-03-29 02:26:30 +00001190 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001191 // If any of the sign extended bits are demanded, we know that the sign
1192 // bit is demanded.
1193 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001194 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001195
Zhou Shengd48653a2007-03-29 04:45:55 +00001196 InputDemandedBits.trunc(SrcBitWidth);
1197 RHSKnownZero.trunc(SrcBitWidth);
1198 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001199 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001200 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001201 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001202 InputDemandedBits.zext(BitWidth);
1203 RHSKnownZero.zext(BitWidth);
1204 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001205 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001206
1207 // If the sign bit of the input is known set or clear, then we know the
1208 // top bits of the result.
1209
1210 // If the input sign bit is known zero, or if the NewBits are not demanded
1211 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001212 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001213 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001214 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1215 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001216 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001217 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001218 }
1219 break;
1220 }
1221 case Instruction::Add: {
1222 // Figure out what the input bits are. If the top bits of the and result
1223 // are not demanded, then the add doesn't demand them from its input
1224 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001225 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001226
1227 // If there is a constant on the RHS, there are a variety of xformations
1228 // we can do.
1229 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1230 // If null, this should be simplified elsewhere. Some of the xforms here
1231 // won't work if the RHS is zero.
1232 if (RHS->isZero())
1233 break;
1234
1235 // If the top bit of the output is demanded, demand everything from the
1236 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001237 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001238
1239 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001240 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001242 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001243
1244 // If the RHS of the add has bits set that can't affect the input, reduce
1245 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001246 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001247 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001248
1249 // Avoid excess work.
1250 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1251 break;
1252
1253 // Turn it into OR if input bits are zero.
1254 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1255 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001256 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001257 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001258 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 }
1260
1261 // We can say something about the output known-zero and known-one bits,
1262 // depending on potential carries from the input constant and the
1263 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1264 // bits set and the RHS constant is 0x01001, then we know we have a known
1265 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1266
1267 // To compute this, we first compute the potential carry bits. These are
1268 // the bits which may be modified. I'm not aware of a better way to do
1269 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001270 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001271 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001272
1273 // Now that we know which bits have carries, compute the known-1/0 sets.
1274
1275 // Bits are known one if they are known zero in one operand and one in the
1276 // other, and there is no input carry.
1277 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1278 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1279
1280 // Bits are known zero if they are known zero in both operands and there
1281 // is no input carry.
1282 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1283 } else {
1284 // If the high-bits of this ADD are not demanded, then it does not demand
1285 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001286 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001287 // Right fill the mask of bits for this ADD to demand the most
1288 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001289 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001290 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1291 LHSKnownZero, LHSKnownOne, Depth+1) ||
1292 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001293 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001294 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 }
1296 }
1297 break;
1298 }
1299 case Instruction::Sub:
1300 // If the high-bits of this SUB are not demanded, then it does not demand
1301 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001302 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001303 // Right fill the mask of bits for this SUB to demand the most
1304 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001305 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001306 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001307 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1308 LHSKnownZero, LHSKnownOne, Depth+1) ||
1309 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001311 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001312 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001313 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1314 // the known zeros and ones.
1315 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001316 break;
1317 case Instruction::Shl:
1318 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001319 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001320 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001321 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001323 return I;
1324 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001325 RHSKnownZero <<= ShiftAmt;
1326 RHSKnownOne <<= ShiftAmt;
1327 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001328 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001329 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001330 }
1331 break;
1332 case Instruction::LShr:
1333 // For a logical shift right
1334 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001335 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001336
Reid Spencer8cb68342007-03-12 17:25:59 +00001337 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001338 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001339 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001340 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001341 return I;
1342 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001343 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1344 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001345 if (ShiftAmt) {
1346 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001347 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001348 RHSKnownZero |= HighBits; // high bits known zero.
1349 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001350 }
1351 break;
1352 case Instruction::AShr:
1353 // If this is an arithmetic shift right and only the low-bit is set, we can
1354 // always convert this into a logical shr, even if the shift amount is
1355 // variable. The low bit of the shift cannot be an input sign bit unless
1356 // the shift amount is >= the size of the datatype, which is undefined.
1357 if (DemandedMask == 1) {
1358 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001359 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001360 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001361 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001362 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001363
1364 // If the sign bit is the only bit demanded by this ashr, then there is no
1365 // need to do it, the shift doesn't change the high bit.
1366 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001367 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001368
1369 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001370 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001371
Reid Spencer8cb68342007-03-12 17:25:59 +00001372 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001373 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001374 // If any of the "high bits" are demanded, we should set the sign bit as
1375 // demanded.
1376 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1377 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001378 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001379 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001380 return I;
1381 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001382 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001383 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001384 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1385 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1386
1387 // Handle the sign bits.
1388 APInt SignBit(APInt::getSignBit(BitWidth));
1389 // Adjust to where it is now in the mask.
1390 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1391
1392 // If the input sign bit is known to be zero, or if none of the top bits
1393 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001394 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001395 (HighBits & ~DemandedMask) == HighBits) {
1396 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001397 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001398 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001399 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001400 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1401 RHSKnownOne |= HighBits;
1402 }
1403 }
1404 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001405 case Instruction::SRem:
1406 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001407 APInt RA = Rem->getValue().abs();
1408 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001409 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001410 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001411
Nick Lewycky8e394322008-11-02 02:41:50 +00001412 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001413 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001414 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001415 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001416 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001417
1418 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1419 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001420
1421 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001422
Chris Lattner886ab6c2009-01-31 08:15:18 +00001423 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001424 }
1425 }
1426 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001427 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001428 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1429 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001430 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1431 KnownZero2, KnownOne2, Depth+1) ||
1432 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001433 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001434 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001435
Chris Lattner455e9ab2009-01-21 18:09:24 +00001436 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001437 Leaders = std::max(Leaders,
1438 KnownZero2.countLeadingOnes());
1439 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001440 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001441 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001442 case Instruction::Call:
1443 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1444 switch (II->getIntrinsicID()) {
1445 default: break;
1446 case Intrinsic::bswap: {
1447 // If the only bits demanded come from one byte of the bswap result,
1448 // just shift the input byte into position to eliminate the bswap.
1449 unsigned NLZ = DemandedMask.countLeadingZeros();
1450 unsigned NTZ = DemandedMask.countTrailingZeros();
1451
1452 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1453 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1454 // have 14 leading zeros, round to 8.
1455 NLZ &= ~7;
1456 NTZ &= ~7;
1457 // If we need exactly one byte, we can do this transformation.
1458 if (BitWidth-NLZ-NTZ == 8) {
1459 unsigned ResultBit = NTZ;
1460 unsigned InputBit = BitWidth-NTZ-8;
1461
1462 // Replace this with either a left or right shift to get the byte into
1463 // the right place.
1464 Instruction *NewVal;
1465 if (InputBit > ResultBit)
1466 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001467 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001468 else
1469 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001470 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001471 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001472 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001473 }
1474
1475 // TODO: Could compute known zero/one bits based on the input.
1476 break;
1477 }
1478 }
1479 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001480 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001481 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001482 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001483
1484 // If the client is only demanding bits that we know, return the known
1485 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001486 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1487 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001488 return false;
1489}
1490
Chris Lattner867b99f2006-10-05 06:55:50 +00001491
Mon P Wangaeb06d22008-11-10 04:46:22 +00001492/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001493/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001494/// actually used by the caller. This method analyzes which elements of the
1495/// operand are undef and returns that information in UndefElts.
1496///
1497/// If the information about demanded elements can be used to simplify the
1498/// operation, the operation is simplified, then the resultant value is
1499/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001500Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1501 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001502 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001503 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001504 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001505 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001506
1507 if (isa<UndefValue>(V)) {
1508 // If the entire vector is undefined, just return this info.
1509 UndefElts = EltMask;
1510 return 0;
1511 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1512 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001513 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001514 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001515
Chris Lattner867b99f2006-10-05 06:55:50 +00001516 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001517 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1518 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001519 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001520
1521 std::vector<Constant*> Elts;
1522 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001523 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001524 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001525 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001526 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1527 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001528 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001529 } else { // Otherwise, defined.
1530 Elts.push_back(CP->getOperand(i));
1531 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001532
Chris Lattner867b99f2006-10-05 06:55:50 +00001533 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001534 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001535 return NewCP != CP ? NewCP : 0;
1536 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001537 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001538 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001539
1540 // Check if this is identity. If so, return 0 since we are not simplifying
1541 // anything.
1542 if (DemandedElts == ((1ULL << VWidth) -1))
1543 return 0;
1544
Reid Spencer9d6565a2007-02-15 02:26:10 +00001545 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001546 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001547 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001548 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001549 for (unsigned i = 0; i != VWidth; ++i) {
1550 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1551 Elts.push_back(Elt);
1552 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001553 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001554 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001555 }
1556
Dan Gohman488fbfc2008-09-09 18:11:14 +00001557 // Limit search depth.
1558 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001559 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001560
1561 // If multiple users are using the root value, procede with
1562 // simplification conservatively assuming that all elements
1563 // are needed.
1564 if (!V->hasOneUse()) {
1565 // Quit if we find multiple users of a non-root value though.
1566 // They'll be handled when it's their turn to be visited by
1567 // the main instcombine process.
1568 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001569 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001570 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571
1572 // Conservatively assume that all elements are needed.
1573 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001574 }
1575
1576 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001577 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001578
1579 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001580 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001581 Value *TmpV;
1582 switch (I->getOpcode()) {
1583 default: break;
1584
1585 case Instruction::InsertElement: {
1586 // If this is a variable index, we don't know which element it overwrites.
1587 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001588 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001589 if (Idx == 0) {
1590 // Note that we can't propagate undef elt info, because we don't know
1591 // which elt is getting updated.
1592 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1593 UndefElts2, Depth+1);
1594 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1595 break;
1596 }
1597
1598 // If this is inserting an element that isn't demanded, remove this
1599 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001600 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001601 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1602 Worklist.Add(I);
1603 return I->getOperand(0);
1604 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001605
1606 // Otherwise, the element inserted overwrites whatever was there, so the
1607 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001608 APInt DemandedElts2 = DemandedElts;
1609 DemandedElts2.clear(IdxNo);
1610 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001611 UndefElts, Depth+1);
1612 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1613
1614 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001615 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001616 break;
1617 }
1618 case Instruction::ShuffleVector: {
1619 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001620 uint64_t LHSVWidth =
1621 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001622 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001623 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001624 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001625 unsigned MaskVal = Shuffle->getMaskValue(i);
1626 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001627 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001628 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001629 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001630 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001631 else
Evan Cheng388df622009-02-03 10:05:09 +00001632 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001633 }
1634 }
1635 }
1636
Nate Begeman7b254672009-02-11 22:36:25 +00001637 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001638 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001639 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001640 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1641
Nate Begeman7b254672009-02-11 22:36:25 +00001642 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001643 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1644 UndefElts3, Depth+1);
1645 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1646
1647 bool NewUndefElts = false;
1648 for (unsigned i = 0; i < VWidth; i++) {
1649 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001650 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001651 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001652 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001653 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001654 NewUndefElts = true;
1655 UndefElts.set(i);
1656 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001657 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001658 if (UndefElts3[MaskVal - LHSVWidth]) {
1659 NewUndefElts = true;
1660 UndefElts.set(i);
1661 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001662 }
1663 }
1664
1665 if (NewUndefElts) {
1666 // Add additional discovered undefs.
1667 std::vector<Constant*> Elts;
1668 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001669 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001670 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001671 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001672 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001673 Shuffle->getMaskValue(i)));
1674 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001675 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001676 MadeChange = true;
1677 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001678 break;
1679 }
Chris Lattner69878332007-04-14 22:29:23 +00001680 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001681 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001682 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1683 if (!VTy) break;
1684 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001685 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001686 unsigned Ratio;
1687
1688 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001689 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001690 // elements as are demanded of us.
1691 Ratio = 1;
1692 InputDemandedElts = DemandedElts;
1693 } else if (VWidth > InVWidth) {
1694 // Untested so far.
1695 break;
1696
1697 // If there are more elements in the result than there are in the source,
1698 // then an input element is live if any of the corresponding output
1699 // elements are live.
1700 Ratio = VWidth/InVWidth;
1701 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001702 if (DemandedElts[OutIdx])
1703 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001704 }
1705 } else {
1706 // Untested so far.
1707 break;
1708
1709 // If there are more elements in the source than there are in the result,
1710 // then an input element is live if the corresponding output element is
1711 // live.
1712 Ratio = InVWidth/VWidth;
1713 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001714 if (DemandedElts[InIdx/Ratio])
1715 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001716 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001717
Chris Lattner69878332007-04-14 22:29:23 +00001718 // div/rem demand all inputs, because they don't want divide by zero.
1719 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1720 UndefElts2, Depth+1);
1721 if (TmpV) {
1722 I->setOperand(0, TmpV);
1723 MadeChange = true;
1724 }
1725
1726 UndefElts = UndefElts2;
1727 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001728 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001729 // If there are more elements in the result than there are in the source,
1730 // then an output element is undef if the corresponding input element is
1731 // undef.
1732 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001733 if (UndefElts2[OutIdx/Ratio])
1734 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001735 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001736 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001737 // If there are more elements in the source than there are in the result,
1738 // then a result element is undef if all of the corresponding input
1739 // elements are undef.
1740 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1741 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001742 if (!UndefElts2[InIdx]) // Not undef?
1743 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001744 }
1745 break;
1746 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001747 case Instruction::And:
1748 case Instruction::Or:
1749 case Instruction::Xor:
1750 case Instruction::Add:
1751 case Instruction::Sub:
1752 case Instruction::Mul:
1753 // div/rem demand all inputs, because they don't want divide by zero.
1754 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1755 UndefElts, Depth+1);
1756 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1757 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1758 UndefElts2, Depth+1);
1759 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1760
1761 // Output elements are undefined if both are undefined. Consider things
1762 // like undef&0. The result is known zero, not undef.
1763 UndefElts &= UndefElts2;
1764 break;
1765
1766 case Instruction::Call: {
1767 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1768 if (!II) break;
1769 switch (II->getIntrinsicID()) {
1770 default: break;
1771
1772 // Binary vector operations that work column-wise. A dest element is a
1773 // function of the corresponding input elements from the two inputs.
1774 case Intrinsic::x86_sse_sub_ss:
1775 case Intrinsic::x86_sse_mul_ss:
1776 case Intrinsic::x86_sse_min_ss:
1777 case Intrinsic::x86_sse_max_ss:
1778 case Intrinsic::x86_sse2_sub_sd:
1779 case Intrinsic::x86_sse2_mul_sd:
1780 case Intrinsic::x86_sse2_min_sd:
1781 case Intrinsic::x86_sse2_max_sd:
1782 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1783 UndefElts, Depth+1);
1784 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1785 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1786 UndefElts2, Depth+1);
1787 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1788
1789 // If only the low elt is demanded and this is a scalarizable intrinsic,
1790 // scalarize it now.
1791 if (DemandedElts == 1) {
1792 switch (II->getIntrinsicID()) {
1793 default: break;
1794 case Intrinsic::x86_sse_sub_ss:
1795 case Intrinsic::x86_sse_mul_ss:
1796 case Intrinsic::x86_sse2_sub_sd:
1797 case Intrinsic::x86_sse2_mul_sd:
1798 // TODO: Lower MIN/MAX/ABS/etc
1799 Value *LHS = II->getOperand(1);
1800 Value *RHS = II->getOperand(2);
1801 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001802 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001803 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001804 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001805 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001806
1807 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001808 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001809 case Intrinsic::x86_sse_sub_ss:
1810 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001811 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001812 II->getName()), *II);
1813 break;
1814 case Intrinsic::x86_sse_mul_ss:
1815 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001816 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001817 II->getName()), *II);
1818 break;
1819 }
1820
1821 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001822 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001823 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001824 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001825 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001826 return New;
1827 }
1828 }
1829
1830 // Output elements are undefined if both are undefined. Consider things
1831 // like undef&0. The result is known zero, not undef.
1832 UndefElts &= UndefElts2;
1833 break;
1834 }
1835 break;
1836 }
1837 }
1838 return MadeChange ? I : 0;
1839}
1840
Dan Gohman45b4e482008-05-19 22:14:15 +00001841
Chris Lattner564a7272003-08-13 19:01:45 +00001842/// AssociativeOpt - Perform an optimization on an associative operator. This
1843/// function is designed to check a chain of associative operators for a
1844/// potential to apply a certain optimization. Since the optimization may be
1845/// applicable if the expression was reassociated, this checks the chain, then
1846/// reassociates the expression as necessary to expose the optimization
1847/// opportunity. This makes use of a special Functor, which must define
1848/// 'shouldApply' and 'apply' methods.
1849///
1850template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001851static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001852 unsigned Opcode = Root.getOpcode();
1853 Value *LHS = Root.getOperand(0);
1854
1855 // Quick check, see if the immediate LHS matches...
1856 if (F.shouldApply(LHS))
1857 return F.apply(Root);
1858
1859 // Otherwise, if the LHS is not of the same opcode as the root, return.
1860 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001861 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001862 // Should we apply this transform to the RHS?
1863 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1864
1865 // If not to the RHS, check to see if we should apply to the LHS...
1866 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1867 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1868 ShouldApply = true;
1869 }
1870
1871 // If the functor wants to apply the optimization to the RHS of LHSI,
1872 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1873 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001874 // Now all of the instructions are in the current basic block, go ahead
1875 // and perform the reassociation.
1876 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1877
1878 // First move the selected RHS to the LHS of the root...
1879 Root.setOperand(0, LHSI->getOperand(1));
1880
1881 // Make what used to be the LHS of the root be the user of the root...
1882 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001883 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001884 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001885 return 0;
1886 }
Chris Lattner65725312004-04-16 18:08:07 +00001887 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001888 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001889 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001890 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001891 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001892
1893 // Now propagate the ExtraOperand down the chain of instructions until we
1894 // get to LHSI.
1895 while (TmpLHSI != LHSI) {
1896 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001897 // Move the instruction to immediately before the chain we are
1898 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001899 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001900 ARI = NextLHSI;
1901
Chris Lattner564a7272003-08-13 19:01:45 +00001902 Value *NextOp = NextLHSI->getOperand(1);
1903 NextLHSI->setOperand(1, ExtraOperand);
1904 TmpLHSI = NextLHSI;
1905 ExtraOperand = NextOp;
1906 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001907
Chris Lattner564a7272003-08-13 19:01:45 +00001908 // Now that the instructions are reassociated, have the functor perform
1909 // the transformation...
1910 return F.apply(Root);
1911 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001912
Chris Lattner564a7272003-08-13 19:01:45 +00001913 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1914 }
1915 return 0;
1916}
1917
Dan Gohman844731a2008-05-13 00:00:25 +00001918namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001919
Nick Lewycky02d639f2008-05-23 04:34:58 +00001920// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001921struct AddRHS {
1922 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001923 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001924 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1925 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001926 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001927 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001928 }
1929};
1930
1931// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1932// iff C1&C2 == 0
1933struct AddMaskingAnd {
1934 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001935 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001936 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001937 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001938 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001939 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001940 }
1941 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001942 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001943 }
1944};
1945
Dan Gohman844731a2008-05-13 00:00:25 +00001946}
1947
Chris Lattner6e7ba452005-01-01 16:22:27 +00001948static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001949 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001950 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001951 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001952
Chris Lattner2eefe512004-04-09 19:05:30 +00001953 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001954 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1955 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001956
Chris Lattner2eefe512004-04-09 19:05:30 +00001957 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1958 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001959 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1960 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001961 }
1962
1963 Value *Op0 = SO, *Op1 = ConstOperand;
1964 if (!ConstIsRHS)
1965 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001966
Chris Lattner6e7ba452005-01-01 16:22:27 +00001967 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001968 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1969 SO->getName()+".op");
1970 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1971 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1972 SO->getName()+".cmp");
1973 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1974 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1975 SO->getName()+".cmp");
1976 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001977}
1978
1979// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1980// constant as the other operand, try to fold the binary operator into the
1981// select arguments. This also works for Cast instructions, which obviously do
1982// not have a second operand.
1983static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1984 InstCombiner *IC) {
1985 // Don't modify shared select instructions
1986 if (!SI->hasOneUse()) return 0;
1987 Value *TV = SI->getOperand(1);
1988 Value *FV = SI->getOperand(2);
1989
1990 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001991 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001992 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001993
Chris Lattner6e7ba452005-01-01 16:22:27 +00001994 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1995 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1996
Gabor Greif051a9502008-04-06 20:25:17 +00001997 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1998 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001999 }
2000 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002001}
2002
Chris Lattner4e998b22004-09-29 05:07:12 +00002003
Chris Lattner5d1704d2009-09-27 19:57:57 +00002004/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2005/// has a PHI node as operand #0, see if we can fold the instruction into the
2006/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002007///
2008/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2009/// that would normally be unprofitable because they strongly encourage jump
2010/// threading.
2011Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2012 bool AllowAggressive) {
2013 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002014 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002015 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002016 if (NumPHIValues == 0 ||
2017 // We normally only transform phis with a single use, unless we're trying
2018 // hard to make jump threading happen.
2019 (!PN->hasOneUse() && !AllowAggressive))
2020 return 0;
2021
2022
Chris Lattner5d1704d2009-09-27 19:57:57 +00002023 // Check to see if all of the operands of the PHI are simple constants
2024 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002025 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2026 // bail out. We don't do arbitrary constant expressions here because moving
2027 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002028 BasicBlock *NonConstBB = 0;
2029 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002030 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2031 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002032 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002033 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002034 NonConstBB = PN->getIncomingBlock(i);
2035
2036 // If the incoming non-constant value is in I's block, we have an infinite
2037 // loop.
2038 if (NonConstBB == I.getParent())
2039 return 0;
2040 }
2041
2042 // If there is exactly one non-constant value, we can insert a copy of the
2043 // operation in that block. However, if this is a critical edge, we would be
2044 // inserting the computation one some other paths (e.g. inside a loop). Only
2045 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002046 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002047 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2048 if (!BI || !BI->isUnconditional()) return 0;
2049 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002050
2051 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002052 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002053 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002054 InsertNewInstBefore(NewPN, *PN);
2055 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002056
2057 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002058 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2059 // We only currently try to fold the condition of a select when it is a phi,
2060 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002061 Value *TrueV = SI->getTrueValue();
2062 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002063 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002064 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002065 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002066 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2067 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002068 Value *InV = 0;
2069 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002070 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002071 } else {
2072 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002073 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2074 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002075 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002076 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002077 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002078 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002079 }
2080 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002081 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002082 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002083 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002084 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002085 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002086 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002087 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002088 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002089 } else {
2090 assert(PN->getIncomingBlock(i) == NonConstBB);
2091 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002092 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002093 PN->getIncomingValue(i), C, "phitmp",
2094 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002095 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002096 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002097 CI->getPredicate(),
2098 PN->getIncomingValue(i), C, "phitmp",
2099 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002100 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002101 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002102
2103 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002104 }
2105 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002106 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002107 } else {
2108 CastInst *CI = cast<CastInst>(&I);
2109 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002110 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002111 Value *InV;
2112 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002113 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002114 } else {
2115 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002116 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002117 I.getType(), "phitmp",
2118 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002119 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002120 }
2121 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002122 }
2123 }
2124 return ReplaceInstUsesWith(I, NewPN);
2125}
2126
Chris Lattner2454a2e2008-01-29 06:52:45 +00002127
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002128/// WillNotOverflowSignedAdd - Return true if we can prove that:
2129/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2130/// This basically requires proving that the add in the original type would not
2131/// overflow to change the sign bit or have a carry out.
2132bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2133 // There are different heuristics we can use for this. Here are some simple
2134 // ones.
2135
2136 // Add has the property that adding any two 2's complement numbers can only
2137 // have one carry bit which can change a sign. As such, if LHS and RHS each
2138 // have at least two sign bits, we know that the addition of the two values will
2139 // sign extend fine.
2140 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2141 return true;
2142
2143
2144 // If one of the operands only has one non-zero bit, and if the other operand
2145 // has a known-zero bit in a more significant place than it (not including the
2146 // sign bit) the ripple may go up to and fill the zero, but won't change the
2147 // sign. For example, (X & ~4) + 1.
2148
2149 // TODO: Implement.
2150
2151 return false;
2152}
2153
Chris Lattner2454a2e2008-01-29 06:52:45 +00002154
Chris Lattner7e708292002-06-25 16:13:24 +00002155Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002156 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002157 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002158
Chris Lattner66331a42004-04-10 22:01:55 +00002159 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002160 // X + undef -> undef
2161 if (isa<UndefValue>(RHS))
2162 return ReplaceInstUsesWith(I, RHS);
2163
Chris Lattner66331a42004-04-10 22:01:55 +00002164 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002165 if (RHSC->isNullValue())
2166 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002167
Chris Lattner66331a42004-04-10 22:01:55 +00002168 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002169 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002170 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002171 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002172 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002173 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002174
2175 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2176 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002177 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002178 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002179
Eli Friedman709b33d2009-07-13 22:27:52 +00002180 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002181 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002182 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002183 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002184 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002185
2186 if (isa<PHINode>(LHS))
2187 if (Instruction *NV = FoldOpIntoPhi(I))
2188 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002189
Chris Lattner4f637d42006-01-06 17:59:59 +00002190 ConstantInt *XorRHS = 0;
2191 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002192 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002193 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002194 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002195 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002196
Zhou Sheng4351c642007-04-02 08:20:41 +00002197 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002198 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2199 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002200 do {
2201 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002202 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2203 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002204 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2205 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002206 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002207 if (!MaskedValueIsZero(XorLHS,
2208 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002209 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002210 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002211 }
2212 }
2213 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002214 C0080Val = APIntOps::lshr(C0080Val, Size);
2215 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2216 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002217
Reid Spencer35c38852007-03-28 01:36:16 +00002218 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002219 // with funny bit widths then this switch statement should be removed. It
2220 // is just here to get the size of the "middle" type back up to something
2221 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002222 const Type *MiddleType = 0;
2223 switch (Size) {
2224 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002225 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2226 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2227 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002228 }
2229 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002230 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002231 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002232 }
2233 }
Chris Lattner66331a42004-04-10 22:01:55 +00002234 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002235
Owen Anderson1d0be152009-08-13 21:58:54 +00002236 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002237 return BinaryOperator::CreateXor(LHS, RHS);
2238
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002239 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002240 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002241 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002242 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002243
2244 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2245 if (RHSI->getOpcode() == Instruction::Sub)
2246 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2247 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2248 }
2249 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2250 if (LHSI->getOpcode() == Instruction::Sub)
2251 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2252 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2253 }
Robert Bocchino71698282004-07-27 21:02:21 +00002254 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002255
Chris Lattner5c4afb92002-05-08 22:46:53 +00002256 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002257 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002258 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002259 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002260 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002261 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002262 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002263 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002264 }
2265
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002266 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002267 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002268
2269 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002270 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002271 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002272 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002273
Misha Brukmanfd939082005-04-21 23:48:37 +00002274
Chris Lattner50af16a2004-11-13 19:50:12 +00002275 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002276 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002277 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002278 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002279
2280 // X*C1 + X*C2 --> X * (C1+C2)
2281 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002282 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002283 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002284 }
2285
2286 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002287 if (dyn_castFoldableMul(RHS, C2) == LHS)
2288 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002289
Chris Lattnere617c9e2007-01-05 02:17:46 +00002290 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002291 if (dyn_castNotVal(LHS) == RHS ||
2292 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002293 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002294
Chris Lattnerad3448c2003-02-18 19:57:07 +00002295
Chris Lattner564a7272003-08-13 19:01:45 +00002296 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002297 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2298 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002299 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002300
2301 // A+B --> A|B iff A and B have no bits set in common.
2302 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2303 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2304 APInt LHSKnownOne(IT->getBitWidth(), 0);
2305 APInt LHSKnownZero(IT->getBitWidth(), 0);
2306 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2307 if (LHSKnownZero != 0) {
2308 APInt RHSKnownOne(IT->getBitWidth(), 0);
2309 APInt RHSKnownZero(IT->getBitWidth(), 0);
2310 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2311
2312 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002313 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002314 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002315 }
2316 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002317
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002318 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002319 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002320 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002321 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2322 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002323 if (W != Y) {
2324 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002325 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002326 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002327 std::swap(W, X);
2328 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002329 std::swap(Y, Z);
2330 std::swap(W, X);
2331 }
2332 }
2333
2334 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002335 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002336 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002337 }
2338 }
2339 }
2340
Chris Lattner6b032052003-10-02 15:11:26 +00002341 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002342 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002343 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002344 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002345
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002346 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002347 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002348 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002349 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002350 if (Anded == CRHS) {
2351 // See if all bits from the first bit set in the Add RHS up are included
2352 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002353 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002354
2355 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002356 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002357
2358 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002359 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002360
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002361 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2362 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002363 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002364 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002365 }
2366 }
2367 }
2368
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002369 // Try to fold constant add into select arguments.
2370 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002371 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002372 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002373 }
2374
Chris Lattner42790482007-12-20 01:56:58 +00002375 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002376 {
2377 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002378 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002379 if (!SI) {
2380 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002381 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002382 }
Chris Lattner42790482007-12-20 01:56:58 +00002383 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002384 Value *TV = SI->getTrueValue();
2385 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002386 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002387
2388 // Can we fold the add into the argument of the select?
2389 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002390 if (match(FV, m_Zero()) &&
2391 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002392 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002393 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002394 if (match(TV, m_Zero()) &&
2395 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002396 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002397 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002398 }
2399 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002400
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002401 // Check for (add (sext x), y), see if we can merge this into an
2402 // integer add followed by a sext.
2403 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2404 // (add (sext x), cst) --> (sext (add x, cst'))
2405 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2406 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002407 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002408 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002409 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002410 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2411 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002412 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2413 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002414 return new SExtInst(NewAdd, I.getType());
2415 }
2416 }
2417
2418 // (add (sext x), (sext y)) --> (sext (add int x, y))
2419 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2420 // Only do this if x/y have the same type, if at last one of them has a
2421 // single use (so we don't increase the number of sexts), and if the
2422 // integer add will not overflow.
2423 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2424 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2425 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2426 RHSConv->getOperand(0))) {
2427 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002428 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2429 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002430 return new SExtInst(NewAdd, I.getType());
2431 }
2432 }
2433 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002434
2435 return Changed ? &I : 0;
2436}
2437
2438Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2439 bool Changed = SimplifyCommutative(I);
2440 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2441
2442 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2443 // X + 0 --> X
2444 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002445 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002446 (I.getType())->getValueAPF()))
2447 return ReplaceInstUsesWith(I, LHS);
2448 }
2449
2450 if (isa<PHINode>(LHS))
2451 if (Instruction *NV = FoldOpIntoPhi(I))
2452 return NV;
2453 }
2454
2455 // -A + B --> B - A
2456 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002457 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002458 return BinaryOperator::CreateFSub(RHS, LHSV);
2459
2460 // A + -B --> A - B
2461 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002462 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002463 return BinaryOperator::CreateFSub(LHS, V);
2464
2465 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2466 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2467 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2468 return ReplaceInstUsesWith(I, LHS);
2469
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002470 // Check for (add double (sitofp x), y), see if we can merge this into an
2471 // integer add followed by a promotion.
2472 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2473 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2474 // ... if the constant fits in the integer value. This is useful for things
2475 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2476 // requires a constant pool load, and generally allows the add to be better
2477 // instcombined.
2478 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2479 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002480 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002481 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002482 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002483 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2484 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002485 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2486 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002487 return new SIToFPInst(NewAdd, I.getType());
2488 }
2489 }
2490
2491 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2492 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2493 // Only do this if x/y have the same type, if at last one of them has a
2494 // single use (so we don't increase the number of int->fp conversions),
2495 // and if the integer add will not overflow.
2496 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2497 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2498 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2499 RHSConv->getOperand(0))) {
2500 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002501 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002502 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002503 return new SIToFPInst(NewAdd, I.getType());
2504 }
2505 }
2506 }
2507
Chris Lattner7e708292002-06-25 16:13:24 +00002508 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002509}
2510
Chris Lattner092543c2009-11-04 08:05:20 +00002511
2512/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2513/// code necessary to compute the offset from the base pointer (without adding
2514/// in the base pointer). Return the result as a signed integer of intptr size.
2515static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2516 TargetData &TD = *IC.getTargetData();
2517 gep_type_iterator GTI = gep_type_begin(GEP);
2518 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2519 Value *Result = Constant::getNullValue(IntPtrTy);
2520
2521 // Build a mask for high order bits.
2522 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2523 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2524
2525 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2526 ++i, ++GTI) {
2527 Value *Op = *i;
2528 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2529 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2530 if (OpC->isZero()) continue;
2531
2532 // Handle a struct index, which adds its field offset to the pointer.
2533 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2534 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2535
2536 Result = IC.Builder->CreateAdd(Result,
2537 ConstantInt::get(IntPtrTy, Size),
2538 GEP->getName()+".offs");
2539 continue;
2540 }
2541
2542 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2543 Constant *OC =
2544 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2545 Scale = ConstantExpr::getMul(OC, Scale);
2546 // Emit an add instruction.
2547 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2548 continue;
2549 }
2550 // Convert to correct type.
2551 if (Op->getType() != IntPtrTy)
2552 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2553 if (Size != 1) {
2554 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2555 // We'll let instcombine(mul) convert this to a shl if possible.
2556 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2557 }
2558
2559 // Emit an add instruction.
2560 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2561 }
2562 return Result;
2563}
2564
2565
2566/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2567/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2568/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2569/// be complex, and scales are involved. The above expression would also be
2570/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2571/// This later form is less amenable to optimization though, and we are allowed
2572/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2573///
2574/// If we can't emit an optimized form for this expression, this returns null.
2575///
2576static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2577 InstCombiner &IC) {
2578 TargetData &TD = *IC.getTargetData();
2579 gep_type_iterator GTI = gep_type_begin(GEP);
2580
2581 // Check to see if this gep only has a single variable index. If so, and if
2582 // any constant indices are a multiple of its scale, then we can compute this
2583 // in terms of the scale of the variable index. For example, if the GEP
2584 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2585 // because the expression will cross zero at the same point.
2586 unsigned i, e = GEP->getNumOperands();
2587 int64_t Offset = 0;
2588 for (i = 1; i != e; ++i, ++GTI) {
2589 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2590 // Compute the aggregate offset of constant indices.
2591 if (CI->isZero()) continue;
2592
2593 // Handle a struct index, which adds its field offset to the pointer.
2594 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2595 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2596 } else {
2597 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2598 Offset += Size*CI->getSExtValue();
2599 }
2600 } else {
2601 // Found our variable index.
2602 break;
2603 }
2604 }
2605
2606 // If there are no variable indices, we must have a constant offset, just
2607 // evaluate it the general way.
2608 if (i == e) return 0;
2609
2610 Value *VariableIdx = GEP->getOperand(i);
2611 // Determine the scale factor of the variable element. For example, this is
2612 // 4 if the variable index is into an array of i32.
2613 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2614
2615 // Verify that there are no other variable indices. If so, emit the hard way.
2616 for (++i, ++GTI; i != e; ++i, ++GTI) {
2617 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2618 if (!CI) return 0;
2619
2620 // Compute the aggregate offset of constant indices.
2621 if (CI->isZero()) continue;
2622
2623 // Handle a struct index, which adds its field offset to the pointer.
2624 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2625 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2626 } else {
2627 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2628 Offset += Size*CI->getSExtValue();
2629 }
2630 }
2631
2632 // Okay, we know we have a single variable index, which must be a
2633 // pointer/array/vector index. If there is no offset, life is simple, return
2634 // the index.
2635 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2636 if (Offset == 0) {
2637 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2638 // we don't need to bother extending: the extension won't affect where the
2639 // computation crosses zero.
2640 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2641 VariableIdx = new TruncInst(VariableIdx,
2642 TD.getIntPtrType(VariableIdx->getContext()),
2643 VariableIdx->getName(), &I);
2644 return VariableIdx;
2645 }
2646
2647 // Otherwise, there is an index. The computation we will do will be modulo
2648 // the pointer size, so get it.
2649 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2650
2651 Offset &= PtrSizeMask;
2652 VariableScale &= PtrSizeMask;
2653
2654 // To do this transformation, any constant index must be a multiple of the
2655 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2656 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2657 // multiple of the variable scale.
2658 int64_t NewOffs = Offset / (int64_t)VariableScale;
2659 if (Offset != NewOffs*(int64_t)VariableScale)
2660 return 0;
2661
2662 // Okay, we can do this evaluation. Start by converting the index to intptr.
2663 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2664 if (VariableIdx->getType() != IntPtrTy)
2665 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2666 true /*SExt*/,
2667 VariableIdx->getName(), &I);
2668 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2669 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2670}
2671
2672
2673/// Optimize pointer differences into the same array into a size. Consider:
2674/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2675/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2676///
2677Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2678 const Type *Ty) {
2679 assert(TD && "Must have target data info for this");
2680
2681 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2682 // this.
2683 bool Swapped;
2684 GetElementPtrInst *GEP;
2685
2686 if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2687 GEP->getOperand(0) == RHS)
2688 Swapped = false;
2689 else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2690 GEP->getOperand(0) == LHS)
2691 Swapped = true;
2692 else
2693 return 0;
2694
2695 // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2696
2697 // Emit the offset of the GEP and an intptr_t.
2698 Value *Result = EmitGEPOffset(GEP, *this);
2699
2700 // If we have p - gep(p, ...) then we have to negate the result.
2701 if (Swapped)
2702 Result = Builder->CreateNeg(Result, "diff.neg");
2703
2704 return Builder->CreateIntCast(Result, Ty, true);
2705}
2706
2707
Chris Lattner7e708292002-06-25 16:13:24 +00002708Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002709 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002710
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002711 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002712 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002713
Chris Lattner092543c2009-11-04 08:05:20 +00002714 // If this is a 'B = x-(-A)', change to B = x+A.
Dan Gohman186a6362009-08-12 16:04:34 +00002715 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002716 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002717
Chris Lattnere87597f2004-10-16 18:11:37 +00002718 if (isa<UndefValue>(Op0))
2719 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2720 if (isa<UndefValue>(Op1))
2721 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner092543c2009-11-04 08:05:20 +00002722 if (I.getType() == Type::getInt1Ty(*Context))
2723 return BinaryOperator::CreateXor(Op0, Op1);
2724
Chris Lattnerd65460f2003-11-05 01:06:05 +00002725 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002726 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002727 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002728 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002729
Chris Lattnerd65460f2003-11-05 01:06:05 +00002730 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002731 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002732 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002733 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002734
Chris Lattner76b7a062007-01-15 07:02:54 +00002735 // -(X >>u 31) -> (X >>s 31)
2736 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002737 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002738 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002739 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002740 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002741 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002742 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002743 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002744 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002745 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002746 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002747 }
2748 }
Chris Lattner092543c2009-11-04 08:05:20 +00002749 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002750 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2751 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002752 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002753 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002754 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002755 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002756 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002757 }
2758 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002759 }
2760 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002761 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002762
2763 // Try to fold constant sub into select arguments.
2764 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002765 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002766 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002767
2768 // C - zext(bool) -> bool ? C - 1 : C
2769 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002770 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002771 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002772 }
2773
Chris Lattner43d84d62005-04-07 16:15:25 +00002774 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002775 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002776 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002777 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002778 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002779 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002780 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002781 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002782 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2783 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2784 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002785 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002786 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002787 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002788 }
2789
Chris Lattnerfd059242003-10-15 16:48:29 +00002790 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002791 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2792 // is not used by anyone else...
2793 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002794 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002795 // Swap the two operands of the subexpr...
2796 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2797 Op1I->setOperand(0, IIOp1);
2798 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002799
Chris Lattnera2881962003-02-18 19:28:33 +00002800 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002801 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002802 }
2803
2804 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2805 //
2806 if (Op1I->getOpcode() == Instruction::And &&
2807 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2808 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2809
Chris Lattner74381062009-08-30 07:44:24 +00002810 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002811 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002812 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002813
Reid Spencerac5209e2006-10-16 23:08:08 +00002814 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002815 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002816 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002817 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002818 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002819 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002820 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002821
Chris Lattnerad3448c2003-02-18 19:57:07 +00002822 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002823 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002824 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002825 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002826 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002827 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002828 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002829 }
Chris Lattner40371712002-05-09 01:29:19 +00002830 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002831 }
Chris Lattnera2881962003-02-18 19:28:33 +00002832
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002833 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2834 if (Op0I->getOpcode() == Instruction::Add) {
2835 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2836 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2837 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2838 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2839 } else if (Op0I->getOpcode() == Instruction::Sub) {
2840 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002841 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002842 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002843 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002844 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002845
Chris Lattner50af16a2004-11-13 19:50:12 +00002846 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002847 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002848 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002849 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002850
Chris Lattner50af16a2004-11-13 19:50:12 +00002851 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002852 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002853 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002854 }
Chris Lattner092543c2009-11-04 08:05:20 +00002855
2856 // Optimize pointer differences into the same array into a size. Consider:
2857 // &A[10] - &A[0]: we should compile this to "10".
2858 if (TD) {
2859 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2860 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2861 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2862 RHS->getOperand(0),
2863 I.getType()))
2864 return ReplaceInstUsesWith(I, Res);
2865
2866 // trunc(p)-trunc(q) -> trunc(p-q)
2867 if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2868 if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2869 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2870 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2871 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2872 RHS->getOperand(0),
2873 I.getType()))
2874 return ReplaceInstUsesWith(I, Res);
2875 }
2876
Chris Lattner3f5b8772002-05-06 16:14:14 +00002877 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002878}
2879
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002880Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2881 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2882
2883 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002884 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002885 return BinaryOperator::CreateFAdd(Op0, V);
2886
2887 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2888 if (Op1I->getOpcode() == Instruction::FAdd) {
2889 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002890 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002891 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002892 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002893 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002894 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002895 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002896 }
2897
2898 return 0;
2899}
2900
Chris Lattnera0141b92007-07-15 20:42:37 +00002901/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2902/// comparison only checks the sign bit. If it only checks the sign bit, set
2903/// TrueIfSigned if the result of the comparison is true when the input value is
2904/// signed.
2905static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2906 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002907 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002908 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2909 TrueIfSigned = true;
2910 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002911 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2912 TrueIfSigned = true;
2913 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002914 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2915 TrueIfSigned = false;
2916 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002917 case ICmpInst::ICMP_UGT:
2918 // True if LHS u> RHS and RHS == high-bit-mask - 1
2919 TrueIfSigned = true;
2920 return RHS->getValue() ==
2921 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2922 case ICmpInst::ICMP_UGE:
2923 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2924 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002925 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002926 default:
2927 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002928 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002929}
2930
Chris Lattner7e708292002-06-25 16:13:24 +00002931Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002932 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002933 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002934
Chris Lattnera2498472009-10-11 21:36:10 +00002935 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002936 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002937
Chris Lattner8af304a2009-10-11 07:53:15 +00002938 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002939 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2940 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002941
2942 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002943 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002944 if (SI->getOpcode() == Instruction::Shl)
2945 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002946 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002947 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002948
Zhou Sheng843f07672007-04-19 05:39:12 +00002949 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002950 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002951 if (CI->equalsInt(1)) // X * 1 == X
2952 return ReplaceInstUsesWith(I, Op0);
2953 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002954 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002955
Zhou Sheng97b52c22007-03-29 01:57:21 +00002956 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002957 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002958 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002959 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002960 }
Chris Lattnera2498472009-10-11 21:36:10 +00002961 } else if (isa<VectorType>(Op1C->getType())) {
2962 if (Op1C->isNullValue())
2963 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002964
Chris Lattnera2498472009-10-11 21:36:10 +00002965 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002966 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002967 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002968
2969 // As above, vector X*splat(1.0) -> X in all defined cases.
2970 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002971 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2972 if (CI->equalsInt(1))
2973 return ReplaceInstUsesWith(I, Op0);
2974 }
2975 }
Chris Lattnera2881962003-02-18 19:28:33 +00002976 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002977
2978 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2979 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002980 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002981 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00002982 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2983 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002984 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002985
2986 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002987
2988 // Try to fold constant mul into select arguments.
2989 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002990 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002991 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002992
2993 if (isa<PHINode>(Op0))
2994 if (Instruction *NV = FoldOpIntoPhi(I))
2995 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002996 }
2997
Dan Gohman186a6362009-08-12 16:04:34 +00002998 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002999 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003000 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003001
Nick Lewycky0c730792008-11-21 07:33:58 +00003002 // (X / Y) * Y = X - (X % Y)
3003 // (X / Y) * -Y = (X % Y) - X
3004 {
Chris Lattnera2498472009-10-11 21:36:10 +00003005 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00003006 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3007 if (!BO ||
3008 (BO->getOpcode() != Instruction::UDiv &&
3009 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00003010 Op1C = Op0;
3011 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00003012 }
Chris Lattnera2498472009-10-11 21:36:10 +00003013 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00003014 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003015 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00003016 (BO->getOpcode() == Instruction::UDiv ||
3017 BO->getOpcode() == Instruction::SDiv)) {
3018 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3019
Dan Gohmanfa94b942009-08-12 16:33:09 +00003020 // If the division is exact, X % Y is zero.
3021 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3022 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00003023 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00003024 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00003025 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00003026 }
3027
Chris Lattner74381062009-08-30 07:44:24 +00003028 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00003029 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00003030 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003031 else
Chris Lattner74381062009-08-30 07:44:24 +00003032 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003033 Rem->takeName(BO);
3034
Chris Lattnera2498472009-10-11 21:36:10 +00003035 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00003036 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00003037 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003038 }
3039 }
3040
Chris Lattner8af304a2009-10-11 07:53:15 +00003041 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00003042 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00003043 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003044
Chris Lattner8af304a2009-10-11 07:53:15 +00003045 // X*(1 << Y) --> X << Y
3046 // (1 << Y)*X --> X << Y
3047 {
3048 Value *Y;
3049 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00003050 return BinaryOperator::CreateShl(Op1, Y);
3051 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00003052 return BinaryOperator::CreateShl(Op0, Y);
3053 }
3054
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003055 // If one of the operands of the multiply is a cast from a boolean value, then
3056 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00003057 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3058 if (!isa<VectorType>(I.getType())) {
3059 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00003060 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00003061
Chris Lattnerd2c58362009-10-11 21:29:45 +00003062 Value *BoolCast = 0, *OtherOp = 0;
3063 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00003064 BoolCast = Op0, OtherOp = Op1;
3065 else if (MaskedValueIsZero(Op1, Negative2))
3066 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00003067
Chris Lattner0036e3a2009-10-11 21:22:21 +00003068 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00003069 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3070 BoolCast, "tmp");
3071 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003072 }
3073 }
3074
Chris Lattner7e708292002-06-25 16:13:24 +00003075 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003076}
3077
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003078Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3079 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003080 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003081
3082 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00003083 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3084 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003085 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3086 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3087 if (Op1F->isExactlyValue(1.0))
3088 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00003089 } else if (isa<VectorType>(Op1C->getType())) {
3090 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003091 // As above, vector X*splat(1.0) -> X in all defined cases.
3092 if (Constant *Splat = Op1V->getSplatValue()) {
3093 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3094 if (F->isExactlyValue(1.0))
3095 return ReplaceInstUsesWith(I, Op0);
3096 }
3097 }
3098 }
3099
3100 // Try to fold constant mul into select arguments.
3101 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3102 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3103 return R;
3104
3105 if (isa<PHINode>(Op0))
3106 if (Instruction *NV = FoldOpIntoPhi(I))
3107 return NV;
3108 }
3109
Dan Gohman186a6362009-08-12 16:04:34 +00003110 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003111 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003112 return BinaryOperator::CreateFMul(Op0v, Op1v);
3113
3114 return Changed ? &I : 0;
3115}
3116
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003117/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3118/// instruction.
3119bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3120 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3121
3122 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3123 int NonNullOperand = -1;
3124 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3125 if (ST->isNullValue())
3126 NonNullOperand = 2;
3127 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3128 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3129 if (ST->isNullValue())
3130 NonNullOperand = 1;
3131
3132 if (NonNullOperand == -1)
3133 return false;
3134
3135 Value *SelectCond = SI->getOperand(0);
3136
3137 // Change the div/rem to use 'Y' instead of the select.
3138 I.setOperand(1, SI->getOperand(NonNullOperand));
3139
3140 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3141 // problem. However, the select, or the condition of the select may have
3142 // multiple uses. Based on our knowledge that the operand must be non-zero,
3143 // propagate the known value for the select into other uses of it, and
3144 // propagate a known value of the condition into its other users.
3145
3146 // If the select and condition only have a single use, don't bother with this,
3147 // early exit.
3148 if (SI->use_empty() && SelectCond->hasOneUse())
3149 return true;
3150
3151 // Scan the current block backward, looking for other uses of SI.
3152 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3153
3154 while (BBI != BBFront) {
3155 --BBI;
3156 // If we found a call to a function, we can't assume it will return, so
3157 // information from below it cannot be propagated above it.
3158 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3159 break;
3160
3161 // Replace uses of the select or its condition with the known values.
3162 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3163 I != E; ++I) {
3164 if (*I == SI) {
3165 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003166 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003167 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00003168 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3169 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003170 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003171 }
3172 }
3173
3174 // If we past the instruction, quit looking for it.
3175 if (&*BBI == SI)
3176 SI = 0;
3177 if (&*BBI == SelectCond)
3178 SelectCond = 0;
3179
3180 // If we ran out of things to eliminate, break out of the loop.
3181 if (SelectCond == 0 && SI == 0)
3182 break;
3183
3184 }
3185 return true;
3186}
3187
3188
Reid Spencer1628cec2006-10-26 06:15:43 +00003189/// This function implements the transforms on div instructions that work
3190/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3191/// used by the visitors to those instructions.
3192/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003193Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003194 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003195
Chris Lattner50b2ca42008-02-19 06:12:18 +00003196 // undef / X -> 0 for integer.
3197 // undef / X -> undef for FP (the undef could be a snan).
3198 if (isa<UndefValue>(Op0)) {
3199 if (Op0->getType()->isFPOrFPVector())
3200 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003201 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003202 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003203
3204 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003205 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003206 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003207
Reid Spencer1628cec2006-10-26 06:15:43 +00003208 return 0;
3209}
Misha Brukmanfd939082005-04-21 23:48:37 +00003210
Reid Spencer1628cec2006-10-26 06:15:43 +00003211/// This function implements the transforms common to both integer division
3212/// instructions (udiv and sdiv). It is called by the visitors to those integer
3213/// division instructions.
3214/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003215Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003216 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3217
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003218 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003219 if (Op0 == Op1) {
3220 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003221 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003222 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003223 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003224 }
3225
Owen Andersoneed707b2009-07-24 23:12:02 +00003226 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003227 return ReplaceInstUsesWith(I, CI);
3228 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003229
Reid Spencer1628cec2006-10-26 06:15:43 +00003230 if (Instruction *Common = commonDivTransforms(I))
3231 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003232
3233 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3234 // This does not apply for fdiv.
3235 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3236 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003237
3238 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3239 // div X, 1 == X
3240 if (RHS->equalsInt(1))
3241 return ReplaceInstUsesWith(I, Op0);
3242
3243 // (X / C1) / C2 -> X / (C1*C2)
3244 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3245 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3246 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003247 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003248 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003249 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003250 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003251 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003252 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003253 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003254
Reid Spencerbca0e382007-03-23 20:05:17 +00003255 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003256 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3257 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3258 return R;
3259 if (isa<PHINode>(Op0))
3260 if (Instruction *NV = FoldOpIntoPhi(I))
3261 return NV;
3262 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003263 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003264
Chris Lattnera2881962003-02-18 19:28:33 +00003265 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003266 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003267 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003268 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003269
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003270 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003271 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003272 return ReplaceInstUsesWith(I, Op0);
3273
Nick Lewycky895f0852008-11-27 20:21:08 +00003274 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3275 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3276 // div X, 1 == X
3277 if (X->isOne())
3278 return ReplaceInstUsesWith(I, Op0);
3279 }
3280
Reid Spencer1628cec2006-10-26 06:15:43 +00003281 return 0;
3282}
3283
3284Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3285 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3286
3287 // Handle the integer div common cases
3288 if (Instruction *Common = commonIDivTransforms(I))
3289 return Common;
3290
Reid Spencer1628cec2006-10-26 06:15:43 +00003291 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003292 // X udiv C^2 -> X >> C
3293 // Check to see if this is an unsigned division with an exact power of 2,
3294 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003295 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003296 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003297 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003298
3299 // X udiv C, where C >= signbit
3300 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003301 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003302 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003303 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003304 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003305 }
3306
3307 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003308 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003309 if (RHSI->getOpcode() == Instruction::Shl &&
3310 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003311 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003312 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003313 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003314 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003315 if (uint32_t C2 = C1.logBase2())
3316 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003317 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003318 }
3319 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003320 }
3321
Reid Spencer1628cec2006-10-26 06:15:43 +00003322 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3323 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003324 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003325 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003326 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003327 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003328 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003329 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003330 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003331 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003332 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003333 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003334
3335 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003336 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003337 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003338
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003339 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003340 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003341 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003342 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003343 return 0;
3344}
3345
Reid Spencer1628cec2006-10-26 06:15:43 +00003346Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3347 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3348
3349 // Handle the integer div common cases
3350 if (Instruction *Common = commonIDivTransforms(I))
3351 return Common;
3352
3353 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3354 // sdiv X, -1 == -X
3355 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003356 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003357
Dan Gohmanfa94b942009-08-12 16:33:09 +00003358 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003359 if (cast<SDivOperator>(&I)->isExact() &&
3360 RHS->getValue().isNonNegative() &&
3361 RHS->getValue().isPowerOf2()) {
3362 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3363 RHS->getValue().exactLogBase2());
3364 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3365 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003366
3367 // -X/C --> X/-C provided the negation doesn't overflow.
3368 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3369 if (isa<Constant>(Sub->getOperand(0)) &&
3370 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003371 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003372 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3373 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003374 }
3375
3376 // If the sign bits of both operands are zero (i.e. we can prove they are
3377 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003378 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003379 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003380 if (MaskedValueIsZero(Op0, Mask)) {
3381 if (MaskedValueIsZero(Op1, Mask)) {
3382 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3383 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3384 }
3385 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003386 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003387 ShiftedInt->getValue().isPowerOf2()) {
3388 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3389 // Safe because the only negative value (1 << Y) can take on is
3390 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3391 // the sign bit set.
3392 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3393 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003394 }
Eli Friedman8be17392009-07-18 09:53:21 +00003395 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003396
3397 return 0;
3398}
3399
3400Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3401 return commonDivTransforms(I);
3402}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003403
Reid Spencer0a783f72006-11-02 01:53:59 +00003404/// This function implements the transforms on rem instructions that work
3405/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3406/// is used by the visitors to those instructions.
3407/// @brief Transforms common to all three rem instructions
3408Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003410
Chris Lattner50b2ca42008-02-19 06:12:18 +00003411 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3412 if (I.getType()->isFPOrFPVector())
3413 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003414 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003415 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003416 if (isa<UndefValue>(Op1))
3417 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003418
3419 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003420 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3421 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003422
Reid Spencer0a783f72006-11-02 01:53:59 +00003423 return 0;
3424}
3425
3426/// This function implements the transforms common to both integer remainder
3427/// instructions (urem and srem). It is called by the visitors to those integer
3428/// remainder instructions.
3429/// @brief Common integer remainder transforms
3430Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3431 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3432
3433 if (Instruction *common = commonRemTransforms(I))
3434 return common;
3435
Dale Johannesened6af242009-01-21 00:35:19 +00003436 // 0 % X == 0 for integer, we don't need to preserve faults!
3437 if (Constant *LHS = dyn_cast<Constant>(Op0))
3438 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003440
Chris Lattner857e8cd2004-12-12 21:48:58 +00003441 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003442 // X % 0 == undef, we don't need to preserve faults!
3443 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003444 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003445
Chris Lattnera2881962003-02-18 19:28:33 +00003446 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003447 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003448
Chris Lattner97943922006-02-28 05:49:21 +00003449 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3450 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3451 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3452 return R;
3453 } else if (isa<PHINode>(Op0I)) {
3454 if (Instruction *NV = FoldOpIntoPhi(I))
3455 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003456 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003457
3458 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003459 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003460 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003461 }
Chris Lattnera2881962003-02-18 19:28:33 +00003462 }
3463
Reid Spencer0a783f72006-11-02 01:53:59 +00003464 return 0;
3465}
3466
3467Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3468 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3469
3470 if (Instruction *common = commonIRemTransforms(I))
3471 return common;
3472
3473 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3474 // X urem C^2 -> X and C
3475 // Check to see if this is an unsigned remainder with an exact power of 2,
3476 // if so, convert to a bitwise and.
3477 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003478 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003479 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003480 }
3481
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003482 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003483 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3484 if (RHSI->getOpcode() == Instruction::Shl &&
3485 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003486 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003487 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003488 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003489 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003490 }
3491 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003492 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003493
Reid Spencer0a783f72006-11-02 01:53:59 +00003494 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3495 // where C1&C2 are powers of two.
3496 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3497 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3498 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3499 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003500 if ((STO->getValue().isPowerOf2()) &&
3501 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003502 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3503 SI->getName()+".t");
3504 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3505 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003506 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003507 }
3508 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003509 }
3510
Chris Lattner3f5b8772002-05-06 16:14:14 +00003511 return 0;
3512}
3513
Reid Spencer0a783f72006-11-02 01:53:59 +00003514Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3515 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3516
Dan Gohmancff55092007-11-05 23:16:33 +00003517 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003518 if (Instruction *Common = commonIRemTransforms(I))
3519 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003520
Dan Gohman186a6362009-08-12 16:04:34 +00003521 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003522 if (!isa<Constant>(RHSNeg) ||
3523 (isa<ConstantInt>(RHSNeg) &&
3524 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003525 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003526 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003527 I.setOperand(1, RHSNeg);
3528 return &I;
3529 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003530
Dan Gohmancff55092007-11-05 23:16:33 +00003531 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003532 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003533 if (I.getType()->isInteger()) {
3534 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3535 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3536 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003537 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003538 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003539 }
3540
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003541 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003542 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3543 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003544
Nick Lewycky9dce8732008-12-20 16:48:00 +00003545 bool hasNegative = false;
3546 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3547 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3548 if (RHS->getValue().isNegative())
3549 hasNegative = true;
3550
3551 if (hasNegative) {
3552 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003553 for (unsigned i = 0; i != VWidth; ++i) {
3554 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3555 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003556 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003557 else
3558 Elts[i] = RHS;
3559 }
3560 }
3561
Owen Andersonaf7ec972009-07-28 21:19:26 +00003562 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003563 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003564 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003565 I.setOperand(1, NewRHSV);
3566 return &I;
3567 }
3568 }
3569 }
3570
Reid Spencer0a783f72006-11-02 01:53:59 +00003571 return 0;
3572}
3573
3574Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003575 return commonRemTransforms(I);
3576}
3577
Chris Lattner457dd822004-06-09 07:59:58 +00003578// isOneBitSet - Return true if there is exactly one bit set in the specified
3579// constant.
3580static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003581 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003582}
3583
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003584// isHighOnes - Return true if the constant is of the form 1+0+.
3585// This is the same as lowones(~X).
3586static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003587 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003588}
3589
Reid Spencere4d87aa2006-12-23 06:05:41 +00003590/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003591/// are carefully arranged to allow folding of expressions such as:
3592///
3593/// (A < B) | (A > B) --> (A != B)
3594///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003595/// Note that this is only valid if the first and second predicates have the
3596/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003597///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003598/// Three bits are used to represent the condition, as follows:
3599/// 0 A > B
3600/// 1 A == B
3601/// 2 A < B
3602///
3603/// <=> Value Definition
3604/// 000 0 Always false
3605/// 001 1 A > B
3606/// 010 2 A == B
3607/// 011 3 A >= B
3608/// 100 4 A < B
3609/// 101 5 A != B
3610/// 110 6 A <= B
3611/// 111 7 Always true
3612///
3613static unsigned getICmpCode(const ICmpInst *ICI) {
3614 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003615 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003616 case ICmpInst::ICMP_UGT: return 1; // 001
3617 case ICmpInst::ICMP_SGT: return 1; // 001
3618 case ICmpInst::ICMP_EQ: return 2; // 010
3619 case ICmpInst::ICMP_UGE: return 3; // 011
3620 case ICmpInst::ICMP_SGE: return 3; // 011
3621 case ICmpInst::ICMP_ULT: return 4; // 100
3622 case ICmpInst::ICMP_SLT: return 4; // 100
3623 case ICmpInst::ICMP_NE: return 5; // 101
3624 case ICmpInst::ICMP_ULE: return 6; // 110
3625 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003626 // True -> 7
3627 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003628 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003629 return 0;
3630 }
3631}
3632
Evan Cheng8db90722008-10-14 17:15:11 +00003633/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3634/// predicate into a three bit mask. It also returns whether it is an ordered
3635/// predicate by reference.
3636static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3637 isOrdered = false;
3638 switch (CC) {
3639 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3640 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003641 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3642 case FCmpInst::FCMP_UGT: return 1; // 001
3643 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3644 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003645 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3646 case FCmpInst::FCMP_UGE: return 3; // 011
3647 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3648 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003649 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3650 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003651 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3652 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003653 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003654 default:
3655 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003656 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003657 return 0;
3658 }
3659}
3660
Reid Spencere4d87aa2006-12-23 06:05:41 +00003661/// getICmpValue - This is the complement of getICmpCode, which turns an
3662/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003663/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003664/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003665static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003666 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003667 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003668 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003669 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003670 case 1:
3671 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003672 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003673 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003674 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3675 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003676 case 3:
3677 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003678 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003679 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003680 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003681 case 4:
3682 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003683 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003684 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003685 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3686 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003687 case 6:
3688 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003689 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003690 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003691 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003692 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003693 }
3694}
3695
Evan Cheng8db90722008-10-14 17:15:11 +00003696/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3697/// opcode and two operands into either a FCmp instruction. isordered is passed
3698/// in to determine which kind of predicate to use in the new fcmp instruction.
3699static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003700 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003701 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003702 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003703 case 0:
3704 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003705 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003706 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003707 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003708 case 1:
3709 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003710 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003711 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003712 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003713 case 2:
3714 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003715 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003716 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003717 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003718 case 3:
3719 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003720 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003721 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003722 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003723 case 4:
3724 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003725 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003726 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003727 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003728 case 5:
3729 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003730 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003731 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003732 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003733 case 6:
3734 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003735 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003736 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003737 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003738 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003739 }
3740}
3741
Chris Lattnerb9553d62008-11-16 04:55:20 +00003742/// PredicatesFoldable - Return true if both predicates match sign or if at
3743/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003744static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003745 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3746 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3747 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003748}
3749
3750namespace {
3751// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3752struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003753 InstCombiner &IC;
3754 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003755 ICmpInst::Predicate pred;
3756 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3757 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3758 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003759 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003760 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3761 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003762 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3763 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003764 return false;
3765 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003766 Instruction *apply(Instruction &Log) const {
3767 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3768 if (ICI->getOperand(0) != LHS) {
3769 assert(ICI->getOperand(1) == LHS);
3770 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003771 }
3772
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003773 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003774 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003775 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003776 unsigned Code;
3777 switch (Log.getOpcode()) {
3778 case Instruction::And: Code = LHSCode & RHSCode; break;
3779 case Instruction::Or: Code = LHSCode | RHSCode; break;
3780 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003781 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003782 }
3783
Nick Lewycky4a134af2009-10-25 05:20:17 +00003784 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003785 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003786 if (Instruction *I = dyn_cast<Instruction>(RV))
3787 return I;
3788 // Otherwise, it's a constant boolean value...
3789 return IC.ReplaceInstUsesWith(Log, RV);
3790 }
3791};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003792} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003793
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003794// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3795// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003796// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003797Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003798 ConstantInt *OpRHS,
3799 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003800 BinaryOperator &TheAnd) {
3801 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003802 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003803 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003804 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003805
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003806 switch (Op->getOpcode()) {
3807 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003808 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003809 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003810 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003811 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003812 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003813 }
3814 break;
3815 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003816 if (Together == AndRHS) // (X | C) & C --> C
3817 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003818
Chris Lattner6e7ba452005-01-01 16:22:27 +00003819 if (Op->hasOneUse() && Together != OpRHS) {
3820 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003821 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003822 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003823 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003824 }
3825 break;
3826 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003827 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003828 // Adding a one to a single bit bit-field should be turned into an XOR
3829 // of the bit. First thing to check is to see if this AND is with a
3830 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003831 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003832
3833 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003834 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003835 // Ok, at this point, we know that we are masking the result of the
3836 // ADD down to exactly one bit. If the constant we are adding has
3837 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003838 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003839
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003840 // Check to see if any bits below the one bit set in AndRHSV are set.
3841 if ((AddRHS & (AndRHSV-1)) == 0) {
3842 // If not, the only thing that can effect the output of the AND is
3843 // the bit specified by AndRHSV. If that bit is set, the effect of
3844 // the XOR is to toggle the bit. If it is clear, then the ADD has
3845 // no effect.
3846 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3847 TheAnd.setOperand(0, X);
3848 return &TheAnd;
3849 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003850 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003851 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003852 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003853 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003854 }
3855 }
3856 }
3857 }
3858 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003859
3860 case Instruction::Shl: {
3861 // We know that the AND will not produce any of the bits shifted in, so if
3862 // the anded constant includes them, clear them now!
3863 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003864 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003865 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003866 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003867 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003868
Zhou Sheng290bec52007-03-29 08:15:12 +00003869 if (CI->getValue() == ShlMask) {
3870 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003871 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3872 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003873 TheAnd.setOperand(1, CI);
3874 return &TheAnd;
3875 }
3876 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003877 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003878 case Instruction::LShr:
3879 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003880 // We know that the AND will not produce any of the bits shifted in, so if
3881 // the anded constant includes them, clear them now! This only applies to
3882 // unsigned shifts, because a signed shr may bring in set bits!
3883 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003884 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003885 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003886 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003887 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003888
Zhou Sheng290bec52007-03-29 08:15:12 +00003889 if (CI->getValue() == ShrMask) {
3890 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003891 return ReplaceInstUsesWith(TheAnd, Op);
3892 } else if (CI != AndRHS) {
3893 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3894 return &TheAnd;
3895 }
3896 break;
3897 }
3898 case Instruction::AShr:
3899 // Signed shr.
3900 // See if this is shifting in some sign extension, then masking it out
3901 // with an and.
3902 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003903 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003904 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003905 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003906 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003907 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003908 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003909 // Make the argument unsigned.
3910 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003911 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003912 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003913 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003914 }
3915 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003916 }
3917 return 0;
3918}
3919
Chris Lattner8b170942002-08-09 23:47:40 +00003920
Chris Lattnera96879a2004-09-29 17:40:11 +00003921/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3922/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003923/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3924/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003925/// insert new instructions.
3926Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003927 bool isSigned, bool Inside,
3928 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003929 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003930 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003931 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003932
Chris Lattnera96879a2004-09-29 17:40:11 +00003933 if (Inside) {
3934 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003935 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003936
Reid Spencere4d87aa2006-12-23 06:05:41 +00003937 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003938 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003939 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003940 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003941 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003942 }
3943
3944 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003945 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003946 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003947 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003948 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003949 }
3950
3951 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003952 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003953
Reid Spencere4e40032007-03-21 23:19:50 +00003954 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003955 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003956 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003957 ICmpInst::Predicate pred = (isSigned ?
3958 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003959 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003960 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003961
Reid Spencere4e40032007-03-21 23:19:50 +00003962 // Emit V-Lo >u Hi-1-Lo
3963 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003964 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003965 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003966 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003967 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003968}
3969
Chris Lattner7203e152005-09-18 07:22:02 +00003970// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3971// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3972// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3973// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003974static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003975 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003976 uint32_t BitWidth = Val->getType()->getBitWidth();
3977 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003978
3979 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003980 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003981 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003982 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003983 return true;
3984}
3985
Chris Lattner7203e152005-09-18 07:22:02 +00003986/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3987/// where isSub determines whether the operator is a sub. If we can fold one of
3988/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003989///
3990/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3991/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3992/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3993///
3994/// return (A +/- B).
3995///
3996Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003997 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003998 Instruction &I) {
3999 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4000 if (!LHSI || LHSI->getNumOperands() != 2 ||
4001 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4002
4003 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4004
4005 switch (LHSI->getOpcode()) {
4006 default: return 0;
4007 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00004008 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004009 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004010 if ((Mask->getValue().countLeadingZeros() +
4011 Mask->getValue().countPopulation()) ==
4012 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004013 break;
4014
4015 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4016 // part, we don't need any explicit masks to take them out of A. If that
4017 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004018 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004019 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004020 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004021 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004022 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004023 break;
4024 }
4025 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004026 return 0;
4027 case Instruction::Or:
4028 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004029 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004030 if ((Mask->getValue().countLeadingZeros() +
4031 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00004032 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004033 break;
4034 return 0;
4035 }
4036
Chris Lattnerc8e77562005-09-18 04:24:45 +00004037 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00004038 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4039 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004040}
4041
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004042/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4043Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4044 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00004045 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004046 ConstantInt *LHSCst, *RHSCst;
4047 ICmpInst::Predicate LHSCC, RHSCC;
4048
Chris Lattnerea065fb2008-11-16 05:10:52 +00004049 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004050 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004051 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004052 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004053 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004054 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00004055
4056 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4057 // where C is a power of 2
4058 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
4059 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00004060 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004061 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00004062 }
4063
4064 // From here on, we only handle:
4065 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4066 if (Val != Val2) return 0;
4067
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004068 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4069 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4070 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4071 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4072 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4073 return 0;
4074
4075 // We can't fold (ugt x, C) & (sgt x, C2).
4076 if (!PredicatesFoldable(LHSCC, RHSCC))
4077 return 0;
4078
4079 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00004080 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004081 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004082 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004083 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00004084 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004085 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00004086 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4087
4088 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004089 std::swap(LHS, RHS);
4090 std::swap(LHSCst, RHSCst);
4091 std::swap(LHSCC, RHSCC);
4092 }
4093
4094 // At this point, we know we have have two icmp instructions
4095 // comparing a value against two constants and and'ing the result
4096 // together. Because of the above check, we know that we only have
4097 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4098 // (from the FoldICmpLogical check above), that the two constants
4099 // are not equal and that the larger constant is on the RHS
4100 assert(LHSCst != RHSCst && "Compares not folded above?");
4101
4102 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004103 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004104 case ICmpInst::ICMP_EQ:
4105 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004106 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004107 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4108 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4109 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004110 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004111 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4112 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4113 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4114 return ReplaceInstUsesWith(I, LHS);
4115 }
4116 case ICmpInst::ICMP_NE:
4117 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004118 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004119 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00004120 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004121 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004122 break; // (X != 13 & X u< 15) -> no change
4123 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00004124 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004125 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004126 break; // (X != 13 & X s< 15) -> no change
4127 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4128 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4129 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4130 return ReplaceInstUsesWith(I, RHS);
4131 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004132 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00004133 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004134 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004135 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00004136 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004137 }
4138 break; // (X != 13 & X != 15) -> no change
4139 }
4140 break;
4141 case ICmpInst::ICMP_ULT:
4142 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004143 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004144 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4145 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004146 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004147 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4148 break;
4149 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4150 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4151 return ReplaceInstUsesWith(I, LHS);
4152 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4153 break;
4154 }
4155 break;
4156 case ICmpInst::ICMP_SLT:
4157 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004158 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004159 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4160 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004161 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004162 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4163 break;
4164 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4165 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4166 return ReplaceInstUsesWith(I, LHS);
4167 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4168 break;
4169 }
4170 break;
4171 case ICmpInst::ICMP_UGT:
4172 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004173 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004174 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4175 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4176 return ReplaceInstUsesWith(I, RHS);
4177 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4178 break;
4179 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004180 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004181 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004182 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004183 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004184 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004185 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004186 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4187 break;
4188 }
4189 break;
4190 case ICmpInst::ICMP_SGT:
4191 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004192 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004193 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4194 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4195 return ReplaceInstUsesWith(I, RHS);
4196 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4197 break;
4198 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004199 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004200 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004201 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004202 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004203 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004204 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004205 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4206 break;
4207 }
4208 break;
4209 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004210
4211 return 0;
4212}
4213
Chris Lattner42d1be02009-07-23 05:14:02 +00004214Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4215 FCmpInst *RHS) {
4216
4217 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4218 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4219 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4220 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4221 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4222 // If either of the constants are nans, then the whole thing returns
4223 // false.
4224 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004225 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004226 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004227 LHS->getOperand(0), RHS->getOperand(0));
4228 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004229
4230 // Handle vector zeros. This occurs because the canonical form of
4231 // "fcmp ord x,x" is "fcmp ord x, 0".
4232 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4233 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004234 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004235 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004236 return 0;
4237 }
4238
4239 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4240 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4241 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4242
4243
4244 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4245 // Swap RHS operands to match LHS.
4246 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4247 std::swap(Op1LHS, Op1RHS);
4248 }
4249
4250 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4251 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4252 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004253 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004254
4255 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004256 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004257 if (Op0CC == FCmpInst::FCMP_TRUE)
4258 return ReplaceInstUsesWith(I, RHS);
4259 if (Op1CC == FCmpInst::FCMP_TRUE)
4260 return ReplaceInstUsesWith(I, LHS);
4261
4262 bool Op0Ordered;
4263 bool Op1Ordered;
4264 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4265 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4266 if (Op1Pred == 0) {
4267 std::swap(LHS, RHS);
4268 std::swap(Op0Pred, Op1Pred);
4269 std::swap(Op0Ordered, Op1Ordered);
4270 }
4271 if (Op0Pred == 0) {
4272 // uno && ueq -> uno && (uno || eq) -> ueq
4273 // ord && olt -> ord && (ord && lt) -> olt
4274 if (Op0Ordered == Op1Ordered)
4275 return ReplaceInstUsesWith(I, RHS);
4276
4277 // uno && oeq -> uno && (ord && eq) -> false
4278 // uno && ord -> false
4279 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004280 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004281 // ord && ueq -> ord && (uno || eq) -> oeq
4282 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4283 Op0LHS, Op0RHS, Context));
4284 }
4285 }
4286
4287 return 0;
4288}
4289
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004290
Chris Lattner7e708292002-06-25 16:13:24 +00004291Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004292 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004293 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004294
Chris Lattnere87597f2004-10-16 18:11:37 +00004295 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004296 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004297
Chris Lattner6e7ba452005-01-01 16:22:27 +00004298 // and X, X = X
4299 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004300 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004301
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004302 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004303 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004304 if (SimplifyDemandedInstructionBits(I))
4305 return &I;
4306 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004307 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004308 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004309 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004310 } else if (isa<ConstantAggregateZero>(Op1)) {
4311 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004312 }
4313 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004314
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004315 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004316 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004317 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004318
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004319 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004320 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004321 Value *Op0LHS = Op0I->getOperand(0);
4322 Value *Op0RHS = Op0I->getOperand(1);
4323 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004324 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004325 case Instruction::Xor:
4326 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004327 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004328 if (!Op0I->hasOneUse()) break;
4329
4330 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4331 // Not masking anything out for the LHS, move to RHS.
4332 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4333 Op0RHS->getName()+".masked");
4334 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4335 }
4336 if (!isa<Constant>(Op0RHS) &&
4337 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4338 // Not masking anything out for the RHS, move to LHS.
4339 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4340 Op0LHS->getName()+".masked");
4341 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004342 }
4343
Chris Lattner6e7ba452005-01-01 16:22:27 +00004344 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004345 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004346 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4347 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4348 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4349 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004350 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004351 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004352 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004353 break;
4354
4355 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004356 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4357 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4358 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4359 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004360 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004361
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004362 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4363 // has 1's for all bits that the subtraction with A might affect.
4364 if (Op0I->hasOneUse()) {
4365 uint32_t BitWidth = AndRHSMask.getBitWidth();
4366 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4367 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4368
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004369 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004370 if (!(A && A->isZero()) && // avoid infinite recursion.
4371 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004372 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004373 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4374 }
4375 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004376 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004377
4378 case Instruction::Shl:
4379 case Instruction::LShr:
4380 // (1 << x) & 1 --> zext(x == 0)
4381 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004382 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004383 Value *NewICmp =
4384 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004385 return new ZExtInst(NewICmp, I.getType());
4386 }
4387 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004388 }
4389
Chris Lattner58403262003-07-23 19:25:52 +00004390 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004391 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004392 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004393 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004394 // If this is an integer truncation or change from signed-to-unsigned, and
4395 // if the source is an and/or with immediate, transform it. This
4396 // frequently occurs for bitfield accesses.
4397 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004398 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004399 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004400 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004401 if (CastOp->getOpcode() == Instruction::And) {
4402 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004403 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4404 // This will fold the two constants together, which may allow
4405 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004406 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004407 CastOp->getOperand(0), I.getType(),
4408 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004409 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004410 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004411 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004412 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004413 } else if (CastOp->getOpcode() == Instruction::Or) {
4414 // Change: and (cast (or X, C1) to T), C2
4415 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004416 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004417 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004418 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004419 return ReplaceInstUsesWith(I, AndRHS);
4420 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004421 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004422 }
Chris Lattner06782f82003-07-23 19:36:21 +00004423 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004424
4425 // Try to fold constant and into select arguments.
4426 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004427 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004428 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004429 if (isa<PHINode>(Op0))
4430 if (Instruction *NV = FoldOpIntoPhi(I))
4431 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004432 }
4433
Dan Gohman186a6362009-08-12 16:04:34 +00004434 Value *Op0NotVal = dyn_castNotVal(Op0);
4435 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004436
Chris Lattner5b62aa72004-06-18 06:07:51 +00004437 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004438 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004439
Misha Brukmancb6267b2004-07-30 12:50:08 +00004440 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004441 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004442 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4443 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004444 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004445 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004446
4447 {
Chris Lattner003b6202007-06-15 05:58:24 +00004448 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004449 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004450 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4451 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004452
4453 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004454 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004455 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004456 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004457 }
4458 }
4459
Dan Gohman4ae51262009-08-12 16:23:25 +00004460 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004461 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4462 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004463
4464 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004465 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004466 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004467 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004468 }
4469 }
Chris Lattner64daab52006-04-01 08:03:55 +00004470
4471 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004472 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004473 if (A == Op1) { // (A^B)&A -> A&(A^B)
4474 I.swapOperands(); // Simplify below
4475 std::swap(Op0, Op1);
4476 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4477 cast<BinaryOperator>(Op0)->swapOperands();
4478 I.swapOperands(); // Simplify below
4479 std::swap(Op0, Op1);
4480 }
4481 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004482
Chris Lattner64daab52006-04-01 08:03:55 +00004483 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004484 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004485 if (B == Op0) { // B&(A^B) -> B&(B^A)
4486 cast<BinaryOperator>(Op1)->swapOperands();
4487 std::swap(A, B);
4488 }
Chris Lattner74381062009-08-30 07:44:24 +00004489 if (A == Op0) // A&(A^B) -> A & ~B
4490 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004491 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004492
4493 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004494 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4495 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004496 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004497 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4498 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004499 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004500 }
4501
Reid Spencere4d87aa2006-12-23 06:05:41 +00004502 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4503 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004504 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004505 return R;
4506
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004507 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4508 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4509 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004510 }
4511
Chris Lattner6fc205f2006-05-05 06:39:07 +00004512 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004513 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4514 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4515 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4516 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004517 if (SrcTy == Op1C->getOperand(0)->getType() &&
4518 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004519 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004520 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4521 I.getType(), TD) &&
4522 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4523 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004524 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4525 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004526 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004527 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004528 }
Chris Lattnere511b742006-11-14 07:46:50 +00004529
4530 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004531 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4532 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4533 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004534 SI0->getOperand(1) == SI1->getOperand(1) &&
4535 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004536 Value *NewOp =
4537 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4538 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004539 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004540 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004541 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004542 }
4543
Evan Cheng8db90722008-10-14 17:15:11 +00004544 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004545 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004546 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4547 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4548 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004549 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004550
Chris Lattner7e708292002-06-25 16:13:24 +00004551 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004552}
4553
Chris Lattner8c34cd22008-10-05 02:13:19 +00004554/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4555/// capable of providing pieces of a bswap. The subexpression provides pieces
4556/// of a bswap if it is proven that each of the non-zero bytes in the output of
4557/// the expression came from the corresponding "byte swapped" byte in some other
4558/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4559/// we know that the expression deposits the low byte of %X into the high byte
4560/// of the bswap result and that all other bytes are zero. This expression is
4561/// accepted, the high byte of ByteValues is set to X to indicate a correct
4562/// match.
4563///
4564/// This function returns true if the match was unsuccessful and false if so.
4565/// On entry to the function the "OverallLeftShift" is a signed integer value
4566/// indicating the number of bytes that the subexpression is later shifted. For
4567/// example, if the expression is later right shifted by 16 bits, the
4568/// OverallLeftShift value would be -2 on entry. This is used to specify which
4569/// byte of ByteValues is actually being set.
4570///
4571/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4572/// byte is masked to zero by a user. For example, in (X & 255), X will be
4573/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4574/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4575/// always in the local (OverallLeftShift) coordinate space.
4576///
4577static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4578 SmallVector<Value*, 8> &ByteValues) {
4579 if (Instruction *I = dyn_cast<Instruction>(V)) {
4580 // If this is an or instruction, it may be an inner node of the bswap.
4581 if (I->getOpcode() == Instruction::Or) {
4582 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4583 ByteValues) ||
4584 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4585 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004586 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004587
4588 // If this is a logical shift by a constant multiple of 8, recurse with
4589 // OverallLeftShift and ByteMask adjusted.
4590 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4591 unsigned ShAmt =
4592 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4593 // Ensure the shift amount is defined and of a byte value.
4594 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4595 return true;
4596
4597 unsigned ByteShift = ShAmt >> 3;
4598 if (I->getOpcode() == Instruction::Shl) {
4599 // X << 2 -> collect(X, +2)
4600 OverallLeftShift += ByteShift;
4601 ByteMask >>= ByteShift;
4602 } else {
4603 // X >>u 2 -> collect(X, -2)
4604 OverallLeftShift -= ByteShift;
4605 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004606 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004607 }
4608
4609 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4610 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4611
4612 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4613 ByteValues);
4614 }
4615
4616 // If this is a logical 'and' with a mask that clears bytes, clear the
4617 // corresponding bytes in ByteMask.
4618 if (I->getOpcode() == Instruction::And &&
4619 isa<ConstantInt>(I->getOperand(1))) {
4620 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4621 unsigned NumBytes = ByteValues.size();
4622 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4623 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4624
4625 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4626 // If this byte is masked out by a later operation, we don't care what
4627 // the and mask is.
4628 if ((ByteMask & (1 << i)) == 0)
4629 continue;
4630
4631 // If the AndMask is all zeros for this byte, clear the bit.
4632 APInt MaskB = AndMask & Byte;
4633 if (MaskB == 0) {
4634 ByteMask &= ~(1U << i);
4635 continue;
4636 }
4637
4638 // If the AndMask is not all ones for this byte, it's not a bytezap.
4639 if (MaskB != Byte)
4640 return true;
4641
4642 // Otherwise, this byte is kept.
4643 }
4644
4645 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4646 ByteValues);
4647 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004648 }
4649
Chris Lattner8c34cd22008-10-05 02:13:19 +00004650 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4651 // the input value to the bswap. Some observations: 1) if more than one byte
4652 // is demanded from this input, then it could not be successfully assembled
4653 // into a byteswap. At least one of the two bytes would not be aligned with
4654 // their ultimate destination.
4655 if (!isPowerOf2_32(ByteMask)) return true;
4656 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004657
Chris Lattner8c34cd22008-10-05 02:13:19 +00004658 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4659 // is demanded, it needs to go into byte 0 of the result. This means that the
4660 // byte needs to be shifted until it lands in the right byte bucket. The
4661 // shift amount depends on the position: if the byte is coming from the high
4662 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4663 // low part, it must be shifted left.
4664 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4665 if (InputByteNo < ByteValues.size()/2) {
4666 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4667 return true;
4668 } else {
4669 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4670 return true;
4671 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004672
4673 // If the destination byte value is already defined, the values are or'd
4674 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004675 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004676 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004677 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004678 return false;
4679}
4680
4681/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4682/// If so, insert the new bswap intrinsic and return it.
4683Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004684 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004685 if (!ITy || ITy->getBitWidth() % 16 ||
4686 // ByteMask only allows up to 32-byte values.
4687 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004688 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004689
4690 /// ByteValues - For each byte of the result, we keep track of which value
4691 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004692 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004693 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004694
4695 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004696 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4697 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004698 return 0;
4699
4700 // Check to see if all of the bytes come from the same value.
4701 Value *V = ByteValues[0];
4702 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4703
4704 // Check to make sure that all of the bytes come from the same value.
4705 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4706 if (ByteValues[i] != V)
4707 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004708 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004709 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004710 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004711 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004712}
4713
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004714/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4715/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4716/// we can simplify this expression to "cond ? C : D or B".
4717static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004718 Value *C, Value *D,
4719 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004720 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004721 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004722 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004723 return 0;
4724
Chris Lattnera6a474d2008-11-16 04:26:55 +00004725 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004726 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004727 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004728 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004729 return SelectInst::Create(Cond, C, B);
4730 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004731 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004732 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004733 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004734 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004735 return 0;
4736}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004737
Chris Lattner69d4ced2008-11-16 05:20:07 +00004738/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4739Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4740 ICmpInst *LHS, ICmpInst *RHS) {
4741 Value *Val, *Val2;
4742 ConstantInt *LHSCst, *RHSCst;
4743 ICmpInst::Predicate LHSCC, RHSCC;
4744
4745 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004746 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004747 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004748 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004749 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004750 return 0;
4751
4752 // From here on, we only handle:
4753 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4754 if (Val != Val2) return 0;
4755
4756 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4757 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4758 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4759 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4760 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4761 return 0;
4762
4763 // We can't fold (ugt x, C) | (sgt x, C2).
4764 if (!PredicatesFoldable(LHSCC, RHSCC))
4765 return 0;
4766
4767 // Ensure that the larger constant is on the RHS.
4768 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004769 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004770 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004771 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004772 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4773 else
4774 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4775
4776 if (ShouldSwap) {
4777 std::swap(LHS, RHS);
4778 std::swap(LHSCst, RHSCst);
4779 std::swap(LHSCC, RHSCC);
4780 }
4781
4782 // At this point, we know we have have two icmp instructions
4783 // comparing a value against two constants and or'ing the result
4784 // together. Because of the above check, we know that we only have
4785 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4786 // FoldICmpLogical check above), that the two constants are not
4787 // equal.
4788 assert(LHSCst != RHSCst && "Compares not folded above?");
4789
4790 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004791 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004792 case ICmpInst::ICMP_EQ:
4793 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004794 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004795 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004796 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004797 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004798 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004799 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004800 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004801 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004802 }
4803 break; // (X == 13 | X == 15) -> no change
4804 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4805 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4806 break;
4807 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4808 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4809 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4810 return ReplaceInstUsesWith(I, RHS);
4811 }
4812 break;
4813 case ICmpInst::ICMP_NE:
4814 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004815 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004816 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4817 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4818 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4819 return ReplaceInstUsesWith(I, LHS);
4820 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4821 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4822 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004823 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004824 }
4825 break;
4826 case ICmpInst::ICMP_ULT:
4827 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004828 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004829 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4830 break;
4831 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4832 // If RHSCst is [us]MAXINT, it is always false. Not handling
4833 // this can cause overflow.
4834 if (RHSCst->isMaxValue(false))
4835 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004836 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004837 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004838 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4839 break;
4840 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4841 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4842 return ReplaceInstUsesWith(I, RHS);
4843 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4844 break;
4845 }
4846 break;
4847 case ICmpInst::ICMP_SLT:
4848 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004849 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004850 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4851 break;
4852 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4853 // If RHSCst is [us]MAXINT, it is always false. Not handling
4854 // this can cause overflow.
4855 if (RHSCst->isMaxValue(true))
4856 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004857 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004858 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004859 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4860 break;
4861 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4862 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4863 return ReplaceInstUsesWith(I, RHS);
4864 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4865 break;
4866 }
4867 break;
4868 case ICmpInst::ICMP_UGT:
4869 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004870 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004871 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4872 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4873 return ReplaceInstUsesWith(I, LHS);
4874 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4875 break;
4876 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4877 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004878 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004879 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4880 break;
4881 }
4882 break;
4883 case ICmpInst::ICMP_SGT:
4884 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004885 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004886 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4887 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4888 return ReplaceInstUsesWith(I, LHS);
4889 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4890 break;
4891 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4892 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004893 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004894 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4895 break;
4896 }
4897 break;
4898 }
4899 return 0;
4900}
4901
Chris Lattner5414cc52009-07-23 05:46:22 +00004902Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4903 FCmpInst *RHS) {
4904 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4905 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4906 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4907 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4908 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4909 // If either of the constants are nans, then the whole thing returns
4910 // true.
4911 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004912 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004913
4914 // Otherwise, no need to compare the two constants, compare the
4915 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004916 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004917 LHS->getOperand(0), RHS->getOperand(0));
4918 }
4919
4920 // Handle vector zeros. This occurs because the canonical form of
4921 // "fcmp uno x,x" is "fcmp uno x, 0".
4922 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4923 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004924 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004925 LHS->getOperand(0), RHS->getOperand(0));
4926
4927 return 0;
4928 }
4929
4930 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4931 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4932 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4933
4934 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4935 // Swap RHS operands to match LHS.
4936 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4937 std::swap(Op1LHS, Op1RHS);
4938 }
4939 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4940 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4941 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004942 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004943 Op0LHS, Op0RHS);
4944 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004945 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004946 if (Op0CC == FCmpInst::FCMP_FALSE)
4947 return ReplaceInstUsesWith(I, RHS);
4948 if (Op1CC == FCmpInst::FCMP_FALSE)
4949 return ReplaceInstUsesWith(I, LHS);
4950 bool Op0Ordered;
4951 bool Op1Ordered;
4952 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4953 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4954 if (Op0Ordered == Op1Ordered) {
4955 // If both are ordered or unordered, return a new fcmp with
4956 // or'ed predicates.
4957 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4958 Op0LHS, Op0RHS, Context);
4959 if (Instruction *I = dyn_cast<Instruction>(RV))
4960 return I;
4961 // Otherwise, it's a constant boolean value...
4962 return ReplaceInstUsesWith(I, RV);
4963 }
4964 }
4965 return 0;
4966}
4967
Bill Wendlinga698a472008-12-01 08:23:25 +00004968/// FoldOrWithConstants - This helper function folds:
4969///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004970/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004971///
4972/// into:
4973///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004974/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004975///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004976/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004977Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004978 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004979 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4980 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004981
Bill Wendling286a0542008-12-02 06:24:20 +00004982 Value *V1 = 0;
4983 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004984 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004985
Bill Wendling29976b92008-12-02 06:18:11 +00004986 APInt Xor = CI1->getValue() ^ CI2->getValue();
4987 if (!Xor.isAllOnesValue()) return 0;
4988
Bill Wendling286a0542008-12-02 06:24:20 +00004989 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004990 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004991 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004992 }
4993
4994 return 0;
4995}
4996
Chris Lattner7e708292002-06-25 16:13:24 +00004997Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004998 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004999 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005000
Chris Lattner42593e62007-03-24 23:56:43 +00005001 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00005002 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005003
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005004 // or X, X = X
5005 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00005006 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005007
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005008 // See if we can simplify any instructions used by the instruction whose sole
5009 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005010 if (SimplifyDemandedInstructionBits(I))
5011 return &I;
5012 if (isa<VectorType>(I.getType())) {
5013 if (isa<ConstantAggregateZero>(Op1)) {
5014 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
5015 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
5016 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
5017 return ReplaceInstUsesWith(I, I.getOperand(1));
5018 }
Chris Lattner42593e62007-03-24 23:56:43 +00005019 }
Chris Lattner041a6c92007-06-15 05:26:55 +00005020
Chris Lattner3f5b8772002-05-06 16:14:14 +00005021 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005022 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00005023 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005024 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005025 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005026 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005027 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005028 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005029 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005030 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005031 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005032
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005033 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005034 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005035 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005036 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005037 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005038 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005039 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005040 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005041
5042 // Try to fold constant and into select arguments.
5043 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005044 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005045 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005046 if (isa<PHINode>(Op0))
5047 if (Instruction *NV = FoldOpIntoPhi(I))
5048 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005049 }
5050
Chris Lattner4f637d42006-01-06 17:59:59 +00005051 Value *A = 0, *B = 0;
5052 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005053
Dan Gohman4ae51262009-08-12 16:23:25 +00005054 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005055 if (A == Op1 || B == Op1) // (A & ?) | A --> A
5056 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00005057 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005058 if (A == Op0 || B == Op0) // A | (A & ?) --> A
5059 return ReplaceInstUsesWith(I, Op0);
5060
Chris Lattner6423d4c2006-07-10 20:25:24 +00005061 // (A | B) | C and A | (B | C) -> bswap if possible.
5062 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00005063 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5064 match(Op1, m_Or(m_Value(), m_Value())) ||
5065 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5066 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00005067 if (Instruction *BSwap = MatchBSwap(I))
5068 return BSwap;
5069 }
5070
Chris Lattner6e4c6492005-05-09 04:58:36 +00005071 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005072 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005073 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005074 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005075 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00005076 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005077 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005078 }
5079
5080 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005081 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005082 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005083 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005084 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00005085 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005086 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005087 }
5088
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005089 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00005090 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005091 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5092 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005093 Value *V1 = 0, *V2 = 0, *V3 = 0;
5094 C1 = dyn_cast<ConstantInt>(C);
5095 C2 = dyn_cast<ConstantInt>(D);
5096 if (C1 && C2) { // (A & C1)|(B & C2)
5097 // If we have: ((V + N) & C1) | (V & C2)
5098 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5099 // replace with V+N.
5100 if (C1->getValue() == ~C2->getValue()) {
5101 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00005102 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005103 // Add commutes, try both ways.
5104 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5105 return ReplaceInstUsesWith(I, A);
5106 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5107 return ReplaceInstUsesWith(I, A);
5108 }
5109 // Or commutes, try both ways.
5110 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005111 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005112 // Add commutes, try both ways.
5113 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5114 return ReplaceInstUsesWith(I, B);
5115 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5116 return ReplaceInstUsesWith(I, B);
5117 }
5118 }
Chris Lattner044e5332007-04-08 08:01:49 +00005119 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00005120 }
5121
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005122 // Check to see if we have any common things being and'ed. If so, find the
5123 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005124 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5125 if (A == B) // (A & C)|(A & D) == A & (C|D)
5126 V1 = A, V2 = C, V3 = D;
5127 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5128 V1 = A, V2 = B, V3 = C;
5129 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5130 V1 = C, V2 = A, V3 = D;
5131 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5132 V1 = C, V2 = A, V3 = B;
5133
5134 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00005135 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005136 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00005137 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005138 }
Dan Gohmanb493b272008-10-28 22:38:57 +00005139
Dan Gohman1975d032008-10-30 20:40:10 +00005140 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005141 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005142 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005143 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005144 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005145 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005146 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005147 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005148 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00005149
Bill Wendlingb01865c2008-11-30 13:52:49 +00005150 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005151 if ((match(C, m_Not(m_Specific(D))) &&
5152 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005153 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005154 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005155 if ((match(A, m_Not(m_Specific(D))) &&
5156 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005157 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005158 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005159 if ((match(C, m_Not(m_Specific(B))) &&
5160 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005161 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005162 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005163 if ((match(A, m_Not(m_Specific(B))) &&
5164 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005165 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005166 }
Chris Lattnere511b742006-11-14 07:46:50 +00005167
5168 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00005169 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5170 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5171 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00005172 SI0->getOperand(1) == SI1->getOperand(1) &&
5173 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005174 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5175 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005176 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005177 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005178 }
5179 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005180
Bill Wendlingb3833d12008-12-01 01:07:11 +00005181 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005182 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5183 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005184 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005185 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005186 }
5187 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005188 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5189 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005190 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005191 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005192 }
5193
Chris Lattner48b59ec2009-10-26 15:40:07 +00005194 if ((A = dyn_castNotVal(Op0))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005195 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00005196 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005197 } else {
5198 A = 0;
5199 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005200 // Note, A is still live here!
Chris Lattner48b59ec2009-10-26 15:40:07 +00005201 if ((B = dyn_castNotVal(Op1))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005202 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00005203 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00005204
Misha Brukmancb6267b2004-07-30 12:50:08 +00005205 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005206 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00005207 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00005208 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005209 }
Chris Lattnera27231a2003-03-10 23:13:59 +00005210 }
Chris Lattnera2881962003-02-18 19:28:33 +00005211
Reid Spencere4d87aa2006-12-23 06:05:41 +00005212 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5213 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005214 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005215 return R;
5216
Chris Lattner69d4ced2008-11-16 05:20:07 +00005217 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5218 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5219 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005220 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005221
5222 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005223 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005224 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005225 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005226 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5227 !isa<ICmpInst>(Op1C->getOperand(0))) {
5228 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005229 if (SrcTy == Op1C->getOperand(0)->getType() &&
5230 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005231 // Only do this if the casts both really cause code to be
5232 // generated.
5233 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5234 I.getType(), TD) &&
5235 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5236 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005237 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5238 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005239 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005240 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005241 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005242 }
Chris Lattner99c65742007-10-24 05:38:08 +00005243 }
5244
5245
5246 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5247 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005248 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5249 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5250 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005251 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005252
Chris Lattner7e708292002-06-25 16:13:24 +00005253 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005254}
5255
Dan Gohman844731a2008-05-13 00:00:25 +00005256namespace {
5257
Chris Lattnerc317d392004-02-16 01:20:27 +00005258// XorSelf - Implements: X ^ X --> 0
5259struct XorSelf {
5260 Value *RHS;
5261 XorSelf(Value *rhs) : RHS(rhs) {}
5262 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5263 Instruction *apply(BinaryOperator &Xor) const {
5264 return &Xor;
5265 }
5266};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005267
Dan Gohman844731a2008-05-13 00:00:25 +00005268}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005269
Chris Lattner7e708292002-06-25 16:13:24 +00005270Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005271 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005272 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005273
Evan Chengd34af782008-03-25 20:07:13 +00005274 if (isa<UndefValue>(Op1)) {
5275 if (isa<UndefValue>(Op0))
5276 // Handle undef ^ undef -> 0 special case. This is a common
5277 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005278 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005279 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005280 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005281
Chris Lattnerc317d392004-02-16 01:20:27 +00005282 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005283 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005284 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005285 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005286 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005287
5288 // See if we can simplify any instructions used by the instruction whose sole
5289 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005290 if (SimplifyDemandedInstructionBits(I))
5291 return &I;
5292 if (isa<VectorType>(I.getType()))
5293 if (isa<ConstantAggregateZero>(Op1))
5294 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005295
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005296 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005297 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005298 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5299 if (Op0I->getOpcode() == Instruction::And ||
5300 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005301 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5302 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5303 if (dyn_castNotVal(Op0I->getOperand(1)))
5304 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005305 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005306 Value *NotY =
5307 Builder->CreateNot(Op0I->getOperand(1),
5308 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005309 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005310 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005311 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005312 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005313
5314 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5315 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5316 if (isFreeToInvert(Op0I->getOperand(0)) &&
5317 isFreeToInvert(Op0I->getOperand(1))) {
5318 Value *NotX =
5319 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5320 Value *NotY =
5321 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5322 if (Op0I->getOpcode() == Instruction::And)
5323 return BinaryOperator::CreateOr(NotX, NotY);
5324 return BinaryOperator::CreateAnd(NotX, NotY);
5325 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005326 }
5327 }
5328 }
5329
5330
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005331 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005332 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005333 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005334 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005335 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005336 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005337
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005338 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005339 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005340 FCI->getOperand(0), FCI->getOperand(1));
5341 }
5342
Nick Lewycky517e1f52008-05-31 19:01:33 +00005343 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5344 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5345 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5346 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5347 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005348 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5349 (RHS == ConstantExpr::getCast(Opcode,
5350 ConstantInt::getTrue(*Context),
5351 Op0C->getDestTy()))) {
5352 CI->setPredicate(CI->getInversePredicate());
5353 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005354 }
5355 }
5356 }
5357 }
5358
Reid Spencere4d87aa2006-12-23 06:05:41 +00005359 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005360 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005361 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5362 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005363 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5364 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005365 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005366 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005367 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005368
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005369 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005370 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005371 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005372 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005373 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005374 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005375 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005376 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005377 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005378 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005379 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005380 Constant *C = ConstantInt::get(*Context,
5381 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005382 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005383
Chris Lattner7c4049c2004-01-12 19:35:11 +00005384 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005385 } else if (Op0I->getOpcode() == Instruction::Or) {
5386 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005387 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005388 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005389 // Anything in both C1 and C2 is known to be zero, remove it from
5390 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005391 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5392 NewRHS = ConstantExpr::getAnd(NewRHS,
5393 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005394 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005395 I.setOperand(0, Op0I->getOperand(0));
5396 I.setOperand(1, NewRHS);
5397 return &I;
5398 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005399 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005400 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005401 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005402
5403 // Try to fold constant and into select arguments.
5404 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005405 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005406 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005407 if (isa<PHINode>(Op0))
5408 if (Instruction *NV = FoldOpIntoPhi(I))
5409 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005410 }
5411
Dan Gohman186a6362009-08-12 16:04:34 +00005412 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005413 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005414 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005415
Dan Gohman186a6362009-08-12 16:04:34 +00005416 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005417 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005418 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005419
Chris Lattner318bf792007-03-18 22:51:34 +00005420
5421 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5422 if (Op1I) {
5423 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005424 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005425 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005426 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005427 I.swapOperands();
5428 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005429 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005430 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005431 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005432 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005433 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005434 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005435 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005436 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005437 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005438 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005439 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005440 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005441 std::swap(A, B);
5442 }
Chris Lattner318bf792007-03-18 22:51:34 +00005443 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005444 I.swapOperands(); // Simplified below.
5445 std::swap(Op0, Op1);
5446 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005447 }
Chris Lattner318bf792007-03-18 22:51:34 +00005448 }
5449
5450 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5451 if (Op0I) {
5452 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005453 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005454 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005455 if (A == Op1) // (B|A)^B == (A|B)^B
5456 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005457 if (B == Op1) // (A|B)^B == A & ~B
5458 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005459 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005460 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005461 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005462 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005463 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005464 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005465 if (A == Op1) // (A&B)^A -> (B&A)^A
5466 std::swap(A, B);
5467 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005468 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005469 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005470 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005471 }
Chris Lattner318bf792007-03-18 22:51:34 +00005472 }
5473
5474 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5475 if (Op0I && Op1I && Op0I->isShift() &&
5476 Op0I->getOpcode() == Op1I->getOpcode() &&
5477 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5478 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005479 Value *NewOp =
5480 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5481 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005482 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005483 Op1I->getOperand(1));
5484 }
5485
5486 if (Op0I && Op1I) {
5487 Value *A, *B, *C, *D;
5488 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005489 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5490 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005491 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005492 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005493 }
5494 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005495 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5496 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005497 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005498 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005499 }
5500
5501 // (A & B)^(C & D)
5502 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005503 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5504 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005505 // (X & Y)^(X & Y) -> (Y^Z) & X
5506 Value *X = 0, *Y = 0, *Z = 0;
5507 if (A == C)
5508 X = A, Y = B, Z = D;
5509 else if (A == D)
5510 X = A, Y = B, Z = C;
5511 else if (B == C)
5512 X = B, Y = A, Z = D;
5513 else if (B == D)
5514 X = B, Y = A, Z = C;
5515
5516 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005517 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005518 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005519 }
5520 }
5521 }
5522
Reid Spencere4d87aa2006-12-23 06:05:41 +00005523 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5524 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005525 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005526 return R;
5527
Chris Lattner6fc205f2006-05-05 06:39:07 +00005528 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005529 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005530 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005531 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5532 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005533 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005534 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005535 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5536 I.getType(), TD) &&
5537 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5538 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005539 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5540 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005541 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005542 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005543 }
Chris Lattner99c65742007-10-24 05:38:08 +00005544 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005545
Chris Lattner7e708292002-06-25 16:13:24 +00005546 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005547}
5548
Owen Andersond672ecb2009-07-03 00:17:18 +00005549static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005550 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005551 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005552}
Chris Lattnera96879a2004-09-29 17:40:11 +00005553
Dan Gohman6de29f82009-06-15 22:12:54 +00005554static bool HasAddOverflow(ConstantInt *Result,
5555 ConstantInt *In1, ConstantInt *In2,
5556 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005557 if (IsSigned)
5558 if (In2->getValue().isNegative())
5559 return Result->getValue().sgt(In1->getValue());
5560 else
5561 return Result->getValue().slt(In1->getValue());
5562 else
5563 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005564}
5565
Dan Gohman6de29f82009-06-15 22:12:54 +00005566/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005567/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005568static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005569 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005570 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005571 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005572
Dan Gohman6de29f82009-06-15 22:12:54 +00005573 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5574 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005575 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005576 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5577 ExtractElement(In1, Idx, Context),
5578 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005579 IsSigned))
5580 return true;
5581 }
5582 return false;
5583 }
5584
5585 return HasAddOverflow(cast<ConstantInt>(Result),
5586 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5587 IsSigned);
5588}
5589
5590static bool HasSubOverflow(ConstantInt *Result,
5591 ConstantInt *In1, ConstantInt *In2,
5592 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005593 if (IsSigned)
5594 if (In2->getValue().isNegative())
5595 return Result->getValue().slt(In1->getValue());
5596 else
5597 return Result->getValue().sgt(In1->getValue());
5598 else
5599 return Result->getValue().ugt(In1->getValue());
5600}
5601
Dan Gohman6de29f82009-06-15 22:12:54 +00005602/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5603/// overflowed for this type.
5604static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005605 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005606 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005607 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005608
5609 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5610 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005611 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005612 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5613 ExtractElement(In1, Idx, Context),
5614 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005615 IsSigned))
5616 return true;
5617 }
5618 return false;
5619 }
5620
5621 return HasSubOverflow(cast<ConstantInt>(Result),
5622 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5623 IsSigned);
5624}
5625
Chris Lattner10c0d912008-04-22 02:53:33 +00005626
Reid Spencere4d87aa2006-12-23 06:05:41 +00005627/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005628/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005629Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005630 ICmpInst::Predicate Cond,
5631 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005632 // Look through bitcasts.
5633 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5634 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005635
Chris Lattner574da9b2005-01-13 20:14:25 +00005636 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005637 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005638 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005639 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005640 // know pointers can't overflow since the gep is inbounds. See if we can
5641 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005642 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5643
5644 // If not, synthesize the offset the hard way.
5645 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005646 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005647 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005648 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005649 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005650 // If the base pointers are different, but the indices are the same, just
5651 // compare the base pointer.
5652 if (PtrBase != GEPRHS->getOperand(0)) {
5653 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005654 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005655 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005656 if (IndicesTheSame)
5657 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5658 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5659 IndicesTheSame = false;
5660 break;
5661 }
5662
5663 // If all indices are the same, just compare the base pointers.
5664 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005665 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005666 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005667
5668 // Otherwise, the base pointers are different and the indices are
5669 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005670 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005671 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005672
Chris Lattnere9d782b2005-01-13 22:25:21 +00005673 // If one of the GEPs has all zero indices, recurse.
5674 bool AllZeros = true;
5675 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5676 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5677 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5678 AllZeros = false;
5679 break;
5680 }
5681 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005682 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5683 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005684
5685 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005686 AllZeros = true;
5687 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5688 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5689 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5690 AllZeros = false;
5691 break;
5692 }
5693 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005694 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005695
Chris Lattner4401c9c2005-01-14 00:20:05 +00005696 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5697 // If the GEPs only differ by one index, compare it.
5698 unsigned NumDifferences = 0; // Keep track of # differences.
5699 unsigned DiffOperand = 0; // The operand that differs.
5700 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5701 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005702 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5703 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005704 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005705 NumDifferences = 2;
5706 break;
5707 } else {
5708 if (NumDifferences++) break;
5709 DiffOperand = i;
5710 }
5711 }
5712
5713 if (NumDifferences == 0) // SAME GEP?
5714 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005715 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005716 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005717
Chris Lattner4401c9c2005-01-14 00:20:05 +00005718 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005719 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5720 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005721 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005722 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005723 }
5724 }
5725
Reid Spencere4d87aa2006-12-23 06:05:41 +00005726 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005727 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005728 if (TD &&
5729 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005730 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5731 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005732 Value *L = EmitGEPOffset(GEPLHS, *this);
5733 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005734 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005735 }
5736 }
5737 return 0;
5738}
5739
Chris Lattnera5406232008-05-19 20:18:56 +00005740/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5741///
5742Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5743 Instruction *LHSI,
5744 Constant *RHSC) {
5745 if (!isa<ConstantFP>(RHSC)) return 0;
5746 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5747
5748 // Get the width of the mantissa. We don't want to hack on conversions that
5749 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005750 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005751 if (MantissaWidth == -1) return 0; // Unknown.
5752
5753 // Check to see that the input is converted from an integer type that is small
5754 // enough that preserves all bits. TODO: check here for "known" sign bits.
5755 // 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 +00005756 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005757
5758 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005759 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5760 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005761 ++InputSize;
5762
5763 // If the conversion would lose info, don't hack on this.
5764 if ((int)InputSize > MantissaWidth)
5765 return 0;
5766
5767 // Otherwise, we can potentially simplify the comparison. We know that it
5768 // will always come through as an integer value and we know the constant is
5769 // not a NAN (it would have been previously simplified).
5770 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5771
5772 ICmpInst::Predicate Pred;
5773 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005774 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005775 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005776 case FCmpInst::FCMP_OEQ:
5777 Pred = ICmpInst::ICMP_EQ;
5778 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005779 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005780 case FCmpInst::FCMP_OGT:
5781 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5782 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005783 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005784 case FCmpInst::FCMP_OGE:
5785 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5786 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005787 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005788 case FCmpInst::FCMP_OLT:
5789 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5790 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005791 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005792 case FCmpInst::FCMP_OLE:
5793 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5794 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005795 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005796 case FCmpInst::FCMP_ONE:
5797 Pred = ICmpInst::ICMP_NE;
5798 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005799 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005800 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005801 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005802 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005803 }
5804
5805 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5806
5807 // Now we know that the APFloat is a normal number, zero or inf.
5808
Chris Lattner85162782008-05-20 03:50:52 +00005809 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005810 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005811 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005812
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005813 if (!LHSUnsigned) {
5814 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5815 // and large values.
5816 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5817 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5818 APFloat::rmNearestTiesToEven);
5819 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5820 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5821 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005822 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5823 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005824 }
5825 } else {
5826 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5827 // +INF and large values.
5828 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5829 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5830 APFloat::rmNearestTiesToEven);
5831 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5832 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5833 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005834 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5835 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005836 }
Chris Lattnera5406232008-05-19 20:18:56 +00005837 }
5838
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005839 if (!LHSUnsigned) {
5840 // See if the RHS value is < SignedMin.
5841 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5842 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5843 APFloat::rmNearestTiesToEven);
5844 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5845 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5846 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005847 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5848 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005849 }
Chris Lattnera5406232008-05-19 20:18:56 +00005850 }
5851
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005852 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5853 // [0, UMAX], but it may still be fractional. See if it is fractional by
5854 // casting the FP value to the integer value and back, checking for equality.
5855 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005856 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005857 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5858 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005859 if (!RHS.isZero()) {
5860 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005861 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5862 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005863 if (!Equal) {
5864 // If we had a comparison against a fractional value, we have to adjust
5865 // the compare predicate and sometimes the value. RHSC is rounded towards
5866 // zero at this point.
5867 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005868 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005869 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005870 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005871 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005872 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005873 case ICmpInst::ICMP_ULE:
5874 // (float)int <= 4.4 --> int <= 4
5875 // (float)int <= -4.4 --> false
5876 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005877 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005878 break;
5879 case ICmpInst::ICMP_SLE:
5880 // (float)int <= 4.4 --> int <= 4
5881 // (float)int <= -4.4 --> int < -4
5882 if (RHS.isNegative())
5883 Pred = ICmpInst::ICMP_SLT;
5884 break;
5885 case ICmpInst::ICMP_ULT:
5886 // (float)int < -4.4 --> false
5887 // (float)int < 4.4 --> int <= 4
5888 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005889 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005890 Pred = ICmpInst::ICMP_ULE;
5891 break;
5892 case ICmpInst::ICMP_SLT:
5893 // (float)int < -4.4 --> int < -4
5894 // (float)int < 4.4 --> int <= 4
5895 if (!RHS.isNegative())
5896 Pred = ICmpInst::ICMP_SLE;
5897 break;
5898 case ICmpInst::ICMP_UGT:
5899 // (float)int > 4.4 --> int > 4
5900 // (float)int > -4.4 --> true
5901 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005902 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005903 break;
5904 case ICmpInst::ICMP_SGT:
5905 // (float)int > 4.4 --> int > 4
5906 // (float)int > -4.4 --> int >= -4
5907 if (RHS.isNegative())
5908 Pred = ICmpInst::ICMP_SGE;
5909 break;
5910 case ICmpInst::ICMP_UGE:
5911 // (float)int >= -4.4 --> true
5912 // (float)int >= 4.4 --> int > 4
5913 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005914 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005915 Pred = ICmpInst::ICMP_UGT;
5916 break;
5917 case ICmpInst::ICMP_SGE:
5918 // (float)int >= -4.4 --> int >= -4
5919 // (float)int >= 4.4 --> int > 4
5920 if (!RHS.isNegative())
5921 Pred = ICmpInst::ICMP_SGT;
5922 break;
5923 }
Chris Lattnera5406232008-05-19 20:18:56 +00005924 }
5925 }
5926
5927 // Lower this FP comparison into an appropriate integer version of the
5928 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005929 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005930}
5931
Reid Spencere4d87aa2006-12-23 06:05:41 +00005932Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00005933 bool Changed = false;
5934
5935 /// Orders the operands of the compare so that they are listed from most
5936 /// complex to least complex. This puts constants before unary operators,
5937 /// before binary operators.
5938 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5939 I.swapOperands();
5940 Changed = true;
5941 }
5942
Chris Lattner8b170942002-08-09 23:47:40 +00005943 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner58e97462007-01-14 19:42:17 +00005944
Chris Lattner210c5d42009-11-09 23:55:12 +00005945 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
5946 return ReplaceInstUsesWith(I, V);
5947
Chris Lattner58e97462007-01-14 19:42:17 +00005948 // Simplify 'fcmp pred X, X'
5949 if (Op0 == Op1) {
5950 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005951 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005952 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5953 case FCmpInst::FCMP_ULT: // True if unordered or less than
5954 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5955 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5956 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5957 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005958 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005959 return &I;
5960
5961 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5962 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5963 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5964 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5965 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5966 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005967 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005968 return &I;
5969 }
5970 }
5971
Reid Spencere4d87aa2006-12-23 06:05:41 +00005972 // Handle fcmp with constant RHS
5973 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5974 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5975 switch (LHSI->getOpcode()) {
5976 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005977 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5978 // block. If in the same block, we're encouraging jump threading. If
5979 // not, we are just pessimizing the code by making an i1 phi.
5980 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005981 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005982 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005983 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005984 case Instruction::SIToFP:
5985 case Instruction::UIToFP:
5986 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5987 return NV;
5988 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005989 case Instruction::Select:
5990 // If either operand of the select is a constant, we can fold the
5991 // comparison into the select arms, which will cause one to be
5992 // constant folded and the select turned into a bitwise or.
5993 Value *Op1 = 0, *Op2 = 0;
5994 if (LHSI->hasOneUse()) {
5995 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5996 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005997 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005998 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005999 Op2 = Builder->CreateFCmp(I.getPredicate(),
6000 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006001 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6002 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006003 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006004 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006005 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6006 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006007 }
6008 }
6009
6010 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006011 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006012 break;
6013 }
6014 }
6015
6016 return Changed ? &I : 0;
6017}
6018
6019Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006020 bool Changed = false;
6021
6022 /// Orders the operands of the compare so that they are listed from most
6023 /// complex to least complex. This puts constants before unary operators,
6024 /// before binary operators.
6025 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6026 I.swapOperands();
6027 Changed = true;
6028 }
6029
Reid Spencere4d87aa2006-12-23 06:05:41 +00006030 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006031
Chris Lattner210c5d42009-11-09 23:55:12 +00006032 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6033 return ReplaceInstUsesWith(I, V);
6034
6035 const Type *Ty = Op0->getType();
Chris Lattner8b170942002-08-09 23:47:40 +00006036
Reid Spencere4d87aa2006-12-23 06:05:41 +00006037 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006038 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006039 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006040 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006041 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006042 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006043 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006044 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006045 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006046 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006047
Reid Spencere4d87aa2006-12-23 06:05:41 +00006048 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006049 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006050 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006051 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006052 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006053 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006054 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006055 case ICmpInst::ICMP_SGT:
6056 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006057 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006058 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006059 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006060 return BinaryOperator::CreateAnd(Not, Op0);
6061 }
6062 case ICmpInst::ICMP_UGE:
6063 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6064 // FALL THROUGH
6065 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006066 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006067 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006068 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006069 case ICmpInst::ICMP_SGE:
6070 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6071 // FALL THROUGH
6072 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006073 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006074 return BinaryOperator::CreateOr(Not, Op0);
6075 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006076 }
Chris Lattner8b170942002-08-09 23:47:40 +00006077 }
6078
Dan Gohman1c8491e2009-04-25 17:12:48 +00006079 unsigned BitWidth = 0;
6080 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006081 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6082 else if (Ty->isIntOrIntVector())
6083 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006084
6085 bool isSignBit = false;
6086
Dan Gohman81b28ce2008-09-16 18:46:06 +00006087 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006088 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006089 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006090
Chris Lattnerb6566012008-01-05 01:18:20 +00006091 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6092 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006093 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006094 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006095 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006096 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006097
Dan Gohman81b28ce2008-09-16 18:46:06 +00006098 // If we have an icmp le or icmp ge instruction, turn it into the
6099 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner210c5d42009-11-09 23:55:12 +00006100 // them being folded in the code below. The SimplifyICmpInst code has
6101 // already handled the edge cases for us, so we just assert on them.
Chris Lattner84dff672008-07-11 05:08:55 +00006102 switch (I.getPredicate()) {
6103 default: break;
6104 case ICmpInst::ICMP_ULE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006105 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006106 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006107 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006108 case ICmpInst::ICMP_SLE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006109 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006110 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006111 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006112 case ICmpInst::ICMP_UGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006113 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006114 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006115 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006116 case ICmpInst::ICMP_SGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006117 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006118 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006119 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006120 }
6121
Chris Lattner183661e2008-07-11 05:40:05 +00006122 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006123 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006124 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006125 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6126 }
6127
6128 // See if we can fold the comparison based on range information we can get
6129 // by checking whether bits are known to be zero or one in the input.
6130 if (BitWidth != 0) {
6131 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6132 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6133
6134 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006135 isSignBit ? APInt::getSignBit(BitWidth)
6136 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006137 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006138 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006139 if (SimplifyDemandedBits(I.getOperandUse(1),
6140 APInt::getAllOnesValue(BitWidth),
6141 Op1KnownZero, Op1KnownOne, 0))
6142 return &I;
6143
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006144 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006145 // in. Compute the Min, Max and RHS values based on the known bits. For the
6146 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006147 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6148 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006149 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006150 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6151 Op0Min, Op0Max);
6152 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6153 Op1Min, Op1Max);
6154 } else {
6155 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6156 Op0Min, Op0Max);
6157 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6158 Op1Min, Op1Max);
6159 }
6160
Chris Lattner183661e2008-07-11 05:40:05 +00006161 // If Min and Max are known to be the same, then SimplifyDemandedBits
6162 // figured out that the LHS is a constant. Just constant fold this now so
6163 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006165 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006166 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006168 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006169 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006170
Chris Lattner183661e2008-07-11 05:40:05 +00006171 // Based on the range information we know about the LHS, see if we can
6172 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006173 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006174 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006175 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006176 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006177 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006178 break;
6179 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006180 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006181 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006182 break;
6183 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006185 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006187 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006188 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006189 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006190 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6191 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006192 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006193 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006194
6195 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6196 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006197 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006198 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006199 }
Chris Lattner84dff672008-07-11 05:08:55 +00006200 break;
6201 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006202 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006203 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006204 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006205 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206
6207 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006208 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006209 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6210 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006211 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006212 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006213
6214 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6215 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006216 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006217 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006218 }
Chris Lattner84dff672008-07-11 05:08:55 +00006219 break;
6220 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006221 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006222 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006223 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006224 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006225 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006226 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006227 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6228 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006229 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006230 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231 }
Chris Lattner84dff672008-07-11 05:08:55 +00006232 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006233 case ICmpInst::ICMP_SGT:
6234 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006235 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006236 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006237 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006238
6239 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006240 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006241 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6242 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006243 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006244 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006245 }
6246 break;
6247 case ICmpInst::ICMP_SGE:
6248 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6249 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006250 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006251 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006252 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006253 break;
6254 case ICmpInst::ICMP_SLE:
6255 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6256 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006257 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006258 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006259 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006260 break;
6261 case ICmpInst::ICMP_UGE:
6262 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6263 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006264 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006265 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006266 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006267 break;
6268 case ICmpInst::ICMP_ULE:
6269 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6270 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006271 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006272 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006273 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006274 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006275 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006276
6277 // Turn a signed comparison into an unsigned one if both operands
6278 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006279 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006280 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6281 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006282 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006283 }
6284
6285 // Test if the ICmpInst instruction is used exclusively by a select as
6286 // part of a minimum or maximum operation. If so, refrain from doing
6287 // any other folding. This helps out other analyses which understand
6288 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6289 // and CodeGen. And in this case, at least one of the comparison
6290 // operands has at least one user besides the compare (the select),
6291 // which would often largely negate the benefit of folding anyway.
6292 if (I.hasOneUse())
6293 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6294 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6295 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6296 return 0;
6297
6298 // See if we are doing a comparison between a constant and an instruction that
6299 // can be folded into the comparison.
6300 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006301 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006302 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006303 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006304 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006305 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6306 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006307 }
6308
Chris Lattner01deb9d2007-04-03 17:43:25 +00006309 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006310 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6311 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6312 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006313 case Instruction::GetElementPtr:
6314 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006315 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006316 bool isAllZeros = true;
6317 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6318 if (!isa<Constant>(LHSI->getOperand(i)) ||
6319 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6320 isAllZeros = false;
6321 break;
6322 }
6323 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006324 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006325 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006326 }
6327 break;
6328
Chris Lattner6970b662005-04-23 15:31:55 +00006329 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006330 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006331 // block. If in the same block, we're encouraging jump threading. If
6332 // not, we are just pessimizing the code by making an i1 phi.
6333 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006334 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006335 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006336 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006337 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006338 // If either operand of the select is a constant, we can fold the
6339 // comparison into the select arms, which will cause one to be
6340 // constant folded and the select turned into a bitwise or.
6341 Value *Op1 = 0, *Op2 = 0;
6342 if (LHSI->hasOneUse()) {
6343 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6344 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006345 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006346 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006347 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6348 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006349 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6350 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006351 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006352 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006353 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6354 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006355 }
6356 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006357
Chris Lattner6970b662005-04-23 15:31:55 +00006358 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006359 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006360 break;
6361 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006362 case Instruction::Call:
6363 // If we have (malloc != null), and if the malloc has a single use, we
6364 // can assume it is successful and remove the malloc.
6365 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6366 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006367 // Need to explicitly erase malloc call here, instead of adding it to
6368 // Worklist, because it won't get DCE'd from the Worklist since
6369 // isInstructionTriviallyDead() returns false for function calls.
6370 // It is OK to replace LHSI/MallocCall with Undef because the
6371 // instruction that uses it will be erased via Worklist.
6372 if (extractMallocCall(LHSI)) {
6373 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6374 EraseInstFromFunction(*LHSI);
6375 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006376 ConstantInt::get(Type::getInt1Ty(*Context),
6377 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006378 }
6379 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6380 if (MallocCall->hasOneUse()) {
6381 MallocCall->replaceAllUsesWith(
6382 UndefValue::get(MallocCall->getType()));
6383 EraseInstFromFunction(*MallocCall);
6384 Worklist.Add(LHSI); // The malloc's bitcast use.
6385 return ReplaceInstUsesWith(I,
6386 ConstantInt::get(Type::getInt1Ty(*Context),
6387 !I.isTrueWhenEqual()));
6388 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006389 }
6390 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006391 }
Chris Lattner6970b662005-04-23 15:31:55 +00006392 }
6393
Reid Spencere4d87aa2006-12-23 06:05:41 +00006394 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006395 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006396 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006397 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006398 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006399 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6400 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006401 return NI;
6402
Reid Spencere4d87aa2006-12-23 06:05:41 +00006403 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006404 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6405 // now.
6406 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6407 if (isa<PointerType>(Op0->getType()) &&
6408 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006409 // We keep moving the cast from the left operand over to the right
6410 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006411 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006412
Chris Lattner57d86372007-01-06 01:45:59 +00006413 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6414 // so eliminate it as well.
6415 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6416 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006417
Chris Lattnerde90b762003-11-03 04:25:02 +00006418 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006419 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006420 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006421 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006422 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006423 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006424 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006425 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006426 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006427 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006428 }
Chris Lattner57d86372007-01-06 01:45:59 +00006429 }
6430
6431 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006432 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006433 // This comes up when you have code like
6434 // int X = A < B;
6435 // if (X) ...
6436 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006437 // with a constant or another cast from the same type.
6438 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006439 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006440 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006441 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006442
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006443 // See if it's the same type of instruction on the left and right.
6444 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6445 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006446 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006447 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006448 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006449 default: break;
6450 case Instruction::Add:
6451 case Instruction::Sub:
6452 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006453 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006454 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006455 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006456 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6457 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6458 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006459 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006460 ? I.getUnsignedPredicate()
6461 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006462 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006463 Op1I->getOperand(0));
6464 }
6465
6466 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006467 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006468 ? I.getUnsignedPredicate()
6469 : I.getSignedPredicate();
6470 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006471 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006472 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006473 }
6474 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006475 break;
6476 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006477 if (!I.isEquality())
6478 break;
6479
Nick Lewycky5d52c452008-08-21 05:56:10 +00006480 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6481 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6482 // Mask = -1 >> count-trailing-zeros(Cst).
6483 if (!CI->isZero() && !CI->isOne()) {
6484 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006485 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006486 APInt::getLowBitsSet(AP.getBitWidth(),
6487 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006488 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006489 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6490 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006491 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006492 }
6493 }
6494 break;
6495 }
6496 }
6497 }
6498 }
6499
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006500 // ~x < ~y --> y < x
6501 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006502 if (match(Op0, m_Not(m_Value(A))) &&
6503 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006504 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006505 }
6506
Chris Lattner65b72ba2006-09-18 04:22:48 +00006507 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006508 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006509
6510 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006511 if (match(Op0, m_Neg(m_Value(A))) &&
6512 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006513 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006514
Dan Gohman4ae51262009-08-12 16:23:25 +00006515 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006516 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6517 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006518 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006519 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006520 }
6521
Dan Gohman4ae51262009-08-12 16:23:25 +00006522 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006523 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006524 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006525 if (match(B, m_ConstantInt(C1)) &&
6526 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006527 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006528 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006529 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6530 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006531 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006532
6533 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006534 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6535 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6536 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6537 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006538 }
6539 }
6540
Dan Gohman4ae51262009-08-12 16:23:25 +00006541 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006542 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006543 // A == (A^B) -> B == 0
6544 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006545 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006546 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006547 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006548
6549 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006550 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006551 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006552 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006553
6554 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006555 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006556 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006557 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006558
Chris Lattner9c2328e2006-11-14 06:06:06 +00006559 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6560 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006561 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6562 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006563 Value *X = 0, *Y = 0, *Z = 0;
6564
6565 if (A == C) {
6566 X = B; Y = D; Z = A;
6567 } else if (A == D) {
6568 X = B; Y = C; Z = A;
6569 } else if (B == C) {
6570 X = A; Y = D; Z = B;
6571 } else if (B == D) {
6572 X = A; Y = C; Z = B;
6573 }
6574
6575 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006576 Op1 = Builder->CreateXor(X, Y, "tmp");
6577 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006578 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006579 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006580 return &I;
6581 }
6582 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006583 }
Chris Lattner7e708292002-06-25 16:13:24 +00006584 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006585}
6586
Chris Lattner562ef782007-06-20 23:46:26 +00006587
6588/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6589/// and CmpRHS are both known to be integer constants.
6590Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6591 ConstantInt *DivRHS) {
6592 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6593 const APInt &CmpRHSV = CmpRHS->getValue();
6594
6595 // FIXME: If the operand types don't match the type of the divide
6596 // then don't attempt this transform. The code below doesn't have the
6597 // logic to deal with a signed divide and an unsigned compare (and
6598 // vice versa). This is because (x /s C1) <s C2 produces different
6599 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6600 // (x /u C1) <u C2. Simply casting the operands and result won't
6601 // work. :( The if statement below tests that condition and bails
6602 // if it finds it.
6603 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006604 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00006605 return 0;
6606 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006607 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006608 if (DivIsSigned && DivRHS->isAllOnesValue())
6609 return 0; // The overflow computation also screws up here
6610 if (DivRHS->isOne())
6611 return 0; // Not worth bothering, and eliminates some funny cases
6612 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006613
6614 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6615 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6616 // C2 (CI). By solving for X we can turn this into a range check
6617 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006618 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006619
6620 // Determine if the product overflows by seeing if the product is
6621 // not equal to the divide. Make sure we do the same kind of divide
6622 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006623 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6624 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006625
6626 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006627 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006628
Chris Lattner1dbfd482007-06-21 18:11:19 +00006629 // Figure out the interval that is being checked. For example, a comparison
6630 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6631 // Compute this interval based on the constants involved and the signedness of
6632 // the compare/divide. This computes a half-open interval, keeping track of
6633 // whether either value in the interval overflows. After analysis each
6634 // overflow variable is set to 0 if it's corresponding bound variable is valid
6635 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6636 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006637 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006638
Chris Lattner562ef782007-06-20 23:46:26 +00006639 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006640 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006641 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006642 HiOverflow = LoOverflow = ProdOV;
6643 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006644 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006645 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006646 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006647 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006648 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006649 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006650 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006651 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6652 HiOverflow = LoOverflow = ProdOV;
6653 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006654 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006655 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006656 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006657 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006658 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6659 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006660 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006661 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006662 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006663 true) ? -1 : 0;
6664 }
Chris Lattner562ef782007-06-20 23:46:26 +00006665 }
Dan Gohman76491272008-02-13 22:09:18 +00006666 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006667 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006668 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006669 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006670 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006671 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6672 HiOverflow = 1; // [INTMIN+1, overflow)
6673 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6674 }
Dan Gohman76491272008-02-13 22:09:18 +00006675 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006676 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006677 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006678 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006679 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006680 LoOverflow = AddWithOverflow(LoBound, HiBound,
6681 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006682 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006683 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6684 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006685 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006686 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006687 }
6688
Chris Lattner1dbfd482007-06-21 18:11:19 +00006689 // Dividing by a negative swaps the condition. LT <-> GT
6690 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006691 }
6692
6693 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006694 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006695 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006696 case ICmpInst::ICMP_EQ:
6697 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006698 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006699 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006700 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006701 ICmpInst::ICMP_UGE, X, LoBound);
6702 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006703 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006704 ICmpInst::ICMP_ULT, X, HiBound);
6705 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006706 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006707 case ICmpInst::ICMP_NE:
6708 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006709 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006710 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006711 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006712 ICmpInst::ICMP_ULT, X, LoBound);
6713 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006714 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006715 ICmpInst::ICMP_UGE, X, HiBound);
6716 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006717 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006718 case ICmpInst::ICMP_ULT:
6719 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006720 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006721 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006722 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006723 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006724 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006725 case ICmpInst::ICMP_UGT:
6726 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006727 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006728 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006729 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006730 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006731 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006732 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006733 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006734 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006735 }
6736}
6737
6738
Chris Lattner01deb9d2007-04-03 17:43:25 +00006739/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6740///
6741Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6742 Instruction *LHSI,
6743 ConstantInt *RHS) {
6744 const APInt &RHSV = RHS->getValue();
6745
6746 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006747 case Instruction::Trunc:
6748 if (ICI.isEquality() && LHSI->hasOneUse()) {
6749 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6750 // of the high bits truncated out of x are known.
6751 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6752 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6753 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6754 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6755 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6756
6757 // If all the high bits are known, we can do this xform.
6758 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6759 // Pull in the high bits from known-ones set.
6760 APInt NewRHS(RHS->getValue());
6761 NewRHS.zext(SrcBits);
6762 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006763 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006764 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006765 }
6766 }
6767 break;
6768
Duncan Sands0091bf22007-04-04 06:42:45 +00006769 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006770 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6771 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6772 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006773 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6774 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006775 Value *CompareVal = LHSI->getOperand(0);
6776
6777 // If the sign bit of the XorCST is not set, there is no change to
6778 // the operation, just stop using the Xor.
6779 if (!XorCST->getValue().isNegative()) {
6780 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006781 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006782 return &ICI;
6783 }
6784
6785 // Was the old condition true if the operand is positive?
6786 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6787
6788 // If so, the new one isn't.
6789 isTrueIfPositive ^= true;
6790
6791 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006792 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006793 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006794 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006795 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006796 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006797 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006798
6799 if (LHSI->hasOneUse()) {
6800 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6801 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6802 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006803 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006804 ? ICI.getUnsignedPredicate()
6805 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006806 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006807 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006808 }
6809
6810 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006811 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006812 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006813 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006814 ? ICI.getUnsignedPredicate()
6815 : ICI.getSignedPredicate();
6816 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006817 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006818 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006819 }
6820 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006821 }
6822 break;
6823 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6824 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6825 LHSI->getOperand(0)->hasOneUse()) {
6826 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6827
6828 // If the LHS is an AND of a truncating cast, we can widen the
6829 // and/compare to be the input width without changing the value
6830 // produced, eliminating a cast.
6831 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6832 // We can do this transformation if either the AND constant does not
6833 // have its sign bit set or if it is an equality comparison.
6834 // Extending a relational comparison when we're checking the sign
6835 // bit would not work.
6836 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006837 (ICI.isEquality() ||
6838 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006839 uint32_t BitWidth =
6840 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6841 APInt NewCST = AndCST->getValue();
6842 NewCST.zext(BitWidth);
6843 APInt NewCI = RHSV;
6844 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006845 Value *NewAnd =
6846 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006847 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006848 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006849 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006850 }
6851 }
6852
6853 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6854 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6855 // happens a LOT in code produced by the C front-end, for bitfield
6856 // access.
6857 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6858 if (Shift && !Shift->isShift())
6859 Shift = 0;
6860
6861 ConstantInt *ShAmt;
6862 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6863 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6864 const Type *AndTy = AndCST->getType(); // Type of the and.
6865
6866 // We can fold this as long as we can't shift unknown bits
6867 // into the mask. This can only happen with signed shift
6868 // rights, as they sign-extend.
6869 if (ShAmt) {
6870 bool CanFold = Shift->isLogicalShift();
6871 if (!CanFold) {
6872 // To test for the bad case of the signed shr, see if any
6873 // of the bits shifted in could be tested after the mask.
6874 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6875 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6876
6877 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6878 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6879 AndCST->getValue()) == 0)
6880 CanFold = true;
6881 }
6882
6883 if (CanFold) {
6884 Constant *NewCst;
6885 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006886 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006887 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006888 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006889
6890 // Check to see if we are shifting out any of the bits being
6891 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006892 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006893 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006894 // If we shifted bits out, the fold is not going to work out.
6895 // As a special case, check to see if this means that the
6896 // result is always true or false now.
6897 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006898 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006899 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006900 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006901 } else {
6902 ICI.setOperand(1, NewCst);
6903 Constant *NewAndCST;
6904 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006905 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006906 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006907 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006908 LHSI->setOperand(1, NewAndCST);
6909 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006910 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006911 return &ICI;
6912 }
6913 }
6914 }
6915
6916 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6917 // preferable because it allows the C<<Y expression to be hoisted out
6918 // of a loop if Y is invariant and X is not.
6919 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006920 ICI.isEquality() && !Shift->isArithmeticShift() &&
6921 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006922 // Compute C << Y.
6923 Value *NS;
6924 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006925 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006926 } else {
6927 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006928 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006929 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006930
6931 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006932 Value *NewAnd =
6933 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006934
6935 ICI.setOperand(0, NewAnd);
6936 return &ICI;
6937 }
6938 }
6939 break;
6940
Chris Lattnera0141b92007-07-15 20:42:37 +00006941 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6942 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6943 if (!ShAmt) break;
6944
6945 uint32_t TypeBits = RHSV.getBitWidth();
6946
6947 // Check that the shift amount is in range. If not, don't perform
6948 // undefined shifts. When the shift is visited it will be
6949 // simplified.
6950 if (ShAmt->uge(TypeBits))
6951 break;
6952
6953 if (ICI.isEquality()) {
6954 // If we are comparing against bits always shifted out, the
6955 // comparison cannot succeed.
6956 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006957 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006958 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006959 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6960 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006961 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006962 return ReplaceInstUsesWith(ICI, Cst);
6963 }
6964
6965 if (LHSI->hasOneUse()) {
6966 // Otherwise strength reduce the shift into an and.
6967 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6968 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006969 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006970 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006971
Chris Lattner74381062009-08-30 07:44:24 +00006972 Value *And =
6973 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006974 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006975 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006976 }
6977 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006978
6979 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6980 bool TrueIfSigned = false;
6981 if (LHSI->hasOneUse() &&
6982 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6983 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006984 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006985 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006986 Value *And =
6987 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006988 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006989 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006990 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006991 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006992 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006993
6994 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006995 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006996 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006997 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006998 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006999
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007000 // Check that the shift amount is in range. If not, don't perform
7001 // undefined shifts. When the shift is visited it will be
7002 // simplified.
7003 uint32_t TypeBits = RHSV.getBitWidth();
7004 if (ShAmt->uge(TypeBits))
7005 break;
7006
7007 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007008
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007009 // If we are comparing against bits always shifted out, the
7010 // comparison cannot succeed.
7011 APInt Comp = RHSV << ShAmtVal;
7012 if (LHSI->getOpcode() == Instruction::LShr)
7013 Comp = Comp.lshr(ShAmtVal);
7014 else
7015 Comp = Comp.ashr(ShAmtVal);
7016
7017 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7018 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007019 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007020 return ReplaceInstUsesWith(ICI, Cst);
7021 }
7022
7023 // Otherwise, check to see if the bits shifted out are known to be zero.
7024 // If so, we can compare against the unshifted value:
7025 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007026 if (LHSI->hasOneUse() &&
7027 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007028 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007029 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007030 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007031 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007032
Evan Chengf30752c2008-04-23 00:38:06 +00007033 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007034 // Otherwise strength reduce the shift into an and.
7035 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007036 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007037
Chris Lattner74381062009-08-30 07:44:24 +00007038 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7039 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007040 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007041 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007042 }
7043 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007044 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007045
7046 case Instruction::SDiv:
7047 case Instruction::UDiv:
7048 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7049 // Fold this div into the comparison, producing a range check.
7050 // Determine, based on the divide type, what the range is being
7051 // checked. If there is an overflow on the low or high side, remember
7052 // it, otherwise compute the range [low, hi) bounding the new value.
7053 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007054 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7055 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7056 DivRHS))
7057 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007058 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007059
7060 case Instruction::Add:
7061 // Fold: icmp pred (add, X, C1), C2
7062
7063 if (!ICI.isEquality()) {
7064 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7065 if (!LHSC) break;
7066 const APInt &LHSV = LHSC->getValue();
7067
7068 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7069 .subtract(LHSV);
7070
Nick Lewycky4a134af2009-10-25 05:20:17 +00007071 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007072 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007073 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007074 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007075 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007076 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007077 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007078 }
7079 } else {
7080 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007081 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007082 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007083 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007084 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007085 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007086 }
7087 }
7088 }
7089 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007090 }
7091
7092 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7093 if (ICI.isEquality()) {
7094 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7095
7096 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7097 // the second operand is a constant, simplify a bit.
7098 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7099 switch (BO->getOpcode()) {
7100 case Instruction::SRem:
7101 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7102 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7103 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7104 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007105 Value *NewRem =
7106 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7107 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007108 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007109 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007110 }
7111 }
7112 break;
7113 case Instruction::Add:
7114 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7115 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7116 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007117 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007118 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007119 } else if (RHSV == 0) {
7120 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7121 // efficiently invertible, or if the add has just this one use.
7122 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7123
Dan Gohman186a6362009-08-12 16:04:34 +00007124 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007125 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007126 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007127 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007128 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007129 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007130 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007131 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007132 }
7133 }
7134 break;
7135 case Instruction::Xor:
7136 // For the xor case, we can xor two constants together, eliminating
7137 // the explicit xor.
7138 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007139 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007140 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007141
7142 // FALLTHROUGH
7143 case Instruction::Sub:
7144 // Replace (([sub|xor] A, B) != 0) with (A != B)
7145 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007146 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007147 BO->getOperand(1));
7148 break;
7149
7150 case Instruction::Or:
7151 // If bits are being or'd in that are not present in the constant we
7152 // are comparing against, then the comparison could never succeed!
7153 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007154 Constant *NotCI = ConstantExpr::getNot(RHS);
7155 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007156 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007157 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007158 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007159 }
7160 break;
7161
7162 case Instruction::And:
7163 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7164 // If bits are being compared against that are and'd out, then the
7165 // comparison can never succeed!
7166 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007167 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007168 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007169 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007170
7171 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7172 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007173 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007174 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007175 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007176
7177 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007178 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007179 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007180 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007181 ICmpInst::Predicate pred = isICMP_NE ?
7182 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007183 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007184 }
7185
7186 // ((X & ~7) == 0) --> X < 8
7187 if (RHSV == 0 && isHighOnes(BOC)) {
7188 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007189 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007190 ICmpInst::Predicate pred = isICMP_NE ?
7191 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007192 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007193 }
7194 }
7195 default: break;
7196 }
7197 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7198 // Handle icmp {eq|ne} <intrinsic>, intcst.
7199 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007200 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007201 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007202 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007203 return &ICI;
7204 }
7205 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007206 }
7207 return 0;
7208}
7209
7210/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7211/// We only handle extending casts so far.
7212///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007213Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7214 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007215 Value *LHSCIOp = LHSCI->getOperand(0);
7216 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007217 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007218 Value *RHSCIOp;
7219
Chris Lattner8c756c12007-05-05 22:41:33 +00007220 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7221 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007222 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7223 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007224 cast<IntegerType>(DestTy)->getBitWidth()) {
7225 Value *RHSOp = 0;
7226 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007227 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007228 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7229 RHSOp = RHSC->getOperand(0);
7230 // If the pointer types don't match, insert a bitcast.
7231 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007232 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007233 }
7234
7235 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007236 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007237 }
7238
7239 // The code below only handles extension cast instructions, so far.
7240 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007241 if (LHSCI->getOpcode() != Instruction::ZExt &&
7242 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007243 return 0;
7244
Reid Spencere4d87aa2006-12-23 06:05:41 +00007245 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007246 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007247
Reid Spencere4d87aa2006-12-23 06:05:41 +00007248 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007249 // Not an extension from the same type?
7250 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007251 if (RHSCIOp->getType() != LHSCIOp->getType())
7252 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007253
Nick Lewycky4189a532008-01-28 03:48:02 +00007254 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007255 // and the other is a zext), then we can't handle this.
7256 if (CI->getOpcode() != LHSCI->getOpcode())
7257 return 0;
7258
Nick Lewycky4189a532008-01-28 03:48:02 +00007259 // Deal with equality cases early.
7260 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007261 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007262
7263 // A signed comparison of sign extended values simplifies into a
7264 // signed comparison.
7265 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007266 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007267
7268 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007269 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007270 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007271
Reid Spencere4d87aa2006-12-23 06:05:41 +00007272 // If we aren't dealing with a constant on the RHS, exit early
7273 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7274 if (!CI)
7275 return 0;
7276
7277 // Compute the constant that would happen if we truncated to SrcTy then
7278 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007279 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7280 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007281 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007282
7283 // If the re-extended constant didn't change...
7284 if (Res2 == CI) {
7285 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7286 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007287 // %A = sext i16 %X to i32
7288 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007289 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007290 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007291 // because %A may have negative value.
7292 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007293 // However, we allow this when the compare is EQ/NE, because they are
7294 // signless.
7295 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007296 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007297 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007298 }
7299
7300 // The re-extended constant changed so the constant cannot be represented
7301 // in the shorter type. Consequently, we cannot emit a simple comparison.
7302
7303 // First, handle some easy cases. We know the result cannot be equal at this
7304 // point so handle the ICI.isEquality() cases
7305 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007306 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007307 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007308 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007309
7310 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7311 // should have been folded away previously and not enter in here.
7312 Value *Result;
7313 if (isSignedCmp) {
7314 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007315 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007316 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007317 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007318 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007319 } else {
7320 // We're performing an unsigned comparison.
7321 if (isSignedExt) {
7322 // We're performing an unsigned comp with a sign extended value.
7323 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007324 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007325 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007326 } else {
7327 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007328 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007329 }
7330 }
7331
7332 // Finally, return the value computed.
7333 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007334 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007335 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007336
7337 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7338 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7339 "ICmp should be folded!");
7340 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007341 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007342 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007343}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007344
Reid Spencer832254e2007-02-02 02:16:23 +00007345Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7346 return commonShiftTransforms(I);
7347}
7348
7349Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7350 return commonShiftTransforms(I);
7351}
7352
7353Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007354 if (Instruction *R = commonShiftTransforms(I))
7355 return R;
7356
7357 Value *Op0 = I.getOperand(0);
7358
7359 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7360 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7361 if (CSI->isAllOnesValue())
7362 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007363
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007364 // See if we can turn a signed shr into an unsigned shr.
7365 if (MaskedValueIsZero(Op0,
7366 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7367 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7368
7369 // Arithmetic shifting an all-sign-bit value is a no-op.
7370 unsigned NumSignBits = ComputeNumSignBits(Op0);
7371 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7372 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007373
Chris Lattner348f6652007-12-06 01:59:46 +00007374 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007375}
7376
7377Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7378 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007379 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007380
7381 // shl X, 0 == X and shr X, 0 == X
7382 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007383 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7384 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007385 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007386
Reid Spencere4d87aa2006-12-23 06:05:41 +00007387 if (isa<UndefValue>(Op0)) {
7388 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007389 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007390 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007391 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007392 }
7393 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007394 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7395 return ReplaceInstUsesWith(I, Op0);
7396 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007397 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007398 }
7399
Dan Gohman9004c8a2009-05-21 02:28:33 +00007400 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007401 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007402 return &I;
7403
Chris Lattner2eefe512004-04-09 19:05:30 +00007404 // Try to fold constant and into select arguments.
7405 if (isa<Constant>(Op0))
7406 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007407 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007408 return R;
7409
Reid Spencerb83eb642006-10-20 07:07:24 +00007410 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007411 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7412 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007413 return 0;
7414}
7415
Reid Spencerb83eb642006-10-20 07:07:24 +00007416Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007417 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007418 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007419
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007420 // See if we can simplify any instructions used by the instruction whose sole
7421 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007422 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007423
Dan Gohmana119de82009-06-14 23:30:43 +00007424 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7425 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007426 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007427 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007428 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007429 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007430 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007431 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007432 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007433 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007434 }
7435
7436 // ((X*C1) << C2) == (X * (C1 << C2))
7437 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7438 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7439 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007440 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007441 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007442
7443 // Try to fold constant and into select arguments.
7444 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7445 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7446 return R;
7447 if (isa<PHINode>(Op0))
7448 if (Instruction *NV = FoldOpIntoPhi(I))
7449 return NV;
7450
Chris Lattner8999dd32007-12-22 09:07:47 +00007451 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7452 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7453 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7454 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7455 // place. Don't try to do this transformation in this case. Also, we
7456 // require that the input operand is a shift-by-constant so that we have
7457 // confidence that the shifts will get folded together. We could do this
7458 // xform in more cases, but it is unlikely to be profitable.
7459 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7460 isa<ConstantInt>(TrOp->getOperand(1))) {
7461 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007462 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007463 // (shift2 (shift1 & 0x00FF), c2)
7464 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007465
7466 // For logical shifts, the truncation has the effect of making the high
7467 // part of the register be zeros. Emulate this by inserting an AND to
7468 // clear the top bits as needed. This 'and' will usually be zapped by
7469 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007470 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7471 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007472 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7473
7474 // The mask we constructed says what the trunc would do if occurring
7475 // between the shifts. We want to know the effect *after* the second
7476 // shift. We know that it is a logical shift by a constant, so adjust the
7477 // mask as appropriate.
7478 if (I.getOpcode() == Instruction::Shl)
7479 MaskV <<= Op1->getZExtValue();
7480 else {
7481 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7482 MaskV = MaskV.lshr(Op1->getZExtValue());
7483 }
7484
Chris Lattner74381062009-08-30 07:44:24 +00007485 // shift1 & 0x00FF
7486 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7487 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007488
7489 // Return the value truncated to the interesting size.
7490 return new TruncInst(And, I.getType());
7491 }
7492 }
7493
Chris Lattner4d5542c2006-01-06 07:12:35 +00007494 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007495 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7496 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7497 Value *V1, *V2;
7498 ConstantInt *CC;
7499 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007500 default: break;
7501 case Instruction::Add:
7502 case Instruction::And:
7503 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007504 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007505 // These operators commute.
7506 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007507 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007508 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007509 m_Specific(Op1)))) {
7510 Value *YS = // (Y << C)
7511 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7512 // (X + (Y << C))
7513 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7514 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007515 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007516 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007517 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007518 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007519
Chris Lattner150f12a2005-09-18 06:30:59 +00007520 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007521 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007522 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007523 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007524 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007525 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007526 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007527 Value *YS = // (Y << C)
7528 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7529 Op0BO->getName());
7530 // X & (CC << C)
7531 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7532 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007533 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007534 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007535 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007536
Reid Spencera07cb7d2007-02-02 14:41:37 +00007537 // FALL THROUGH.
7538 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007539 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007540 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007541 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007542 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007543 Value *YS = // (Y << C)
7544 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7545 // (X + (Y << C))
7546 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7547 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007548 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007549 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007550 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007551 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007552
Chris Lattner13d4ab42006-05-31 21:14:00 +00007553 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007554 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7555 match(Op0BO->getOperand(0),
7556 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007557 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007558 cast<BinaryOperator>(Op0BO->getOperand(0))
7559 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007560 Value *YS = // (Y << C)
7561 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7562 // X & (CC << C)
7563 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7564 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007565
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007566 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007567 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007568
Chris Lattner11021cb2005-09-18 05:12:10 +00007569 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007570 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007571 }
7572
7573
7574 // If the operand is an bitwise operator with a constant RHS, and the
7575 // shift is the only use, we can pull it out of the shift.
7576 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7577 bool isValid = true; // Valid only for And, Or, Xor
7578 bool highBitSet = false; // Transform if high bit of constant set?
7579
7580 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007581 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007582 case Instruction::Add:
7583 isValid = isLeftShift;
7584 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007585 case Instruction::Or:
7586 case Instruction::Xor:
7587 highBitSet = false;
7588 break;
7589 case Instruction::And:
7590 highBitSet = true;
7591 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007592 }
7593
7594 // If this is a signed shift right, and the high bit is modified
7595 // by the logical operation, do not perform the transformation.
7596 // The highBitSet boolean indicates the value of the high bit of
7597 // the constant which would cause it to be modified for this
7598 // operation.
7599 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007600 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007601 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007602
7603 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007604 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007605
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007606 Value *NewShift =
7607 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007608 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007609
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007610 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007611 NewRHS);
7612 }
7613 }
7614 }
7615 }
7616
Chris Lattnerad0124c2006-01-06 07:52:12 +00007617 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007618 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7619 if (ShiftOp && !ShiftOp->isShift())
7620 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007621
Reid Spencerb83eb642006-10-20 07:07:24 +00007622 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007623 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007624 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7625 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007626 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7627 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7628 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007629
Zhou Sheng4351c642007-04-02 08:20:41 +00007630 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007631
7632 const IntegerType *Ty = cast<IntegerType>(I.getType());
7633
7634 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007635 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007636 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7637 // saturates.
7638 if (AmtSum >= TypeBits) {
7639 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007640 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007641 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7642 }
7643
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007644 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007645 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007646 }
7647
7648 if (ShiftOp->getOpcode() == Instruction::LShr &&
7649 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007650 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007651 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007652
Chris Lattnerb87056f2007-02-05 00:57:54 +00007653 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007654 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007655 }
7656
7657 if (ShiftOp->getOpcode() == Instruction::AShr &&
7658 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007659 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007660 if (AmtSum >= TypeBits)
7661 AmtSum = TypeBits-1;
7662
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007663 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007664
Zhou Shenge9e03f62007-03-28 15:02:20 +00007665 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007666 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007667 }
7668
Chris Lattnerb87056f2007-02-05 00:57:54 +00007669 // Okay, if we get here, one shift must be left, and the other shift must be
7670 // right. See if the amounts are equal.
7671 if (ShiftAmt1 == ShiftAmt2) {
7672 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7673 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007674 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007675 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007676 }
7677 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7678 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007679 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007680 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007681 }
7682 // We can simplify ((X << C) >>s C) into a trunc + sext.
7683 // NOTE: we could do this for any C, but that would make 'unusual' integer
7684 // types. For now, just stick to ones well-supported by the code
7685 // generators.
7686 const Type *SExtType = 0;
7687 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007688 case 1 :
7689 case 8 :
7690 case 16 :
7691 case 32 :
7692 case 64 :
7693 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007694 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007695 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007696 default: break;
7697 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007698 if (SExtType)
7699 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007700 // Otherwise, we can't handle it yet.
7701 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007702 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007703
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007704 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007705 if (I.getOpcode() == Instruction::Shl) {
7706 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7707 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007708 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007709
Reid Spencer55702aa2007-03-25 21:11:44 +00007710 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007711 return BinaryOperator::CreateAnd(Shift,
7712 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007713 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007714
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007715 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007716 if (I.getOpcode() == Instruction::LShr) {
7717 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007718 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007719
Reid Spencerd5e30f02007-03-26 17:18:58 +00007720 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007721 return BinaryOperator::CreateAnd(Shift,
7722 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007723 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007724
7725 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7726 } else {
7727 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007728 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007729
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007730 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007731 if (I.getOpcode() == Instruction::Shl) {
7732 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7733 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007734 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7735 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007736
Reid Spencer55702aa2007-03-25 21:11:44 +00007737 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007738 return BinaryOperator::CreateAnd(Shift,
7739 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007740 }
7741
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007742 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007743 if (I.getOpcode() == Instruction::LShr) {
7744 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007745 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007746
Reid Spencer68d27cf2007-03-26 23:45:51 +00007747 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007748 return BinaryOperator::CreateAnd(Shift,
7749 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007750 }
7751
7752 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007753 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007754 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007755 return 0;
7756}
7757
Chris Lattnera1be5662002-05-02 17:06:02 +00007758
Chris Lattnercfd65102005-10-29 04:36:15 +00007759/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7760/// expression. If so, decompose it, returning some value X, such that Val is
7761/// X*Scale+Offset.
7762///
7763static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007764 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007765 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7766 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007767 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007768 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007769 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007770 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007771 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7772 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7773 if (I->getOpcode() == Instruction::Shl) {
7774 // This is a value scaled by '1 << the shift amt'.
7775 Scale = 1U << RHS->getZExtValue();
7776 Offset = 0;
7777 return I->getOperand(0);
7778 } else if (I->getOpcode() == Instruction::Mul) {
7779 // This value is scaled by 'RHS'.
7780 Scale = RHS->getZExtValue();
7781 Offset = 0;
7782 return I->getOperand(0);
7783 } else if (I->getOpcode() == Instruction::Add) {
7784 // We have X+C. Check to see if we really have (X*C2)+C1,
7785 // where C1 is divisible by C2.
7786 unsigned SubScale;
7787 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007788 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7789 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007790 Offset += RHS->getZExtValue();
7791 Scale = SubScale;
7792 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007793 }
7794 }
7795 }
7796
7797 // Otherwise, we can't look past this.
7798 Scale = 1;
7799 Offset = 0;
7800 return Val;
7801}
7802
7803
Chris Lattnerb3f83972005-10-24 06:03:58 +00007804/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7805/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007806Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00007807 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007808 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007809
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007810 BuilderTy AllocaBuilder(*Builder);
7811 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7812
Chris Lattnerb53c2382005-10-24 06:22:12 +00007813 // Remove any uses of AI that are dead.
7814 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007815
Chris Lattnerb53c2382005-10-24 06:22:12 +00007816 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7817 Instruction *User = cast<Instruction>(*UI++);
7818 if (isInstructionTriviallyDead(User)) {
7819 while (UI != E && *UI == User)
7820 ++UI; // If this instruction uses AI more than once, don't break UI.
7821
Chris Lattnerb53c2382005-10-24 06:22:12 +00007822 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007823 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007824 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007825 }
7826 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007827
7828 // This requires TargetData to get the alloca alignment and size information.
7829 if (!TD) return 0;
7830
Chris Lattnerb3f83972005-10-24 06:03:58 +00007831 // Get the type really allocated and the type casted to.
7832 const Type *AllocElTy = AI.getAllocatedType();
7833 const Type *CastElTy = PTy->getElementType();
7834 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007835
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007836 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7837 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007838 if (CastElTyAlign < AllocElTyAlign) return 0;
7839
Chris Lattner39387a52005-10-24 06:35:18 +00007840 // If the allocation has multiple uses, only promote it if we are strictly
7841 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007842 // same, we open the door to infinite loops of various kinds. (A reference
7843 // from a dbg.declare doesn't count as a use for this purpose.)
7844 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7845 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007846
Duncan Sands777d2302009-05-09 07:06:46 +00007847 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7848 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007849 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007850
Chris Lattner455fcc82005-10-29 03:19:53 +00007851 // See if we can satisfy the modulus by pulling a scale out of the array
7852 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007853 unsigned ArraySizeScale;
7854 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007855 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007856 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7857 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007858
Chris Lattner455fcc82005-10-29 03:19:53 +00007859 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7860 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007861 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7862 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007863
Chris Lattner455fcc82005-10-29 03:19:53 +00007864 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7865 Value *Amt = 0;
7866 if (Scale == 1) {
7867 Amt = NumElements;
7868 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007869 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007870 // Insert before the alloca, not before the cast.
7871 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007872 }
7873
Jeff Cohen86796be2007-04-04 16:58:57 +00007874 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007875 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007876 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007877 }
7878
Victor Hernandez7b929da2009-10-23 21:09:37 +00007879 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007880 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007881 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007882
Dale Johannesena0a66372009-03-05 00:39:02 +00007883 // If the allocation has one real use plus a dbg.declare, just remove the
7884 // declare.
7885 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7886 EraseInstFromFunction(*DI);
7887 }
7888 // If the allocation has multiple real uses, insert a cast and change all
7889 // things that used it to use the new cast. This will also hack on CI, but it
7890 // will die soon.
7891 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007892 // New is the allocation instruction, pointer typed. AI is the original
7893 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007894 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007895 AI.replaceAllUsesWith(NewCast);
7896 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007897 return ReplaceInstUsesWith(CI, New);
7898}
7899
Chris Lattner70074e02006-05-13 02:06:03 +00007900/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007901/// and return it as type Ty without inserting any new casts and without
7902/// changing the computed value. This is used by code that tries to decide
7903/// whether promoting or shrinking integer operations to wider or smaller types
7904/// will allow us to eliminate a truncate or extend.
7905///
7906/// This is a truncation operation if Ty is smaller than V->getType(), or an
7907/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007908///
7909/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7910/// should return true if trunc(V) can be computed by computing V in the smaller
7911/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7912/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7913/// efficiently truncated.
7914///
7915/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7916/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7917/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007918bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007919 unsigned CastOpc,
7920 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007921 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007922 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007923 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007924
7925 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007926 if (!I) return false;
7927
Dan Gohman6de29f82009-06-15 22:12:54 +00007928 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007929
Chris Lattner951626b2007-08-02 06:11:14 +00007930 // If this is an extension or truncate, we can often eliminate it.
7931 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7932 // If this is a cast from the destination type, we can trivially eliminate
7933 // it, and this will remove a cast overall.
7934 if (I->getOperand(0)->getType() == Ty) {
7935 // If the first operand is itself a cast, and is eliminable, do not count
7936 // this as an eliminable cast. We would prefer to eliminate those two
7937 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007938 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007939 ++NumCastsRemoved;
7940 return true;
7941 }
7942 }
7943
7944 // We can't extend or shrink something that has multiple uses: doing so would
7945 // require duplicating the instruction in general, which isn't profitable.
7946 if (!I->hasOneUse()) return false;
7947
Evan Chengf35fd542009-01-15 17:01:23 +00007948 unsigned Opc = I->getOpcode();
7949 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007950 case Instruction::Add:
7951 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007952 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007953 case Instruction::And:
7954 case Instruction::Or:
7955 case Instruction::Xor:
7956 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007957 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007958 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007959 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007960 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007961
Eli Friedman070a9812009-07-13 22:46:01 +00007962 case Instruction::UDiv:
7963 case Instruction::URem: {
7964 // UDiv and URem can be truncated if all the truncated bits are zero.
7965 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7966 uint32_t BitWidth = Ty->getScalarSizeInBits();
7967 if (BitWidth < OrigBitWidth) {
7968 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7969 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7970 MaskedValueIsZero(I->getOperand(1), Mask)) {
7971 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7972 NumCastsRemoved) &&
7973 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7974 NumCastsRemoved);
7975 }
7976 }
7977 break;
7978 }
Chris Lattner46b96052006-11-29 07:18:39 +00007979 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007980 // If we are truncating the result of this SHL, and if it's a shift of a
7981 // constant amount, we can always perform a SHL in a smaller type.
7982 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007983 uint32_t BitWidth = Ty->getScalarSizeInBits();
7984 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007985 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007986 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007987 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007988 }
7989 break;
7990 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007991 // If this is a truncate of a logical shr, we can truncate it to a smaller
7992 // lshr iff we know that the bits we would otherwise be shifting in are
7993 // already zeros.
7994 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007995 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7996 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007997 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007998 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007999 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8000 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008001 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008002 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008003 }
8004 }
Chris Lattner46b96052006-11-29 07:18:39 +00008005 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008006 case Instruction::ZExt:
8007 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008008 case Instruction::Trunc:
8009 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008010 // can safely replace it. Note that replacing it does not reduce the number
8011 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008012 if (Opc == CastOpc)
8013 return true;
8014
8015 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008016 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008017 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008018 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008019 case Instruction::Select: {
8020 SelectInst *SI = cast<SelectInst>(I);
8021 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008022 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008023 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008024 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008025 }
Chris Lattner8114b712008-06-18 04:00:49 +00008026 case Instruction::PHI: {
8027 // We can change a phi if we can change all operands.
8028 PHINode *PN = cast<PHINode>(I);
8029 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8030 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008031 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008032 return false;
8033 return true;
8034 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008035 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008036 // TODO: Can handle more cases here.
8037 break;
8038 }
8039
8040 return false;
8041}
8042
8043/// EvaluateInDifferentType - Given an expression that
8044/// CanEvaluateInDifferentType returns true for, actually insert the code to
8045/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008046Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008047 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008048 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00008049 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008050
8051 // Otherwise, it must be an instruction.
8052 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008053 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008054 unsigned Opc = I->getOpcode();
8055 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008056 case Instruction::Add:
8057 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008058 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008059 case Instruction::And:
8060 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008061 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008062 case Instruction::AShr:
8063 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008064 case Instruction::Shl:
8065 case Instruction::UDiv:
8066 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008067 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008068 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008069 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008070 break;
8071 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008072 case Instruction::Trunc:
8073 case Instruction::ZExt:
8074 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008075 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008076 // just return the source. There's no need to insert it because it is not
8077 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008078 if (I->getOperand(0)->getType() == Ty)
8079 return I->getOperand(0);
8080
Chris Lattner8114b712008-06-18 04:00:49 +00008081 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00008082 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008083 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008084 case Instruction::Select: {
8085 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8086 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8087 Res = SelectInst::Create(I->getOperand(0), True, False);
8088 break;
8089 }
Chris Lattner8114b712008-06-18 04:00:49 +00008090 case Instruction::PHI: {
8091 PHINode *OPN = cast<PHINode>(I);
8092 PHINode *NPN = PHINode::Create(Ty);
8093 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8094 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8095 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8096 }
8097 Res = NPN;
8098 break;
8099 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008100 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008101 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008102 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008103 break;
8104 }
8105
Chris Lattner8114b712008-06-18 04:00:49 +00008106 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008107 return InsertNewInstBefore(Res, *I);
8108}
8109
Reid Spencer3da59db2006-11-27 01:05:10 +00008110/// @brief Implement the transforms common to all CastInst visitors.
8111Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008112 Value *Src = CI.getOperand(0);
8113
Dan Gohman23d9d272007-05-11 21:10:54 +00008114 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008115 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008116 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008117 if (Instruction::CastOps opc =
8118 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8119 // The first cast (CSrc) is eliminable so we need to fix up or replace
8120 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008121 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008122 }
8123 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008124
Reid Spencer3da59db2006-11-27 01:05:10 +00008125 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008126 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8127 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8128 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008129
8130 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00008131 if (isa<PHINode>(Src)) {
8132 // We don't do this if this would create a PHI node with an illegal type if
8133 // it is currently legal.
8134 if (!isa<IntegerType>(Src->getType()) ||
8135 !isa<IntegerType>(CI.getType()) ||
8136 (TD && TD->isLegalInteger(CI.getType()->getPrimitiveSizeInBits())) ||
8137 (TD && !TD->isLegalInteger(Src->getType()->getPrimitiveSizeInBits())))
8138 if (Instruction *NV = FoldOpIntoPhi(CI))
8139 return NV;
8140
8141 }
Chris Lattner9fb92132006-04-12 18:09:35 +00008142
Reid Spencer3da59db2006-11-27 01:05:10 +00008143 return 0;
8144}
8145
Chris Lattner46cd5a12009-01-09 05:44:56 +00008146/// FindElementAtOffset - Given a type and a constant offset, determine whether
8147/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008148/// the specified offset. If so, fill them into NewIndices and return the
8149/// resultant element type, otherwise return null.
8150static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8151 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008152 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008153 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008154 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008155 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008156
8157 // Start with the index over the outer type. Note that the type size
8158 // might be zero (even if the offset isn't zero) if the indexed type
8159 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008160 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008161 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008162 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008163 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008164 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008165
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008166 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008167 if (Offset < 0) {
8168 --FirstIdx;
8169 Offset += TySize;
8170 assert(Offset >= 0);
8171 }
8172 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8173 }
8174
Owen Andersoneed707b2009-07-24 23:12:02 +00008175 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008176
8177 // Index into the types. If we fail, set OrigBase to null.
8178 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008179 // Indexing into tail padding between struct/array elements.
8180 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008181 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008182
Chris Lattner46cd5a12009-01-09 05:44:56 +00008183 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8184 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008185 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8186 "Offset must stay within the indexed type");
8187
Chris Lattner46cd5a12009-01-09 05:44:56 +00008188 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008189 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008190
8191 Offset -= SL->getElementOffset(Elt);
8192 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008193 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008194 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008195 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008196 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008197 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008198 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008199 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008200 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008201 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008202 }
8203 }
8204
Chris Lattner3914f722009-01-24 01:00:13 +00008205 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008206}
8207
Chris Lattnerd3e28342007-04-27 17:44:50 +00008208/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8209Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8210 Value *Src = CI.getOperand(0);
8211
Chris Lattnerd3e28342007-04-27 17:44:50 +00008212 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008213 // If casting the result of a getelementptr instruction with no offset, turn
8214 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008215 if (GEP->hasAllZeroIndices()) {
8216 // Changing the cast operand is usually not a good idea but it is safe
8217 // here because the pointer operand is being replaced with another
8218 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008219 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008220 CI.setOperand(0, GEP->getOperand(0));
8221 return &CI;
8222 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008223
8224 // If the GEP has a single use, and the base pointer is a bitcast, and the
8225 // GEP computes a constant offset, see if we can convert these three
8226 // instructions into fewer. This typically happens with unions and other
8227 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008228 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008229 if (GEP->hasAllConstantIndices()) {
8230 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008231 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008232 int64_t Offset = OffsetV->getSExtValue();
8233
8234 // Get the base pointer input of the bitcast, and the type it points to.
8235 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8236 const Type *GEPIdxTy =
8237 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008238 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008239 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008240 // If we were able to index down into an element, create the GEP
8241 // and bitcast the result. This eliminates one bitcast, potentially
8242 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008243 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8244 Builder->CreateInBoundsGEP(OrigBase,
8245 NewIndices.begin(), NewIndices.end()) :
8246 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008247 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008248
Chris Lattner46cd5a12009-01-09 05:44:56 +00008249 if (isa<BitCastInst>(CI))
8250 return new BitCastInst(NGEP, CI.getType());
8251 assert(isa<PtrToIntInst>(CI));
8252 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008253 }
8254 }
8255 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008256 }
8257
8258 return commonCastTransforms(CI);
8259}
8260
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008261/// commonIntCastTransforms - This function implements the common transforms
8262/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008263Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8264 if (Instruction *Result = commonCastTransforms(CI))
8265 return Result;
8266
8267 Value *Src = CI.getOperand(0);
8268 const Type *SrcTy = Src->getType();
8269 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008270 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8271 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008272
Reid Spencer3da59db2006-11-27 01:05:10 +00008273 // See if we can simplify any instructions used by the LHS whose sole
8274 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008275 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008276 return &CI;
8277
8278 // If the source isn't an instruction or has more than one use then we
8279 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008280 Instruction *SrcI = dyn_cast<Instruction>(Src);
8281 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008282 return 0;
8283
Chris Lattnerc739cd62007-03-03 05:27:34 +00008284 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008285 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008286 // Only do this if the dest type is a simple type, don't convert the
8287 // expression tree to something weird like i93 unless the source is also
8288 // strange.
Chris Lattner918871e2009-11-07 19:11:46 +00008289 if (TD &&
8290 (TD->isLegalInteger(DestTy->getScalarType()->getPrimitiveSizeInBits()) ||
8291 !TD->isLegalInteger((SrcI->getType()->getScalarType()
8292 ->getPrimitiveSizeInBits()))) &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008293 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008294 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008295 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008296 // eliminates the cast, so it is always a win. If this is a zero-extension,
8297 // we need to do an AND to maintain the clear top-part of the computation,
8298 // so we require that the input have eliminated at least one cast. If this
8299 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008300 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008301 bool DoXForm = false;
8302 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008303 switch (CI.getOpcode()) {
8304 default:
8305 // All the others use floating point so we shouldn't actually
8306 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008307 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008308 case Instruction::Trunc:
8309 DoXForm = true;
8310 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008311 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008312 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00008313
Chris Lattner39c27ed2009-01-31 19:05:27 +00008314 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008315 // If it's unnecessary to issue an AND to clear the high bits, it's
8316 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008317 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008318 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8319 if (MaskedValueIsZero(TryRes, Mask))
8320 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008321
8322 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008323 if (TryI->use_empty())
8324 EraseInstFromFunction(*TryI);
8325 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008326 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008327 }
Evan Chengf35fd542009-01-15 17:01:23 +00008328 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008329 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008330 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008331 // If we do not have to emit the truncate + sext pair, then it's always
8332 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008333 //
8334 // It's not safe to eliminate the trunc + sext pair if one of the
8335 // eliminated cast is a truncate. e.g.
8336 // t2 = trunc i32 t1 to i16
8337 // t3 = sext i16 t2 to i32
8338 // !=
8339 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008340 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008341 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8342 if (NumSignBits > (DestBitSize - SrcBitSize))
8343 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008344
8345 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008346 if (TryI->use_empty())
8347 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008348 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008349 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008350 }
Evan Chengf35fd542009-01-15 17:01:23 +00008351 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008352
8353 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008354 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8355 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008356 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8357 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008358 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008359 // Just replace this cast with the result.
8360 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008361
Reid Spencer3da59db2006-11-27 01:05:10 +00008362 assert(Res->getType() == DestTy);
8363 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008364 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008365 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008366 // Just replace this cast with the result.
8367 return ReplaceInstUsesWith(CI, Res);
8368 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008369 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008370
8371 // If the high bits are already zero, just replace this cast with the
8372 // result.
8373 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8374 if (MaskedValueIsZero(Res, Mask))
8375 return ReplaceInstUsesWith(CI, Res);
8376
8377 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008378 Constant *C = ConstantInt::get(*Context,
8379 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008380 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008381 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008382 case Instruction::SExt: {
8383 // If the high bits are already filled with sign bit, just replace this
8384 // cast with the result.
8385 unsigned NumSignBits = ComputeNumSignBits(Res);
8386 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008387 return ReplaceInstUsesWith(CI, Res);
8388
Reid Spencer3da59db2006-11-27 01:05:10 +00008389 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008390 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008391 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008392 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008393 }
8394 }
8395
8396 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8397 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8398
8399 switch (SrcI->getOpcode()) {
8400 case Instruction::Add:
8401 case Instruction::Mul:
8402 case Instruction::And:
8403 case Instruction::Or:
8404 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008405 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008406 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8407 // Don't insert two casts unless at least one can be eliminated.
8408 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008409 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008410 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8411 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008412 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008413 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008414 }
8415 }
8416
8417 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8418 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8419 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008420 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008421 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008422 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008423 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008424 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008425 }
8426 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008427
Eli Friedman65445c52009-07-13 21:45:57 +00008428 case Instruction::Shl: {
8429 // Canonicalize trunc inside shl, if we can.
8430 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8431 if (CI && DestBitSize < SrcBitSize &&
8432 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008433 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8434 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008435 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008436 }
8437 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008438 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008439 }
8440 return 0;
8441}
8442
Chris Lattner8a9f5712007-04-11 06:57:46 +00008443Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008444 if (Instruction *Result = commonIntCastTransforms(CI))
8445 return Result;
8446
8447 Value *Src = CI.getOperand(0);
8448 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008449 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8450 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008451
8452 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008453 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008454 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008455 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008456 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008457 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008458 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008459
Chris Lattner4f9797d2009-03-24 18:15:30 +00008460 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8461 ConstantInt *ShAmtV = 0;
8462 Value *ShiftOp = 0;
8463 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008464 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008465 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8466
8467 // Get a mask for the bits shifting in.
8468 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8469 if (MaskedValueIsZero(ShiftOp, Mask)) {
8470 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008471 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008472
8473 // Okay, we can shrink this. Truncate the input, then return a new
8474 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008475 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008476 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008477 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008478 }
8479 }
Chris Lattner9956c052009-11-08 19:23:30 +00008480
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008481 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008482}
8483
Evan Chengb98a10e2008-03-24 00:21:34 +00008484/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8485/// in order to eliminate the icmp.
8486Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8487 bool DoXform) {
8488 // If we are just checking for a icmp eq of a single bit and zext'ing it
8489 // to an integer, then shift the bit to the appropriate place and then
8490 // cast to integer to avoid the comparison.
8491 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8492 const APInt &Op1CV = Op1C->getValue();
8493
8494 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8495 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8496 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8497 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8498 if (!DoXform) return ICI;
8499
8500 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008501 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008502 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008503 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008504 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008505 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008506
8507 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008508 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008509 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008510 }
8511
8512 return ReplaceInstUsesWith(CI, In);
8513 }
8514
8515
8516
8517 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8518 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8519 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8520 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8521 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8522 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8523 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8524 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8525 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8526 // This only works for EQ and NE
8527 ICI->isEquality()) {
8528 // If Op1C some other power of two, convert:
8529 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8530 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8531 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8532 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8533
8534 APInt KnownZeroMask(~KnownZero);
8535 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8536 if (!DoXform) return ICI;
8537
8538 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8539 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8540 // (X&4) == 2 --> false
8541 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008542 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008543 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008544 return ReplaceInstUsesWith(CI, Res);
8545 }
8546
8547 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8548 Value *In = ICI->getOperand(0);
8549 if (ShiftAmt) {
8550 // Perform a logical shr by shiftamt.
8551 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008552 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8553 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008554 }
8555
8556 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008557 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008558 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008559 }
8560
8561 if (CI.getType() == In->getType())
8562 return ReplaceInstUsesWith(CI, In);
8563 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008564 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008565 }
8566 }
8567 }
8568
8569 return 0;
8570}
8571
Chris Lattner8a9f5712007-04-11 06:57:46 +00008572Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008573 // If one of the common conversion will work ..
8574 if (Instruction *Result = commonIntCastTransforms(CI))
8575 return Result;
8576
8577 Value *Src = CI.getOperand(0);
8578
Chris Lattnera84f47c2009-02-17 20:47:23 +00008579 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8580 // types and if the sizes are just right we can convert this into a logical
8581 // 'and' which will be much cheaper than the pair of casts.
8582 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8583 // Get the sizes of the types involved. We know that the intermediate type
8584 // will be smaller than A or C, but don't know the relation between A and C.
8585 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008586 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8587 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8588 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008589 // If we're actually extending zero bits, then if
8590 // SrcSize < DstSize: zext(a & mask)
8591 // SrcSize == DstSize: a & mask
8592 // SrcSize > DstSize: trunc(a) & mask
8593 if (SrcSize < DstSize) {
8594 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008595 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008596 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008597 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008598 }
8599
8600 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008601 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008602 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008603 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008604 }
8605 if (SrcSize > DstSize) {
8606 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008607 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008608 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008609 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008610 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008611 }
8612 }
8613
Evan Chengb98a10e2008-03-24 00:21:34 +00008614 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8615 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008616
Evan Chengb98a10e2008-03-24 00:21:34 +00008617 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8618 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8619 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8620 // of the (zext icmp) will be transformed.
8621 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8622 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8623 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8624 (transformZExtICmp(LHS, CI, false) ||
8625 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008626 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8627 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008628 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008629 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008630 }
8631
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008632 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008633 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8634 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8635 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8636 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008637 if (TI0->getType() == CI.getType())
8638 return
8639 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008640 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008641 }
8642
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008643 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8644 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8645 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8646 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8647 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8648 And->getOperand(1) == C)
8649 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8650 Value *TI0 = TI->getOperand(0);
8651 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008652 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008653 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008654 return BinaryOperator::CreateXor(NewAnd, ZC);
8655 }
8656 }
8657
Reid Spencer3da59db2006-11-27 01:05:10 +00008658 return 0;
8659}
8660
Chris Lattner8a9f5712007-04-11 06:57:46 +00008661Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008662 if (Instruction *I = commonIntCastTransforms(CI))
8663 return I;
8664
Chris Lattner8a9f5712007-04-11 06:57:46 +00008665 Value *Src = CI.getOperand(0);
8666
Dan Gohman1975d032008-10-30 20:40:10 +00008667 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008668 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008669 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008670 Constant::getAllOnesValue(CI.getType()),
8671 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008672
8673 // See if the value being truncated is already sign extended. If so, just
8674 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008675 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008676 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008677 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8678 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8679 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008680 unsigned NumSignBits = ComputeNumSignBits(Op);
8681
8682 if (OpBits == DestBits) {
8683 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8684 // bits, it is already ready.
8685 if (NumSignBits > DestBits-MidBits)
8686 return ReplaceInstUsesWith(CI, Op);
8687 } else if (OpBits < DestBits) {
8688 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8689 // bits, just sext from i32.
8690 if (NumSignBits > OpBits-MidBits)
8691 return new SExtInst(Op, CI.getType(), "tmp");
8692 } else {
8693 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8694 // bits, just truncate to i32.
8695 if (NumSignBits > OpBits-MidBits)
8696 return new TruncInst(Op, CI.getType(), "tmp");
8697 }
8698 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008699
8700 // If the input is a shl/ashr pair of a same constant, then this is a sign
8701 // extension from a smaller value. If we could trust arbitrary bitwidth
8702 // integers, we could turn this into a truncate to the smaller bit and then
8703 // use a sext for the whole extension. Since we don't, look deeper and check
8704 // for a truncate. If the source and dest are the same type, eliminate the
8705 // trunc and extend and just do shifts. For example, turn:
8706 // %a = trunc i32 %i to i8
8707 // %b = shl i8 %a, 6
8708 // %c = ashr i8 %b, 6
8709 // %d = sext i8 %c to i32
8710 // into:
8711 // %a = shl i32 %i, 30
8712 // %d = ashr i32 %a, 30
8713 Value *A = 0;
8714 ConstantInt *BA = 0, *CA = 0;
8715 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008716 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008717 BA == CA && isa<TruncInst>(A)) {
8718 Value *I = cast<TruncInst>(A)->getOperand(0);
8719 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008720 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8721 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008722 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008723 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008724 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008725 return BinaryOperator::CreateAShr(I, ShAmtV);
8726 }
8727 }
8728
Chris Lattnerba417832007-04-11 06:12:58 +00008729 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008730}
8731
Chris Lattnerb7530652008-01-27 05:29:54 +00008732/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8733/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008734static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008735 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008736 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008737 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008738 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8739 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008740 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008741 return 0;
8742}
8743
8744/// LookThroughFPExtensions - If this is an fp extension instruction, look
8745/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008746static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008747 if (Instruction *I = dyn_cast<Instruction>(V))
8748 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008749 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008750
8751 // If this value is a constant, return the constant in the smallest FP type
8752 // that can accurately represent it. This allows us to turn
8753 // (float)((double)X+2.0) into x+2.0f.
8754 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008755 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008756 return V; // No constant folding of this.
8757 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008758 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008759 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008760 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008761 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008762 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008763 return V;
8764 // Don't try to shrink to various long double types.
8765 }
8766
8767 return V;
8768}
8769
8770Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8771 if (Instruction *I = commonCastTransforms(CI))
8772 return I;
8773
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008774 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008775 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008776 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008777 // many builtins (sqrt, etc).
8778 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8779 if (OpI && OpI->hasOneUse()) {
8780 switch (OpI->getOpcode()) {
8781 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008782 case Instruction::FAdd:
8783 case Instruction::FSub:
8784 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008785 case Instruction::FDiv:
8786 case Instruction::FRem:
8787 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008788 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8789 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008790 if (LHSTrunc->getType() != SrcTy &&
8791 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008792 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008793 // If the source types were both smaller than the destination type of
8794 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008795 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8796 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008797 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8798 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008799 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008800 }
8801 }
8802 break;
8803 }
8804 }
8805 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008806}
8807
8808Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8809 return commonCastTransforms(CI);
8810}
8811
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008812Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008813 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8814 if (OpI == 0)
8815 return commonCastTransforms(FI);
8816
8817 // fptoui(uitofp(X)) --> X
8818 // fptoui(sitofp(X)) --> X
8819 // This is safe if the intermediate type has enough bits in its mantissa to
8820 // accurately represent all values of X. For example, do not do this with
8821 // i64->float->i64. This is also safe for sitofp case, because any negative
8822 // 'X' value would cause an undefined result for the fptoui.
8823 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8824 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008825 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008826 OpI->getType()->getFPMantissaWidth())
8827 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008828
8829 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008830}
8831
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008832Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008833 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8834 if (OpI == 0)
8835 return commonCastTransforms(FI);
8836
8837 // fptosi(sitofp(X)) --> X
8838 // fptosi(uitofp(X)) --> X
8839 // This is safe if the intermediate type has enough bits in its mantissa to
8840 // accurately represent all values of X. For example, do not do this with
8841 // i64->float->i64. This is also safe for sitofp case, because any negative
8842 // 'X' value would cause an undefined result for the fptoui.
8843 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8844 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008845 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008846 OpI->getType()->getFPMantissaWidth())
8847 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008848
8849 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008850}
8851
8852Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8853 return commonCastTransforms(CI);
8854}
8855
8856Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8857 return commonCastTransforms(CI);
8858}
8859
Chris Lattnera0e69692009-03-24 18:35:40 +00008860Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8861 // If the destination integer type is smaller than the intptr_t type for
8862 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8863 // trunc to be exposed to other transforms. Don't do this for extending
8864 // ptrtoint's, because we don't know if the target sign or zero extends its
8865 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008866 if (TD &&
8867 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008868 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8869 TD->getIntPtrType(CI.getContext()),
8870 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008871 return new TruncInst(P, CI.getType());
8872 }
8873
Chris Lattnerd3e28342007-04-27 17:44:50 +00008874 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008875}
8876
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008877Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008878 // If the source integer type is larger than the intptr_t type for
8879 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8880 // allows the trunc to be exposed to other transforms. Don't do this for
8881 // extending inttoptr's, because we don't know if the target sign or zero
8882 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008883 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008884 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008885 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8886 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008887 return new IntToPtrInst(P, CI.getType());
8888 }
8889
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008890 if (Instruction *I = commonCastTransforms(CI))
8891 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008892
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008893 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008894}
8895
Chris Lattnerd3e28342007-04-27 17:44:50 +00008896Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008897 // If the operands are integer typed then apply the integer transforms,
8898 // otherwise just apply the common ones.
8899 Value *Src = CI.getOperand(0);
8900 const Type *SrcTy = Src->getType();
8901 const Type *DestTy = CI.getType();
8902
Eli Friedman7e25d452009-07-13 20:53:00 +00008903 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008904 if (Instruction *I = commonPointerCastTransforms(CI))
8905 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008906 } else {
8907 if (Instruction *Result = commonCastTransforms(CI))
8908 return Result;
8909 }
8910
8911
8912 // Get rid of casts from one type to the same type. These are useless and can
8913 // be replaced by the operand.
8914 if (DestTy == Src->getType())
8915 return ReplaceInstUsesWith(CI, Src);
8916
Reid Spencer3da59db2006-11-27 01:05:10 +00008917 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008918 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8919 const Type *DstElTy = DstPTy->getElementType();
8920 const Type *SrcElTy = SrcPTy->getElementType();
8921
Nate Begeman83ad90a2008-03-31 00:22:16 +00008922 // If the address spaces don't match, don't eliminate the bitcast, which is
8923 // required for changing types.
8924 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8925 return 0;
8926
Victor Hernandez83d63912009-09-18 22:35:49 +00008927 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008928 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008929 // There is no need to modify malloc calls because it is their bitcast that
8930 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00008931 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00008932 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8933 return V;
8934
Chris Lattnerd717c182007-05-05 22:32:24 +00008935 // If the source and destination are pointers, and this cast is equivalent
8936 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008937 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008938 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008939 unsigned NumZeros = 0;
8940 while (SrcElTy != DstElTy &&
8941 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8942 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8943 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8944 ++NumZeros;
8945 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008946
Chris Lattnerd3e28342007-04-27 17:44:50 +00008947 // If we found a path from the src to dest, create the getelementptr now.
8948 if (SrcElTy == DstElTy) {
8949 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008950 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8951 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008952 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008953 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008954
Eli Friedman2451a642009-07-18 23:06:53 +00008955 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8956 if (DestVTy->getNumElements() == 1) {
8957 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008958 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008959 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008960 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008961 }
8962 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8963 }
8964 }
8965
8966 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8967 if (SrcVTy->getNumElements() == 1) {
8968 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008969 Value *Elem =
8970 Builder->CreateExtractElement(Src,
8971 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008972 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8973 }
8974 }
8975 }
8976
Reid Spencer3da59db2006-11-27 01:05:10 +00008977 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8978 if (SVI->hasOneUse()) {
8979 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8980 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008981 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008982 cast<VectorType>(DestTy)->getNumElements() ==
8983 SVI->getType()->getNumElements() &&
8984 SVI->getType()->getNumElements() ==
8985 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008986 CastInst *Tmp;
8987 // If either of the operands is a cast from CI.getType(), then
8988 // evaluating the shuffle in the casted destination's type will allow
8989 // us to eliminate at least one cast.
8990 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8991 Tmp->getOperand(0)->getType() == DestTy) ||
8992 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8993 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008994 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8995 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008996 // Return a new shuffle vector. Use the same element ID's, as we
8997 // know the vector types match #elts.
8998 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008999 }
9000 }
9001 }
9002 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009003 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009004}
9005
Chris Lattnere576b912004-04-09 23:46:01 +00009006/// GetSelectFoldableOperands - We want to turn code that looks like this:
9007/// %C = or %A, %B
9008/// %D = select %cond, %C, %A
9009/// into:
9010/// %C = select %cond, %B, 0
9011/// %D = or %A, %C
9012///
9013/// Assuming that the specified instruction is an operand to the select, return
9014/// a bitmask indicating which operands of this instruction are foldable if they
9015/// equal the other incoming value of the select.
9016///
9017static unsigned GetSelectFoldableOperands(Instruction *I) {
9018 switch (I->getOpcode()) {
9019 case Instruction::Add:
9020 case Instruction::Mul:
9021 case Instruction::And:
9022 case Instruction::Or:
9023 case Instruction::Xor:
9024 return 3; // Can fold through either operand.
9025 case Instruction::Sub: // Can only fold on the amount subtracted.
9026 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009027 case Instruction::LShr:
9028 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009029 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009030 default:
9031 return 0; // Cannot fold
9032 }
9033}
9034
9035/// GetSelectFoldableConstant - For the same transformation as the previous
9036/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009037static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009038 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009039 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009040 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009041 case Instruction::Add:
9042 case Instruction::Sub:
9043 case Instruction::Or:
9044 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009045 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009046 case Instruction::LShr:
9047 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009048 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009049 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009050 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009051 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009052 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009053 }
9054}
9055
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009056/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9057/// have the same opcode and only one use each. Try to simplify this.
9058Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9059 Instruction *FI) {
9060 if (TI->getNumOperands() == 1) {
9061 // If this is a non-volatile load or a cast from the same type,
9062 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009063 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009064 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9065 return 0;
9066 } else {
9067 return 0; // unknown unary op.
9068 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009069
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009070 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009071 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009072 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009073 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009074 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009075 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009076 }
9077
Reid Spencer832254e2007-02-02 02:16:23 +00009078 // Only handle binary operators here.
9079 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009080 return 0;
9081
9082 // Figure out if the operations have any operands in common.
9083 Value *MatchOp, *OtherOpT, *OtherOpF;
9084 bool MatchIsOpZero;
9085 if (TI->getOperand(0) == FI->getOperand(0)) {
9086 MatchOp = TI->getOperand(0);
9087 OtherOpT = TI->getOperand(1);
9088 OtherOpF = FI->getOperand(1);
9089 MatchIsOpZero = true;
9090 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9091 MatchOp = TI->getOperand(1);
9092 OtherOpT = TI->getOperand(0);
9093 OtherOpF = FI->getOperand(0);
9094 MatchIsOpZero = false;
9095 } else if (!TI->isCommutative()) {
9096 return 0;
9097 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9098 MatchOp = TI->getOperand(0);
9099 OtherOpT = TI->getOperand(1);
9100 OtherOpF = FI->getOperand(0);
9101 MatchIsOpZero = true;
9102 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9103 MatchOp = TI->getOperand(1);
9104 OtherOpT = TI->getOperand(0);
9105 OtherOpF = FI->getOperand(1);
9106 MatchIsOpZero = true;
9107 } else {
9108 return 0;
9109 }
9110
9111 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009112 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9113 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009114 InsertNewInstBefore(NewSI, SI);
9115
9116 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9117 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009118 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009119 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009120 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009121 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009122 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009123 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009124}
9125
Evan Chengde621922009-03-31 20:42:45 +00009126static bool isSelect01(Constant *C1, Constant *C2) {
9127 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9128 if (!C1I)
9129 return false;
9130 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9131 if (!C2I)
9132 return false;
9133 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9134}
9135
9136/// FoldSelectIntoOp - Try fold the select into one of the operands to
9137/// facilitate further optimization.
9138Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9139 Value *FalseVal) {
9140 // See the comment above GetSelectFoldableOperands for a description of the
9141 // transformation we are doing here.
9142 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9143 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9144 !isa<Constant>(FalseVal)) {
9145 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9146 unsigned OpToFold = 0;
9147 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9148 OpToFold = 1;
9149 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9150 OpToFold = 2;
9151 }
9152
9153 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009154 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009155 Value *OOp = TVI->getOperand(2-OpToFold);
9156 // Avoid creating select between 2 constants unless it's selecting
9157 // between 0 and 1.
9158 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9159 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9160 InsertNewInstBefore(NewSel, SI);
9161 NewSel->takeName(TVI);
9162 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9163 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009164 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009165 }
9166 }
9167 }
9168 }
9169 }
9170
9171 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9172 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9173 !isa<Constant>(TrueVal)) {
9174 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9175 unsigned OpToFold = 0;
9176 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9177 OpToFold = 1;
9178 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9179 OpToFold = 2;
9180 }
9181
9182 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009183 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009184 Value *OOp = FVI->getOperand(2-OpToFold);
9185 // Avoid creating select between 2 constants unless it's selecting
9186 // between 0 and 1.
9187 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9188 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9189 InsertNewInstBefore(NewSel, SI);
9190 NewSel->takeName(FVI);
9191 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9192 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009193 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009194 }
9195 }
9196 }
9197 }
9198 }
9199
9200 return 0;
9201}
9202
Dan Gohman81b28ce2008-09-16 18:46:06 +00009203/// visitSelectInstWithICmp - Visit a SelectInst that has an
9204/// ICmpInst as its first operand.
9205///
9206Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9207 ICmpInst *ICI) {
9208 bool Changed = false;
9209 ICmpInst::Predicate Pred = ICI->getPredicate();
9210 Value *CmpLHS = ICI->getOperand(0);
9211 Value *CmpRHS = ICI->getOperand(1);
9212 Value *TrueVal = SI.getTrueValue();
9213 Value *FalseVal = SI.getFalseValue();
9214
9215 // Check cases where the comparison is with a constant that
9216 // can be adjusted to fit the min/max idiom. We may edit ICI in
9217 // place here, so make sure the select is the only user.
9218 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009219 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009220 switch (Pred) {
9221 default: break;
9222 case ICmpInst::ICMP_ULT:
9223 case ICmpInst::ICMP_SLT: {
9224 // X < MIN ? T : F --> F
9225 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9226 return ReplaceInstUsesWith(SI, FalseVal);
9227 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009228 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009229 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9230 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9231 Pred = ICmpInst::getSwappedPredicate(Pred);
9232 CmpRHS = AdjustedRHS;
9233 std::swap(FalseVal, TrueVal);
9234 ICI->setPredicate(Pred);
9235 ICI->setOperand(1, CmpRHS);
9236 SI.setOperand(1, TrueVal);
9237 SI.setOperand(2, FalseVal);
9238 Changed = true;
9239 }
9240 break;
9241 }
9242 case ICmpInst::ICMP_UGT:
9243 case ICmpInst::ICMP_SGT: {
9244 // X > MAX ? T : F --> F
9245 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9246 return ReplaceInstUsesWith(SI, FalseVal);
9247 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009248 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009249 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9250 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9251 Pred = ICmpInst::getSwappedPredicate(Pred);
9252 CmpRHS = AdjustedRHS;
9253 std::swap(FalseVal, TrueVal);
9254 ICI->setPredicate(Pred);
9255 ICI->setOperand(1, CmpRHS);
9256 SI.setOperand(1, TrueVal);
9257 SI.setOperand(2, FalseVal);
9258 Changed = true;
9259 }
9260 break;
9261 }
9262 }
9263
Dan Gohman1975d032008-10-30 20:40:10 +00009264 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9265 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009266 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009267 if (match(TrueVal, m_ConstantInt<-1>()) &&
9268 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009269 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009270 else if (match(TrueVal, m_ConstantInt<0>()) &&
9271 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009272 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9273
Dan Gohman1975d032008-10-30 20:40:10 +00009274 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9275 // If we are just checking for a icmp eq of a single bit and zext'ing it
9276 // to an integer, then shift the bit to the appropriate place and then
9277 // cast to integer to avoid the comparison.
9278 const APInt &Op1CV = CI->getValue();
9279
9280 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9281 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9282 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009283 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009284 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009285 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009286 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009287 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009288 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009289 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009290 if (In->getType() != SI.getType())
9291 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009292 true/*SExt*/, "tmp", ICI);
9293
9294 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009295 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009296 In->getName()+".not"), *ICI);
9297
9298 return ReplaceInstUsesWith(SI, In);
9299 }
9300 }
9301 }
9302
Dan Gohman81b28ce2008-09-16 18:46:06 +00009303 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9304 // Transform (X == Y) ? X : Y -> Y
9305 if (Pred == ICmpInst::ICMP_EQ)
9306 return ReplaceInstUsesWith(SI, FalseVal);
9307 // Transform (X != Y) ? X : Y -> X
9308 if (Pred == ICmpInst::ICMP_NE)
9309 return ReplaceInstUsesWith(SI, TrueVal);
9310 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9311
9312 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9313 // Transform (X == Y) ? Y : X -> X
9314 if (Pred == ICmpInst::ICMP_EQ)
9315 return ReplaceInstUsesWith(SI, FalseVal);
9316 // Transform (X != Y) ? Y : X -> Y
9317 if (Pred == ICmpInst::ICMP_NE)
9318 return ReplaceInstUsesWith(SI, TrueVal);
9319 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9320 }
9321
9322 /// NOTE: if we wanted to, this is where to detect integer ABS
9323
9324 return Changed ? &SI : 0;
9325}
9326
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009327
Chris Lattner7f239582009-10-22 00:17:26 +00009328/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9329/// PHI node (but the two may be in different blocks). See if the true/false
9330/// values (V) are live in all of the predecessor blocks of the PHI. For
9331/// example, cases like this cannot be mapped:
9332///
9333/// X = phi [ C1, BB1], [C2, BB2]
9334/// Y = add
9335/// Z = select X, Y, 0
9336///
9337/// because Y is not live in BB1/BB2.
9338///
9339static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9340 const SelectInst &SI) {
9341 // If the value is a non-instruction value like a constant or argument, it
9342 // can always be mapped.
9343 const Instruction *I = dyn_cast<Instruction>(V);
9344 if (I == 0) return true;
9345
9346 // If V is a PHI node defined in the same block as the condition PHI, we can
9347 // map the arguments.
9348 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9349
9350 if (const PHINode *VP = dyn_cast<PHINode>(I))
9351 if (VP->getParent() == CondPHI->getParent())
9352 return true;
9353
9354 // Otherwise, if the PHI and select are defined in the same block and if V is
9355 // defined in a different block, then we can transform it.
9356 if (SI.getParent() == CondPHI->getParent() &&
9357 I->getParent() != CondPHI->getParent())
9358 return true;
9359
9360 // Otherwise we have a 'hard' case and we can't tell without doing more
9361 // detailed dominator based analysis, punt.
9362 return false;
9363}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009364
Chris Lattner3d69f462004-03-12 05:52:32 +00009365Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009366 Value *CondVal = SI.getCondition();
9367 Value *TrueVal = SI.getTrueValue();
9368 Value *FalseVal = SI.getFalseValue();
9369
9370 // select true, X, Y -> X
9371 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009372 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009373 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009374
9375 // select C, X, X -> X
9376 if (TrueVal == FalseVal)
9377 return ReplaceInstUsesWith(SI, TrueVal);
9378
Chris Lattnere87597f2004-10-16 18:11:37 +00009379 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9380 return ReplaceInstUsesWith(SI, FalseVal);
9381 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9382 return ReplaceInstUsesWith(SI, TrueVal);
9383 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9384 if (isa<Constant>(TrueVal))
9385 return ReplaceInstUsesWith(SI, TrueVal);
9386 else
9387 return ReplaceInstUsesWith(SI, FalseVal);
9388 }
9389
Owen Anderson1d0be152009-08-13 21:58:54 +00009390 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009391 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009392 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009393 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009394 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009395 } else {
9396 // Change: A = select B, false, C --> A = and !B, C
9397 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009398 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009399 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009400 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009401 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009402 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009403 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009404 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009405 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009406 } else {
9407 // Change: A = select B, C, true --> A = or !B, C
9408 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009409 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009410 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009411 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009412 }
9413 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009414
9415 // select a, b, a -> a&b
9416 // select a, a, b -> a|b
9417 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009418 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009419 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009420 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009421 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009422
Chris Lattner2eefe512004-04-09 19:05:30 +00009423 // Selecting between two integer constants?
9424 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9425 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009426 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009427 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009428 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009429 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009430 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009431 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009432 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009433 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009434 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009435 }
Chris Lattner457dd822004-06-09 07:59:58 +00009436
Reid Spencere4d87aa2006-12-23 06:05:41 +00009437 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009438 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009439 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009440 // non-constant value, eliminate this whole mess. This corresponds to
9441 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009442 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009443 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009444 cast<Constant>(IC->getOperand(1))->isNullValue())
9445 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9446 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009447 isa<ConstantInt>(ICA->getOperand(1)) &&
9448 (ICA->getOperand(1) == TrueValC ||
9449 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009450 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9451 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009452 // know whether we have a icmp_ne or icmp_eq and whether the
9453 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009454 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009455 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009456 Value *V = ICA;
9457 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009458 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009459 Instruction::Xor, V, ICA->getOperand(1)), SI);
9460 return ReplaceInstUsesWith(SI, V);
9461 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009462 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009463 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009464
9465 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009466 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9467 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009468 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009469 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9470 // This is not safe in general for floating point:
9471 // consider X== -0, Y== +0.
9472 // It becomes safe if either operand is a nonzero constant.
9473 ConstantFP *CFPt, *CFPf;
9474 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9475 !CFPt->getValueAPF().isZero()) ||
9476 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9477 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009478 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009479 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009480 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009481 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009482 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009483 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009484
Reid Spencere4d87aa2006-12-23 06:05:41 +00009485 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009486 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009487 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9488 // This is not safe in general for floating point:
9489 // consider X== -0, Y== +0.
9490 // It becomes safe if either operand is a nonzero constant.
9491 ConstantFP *CFPt, *CFPf;
9492 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9493 !CFPt->getValueAPF().isZero()) ||
9494 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9495 !CFPf->getValueAPF().isZero()))
9496 return ReplaceInstUsesWith(SI, FalseVal);
9497 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009498 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009499 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9500 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009501 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009502 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009503 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009504 }
9505
9506 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009507 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9508 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9509 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009510
Chris Lattner87875da2005-01-13 22:52:24 +00009511 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9512 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9513 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009514 Instruction *AddOp = 0, *SubOp = 0;
9515
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009516 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9517 if (TI->getOpcode() == FI->getOpcode())
9518 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9519 return IV;
9520
9521 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9522 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009523 if ((TI->getOpcode() == Instruction::Sub &&
9524 FI->getOpcode() == Instruction::Add) ||
9525 (TI->getOpcode() == Instruction::FSub &&
9526 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009527 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009528 } else if ((FI->getOpcode() == Instruction::Sub &&
9529 TI->getOpcode() == Instruction::Add) ||
9530 (FI->getOpcode() == Instruction::FSub &&
9531 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009532 AddOp = TI; SubOp = FI;
9533 }
9534
9535 if (AddOp) {
9536 Value *OtherAddOp = 0;
9537 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9538 OtherAddOp = AddOp->getOperand(1);
9539 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9540 OtherAddOp = AddOp->getOperand(0);
9541 }
9542
9543 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009544 // So at this point we know we have (Y -> OtherAddOp):
9545 // select C, (add X, Y), (sub X, Z)
9546 Value *NegVal; // Compute -Z
9547 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009548 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009549 } else {
9550 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009551 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009552 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009553 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009554
9555 Value *NewTrueOp = OtherAddOp;
9556 Value *NewFalseOp = NegVal;
9557 if (AddOp != TI)
9558 std::swap(NewTrueOp, NewFalseOp);
9559 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009560 SelectInst::Create(CondVal, NewTrueOp,
9561 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009562
9563 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009564 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009565 }
9566 }
9567 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009568
Chris Lattnere576b912004-04-09 23:46:01 +00009569 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009570 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009571 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9572 if (FoldI)
9573 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009574 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009575
Chris Lattner7f239582009-10-22 00:17:26 +00009576 // See if we can fold the select into a phi node if the condition is a select.
9577 if (isa<PHINode>(SI.getCondition()))
9578 // The true/false values have to be live in the PHI predecessor's blocks.
9579 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9580 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9581 if (Instruction *NV = FoldOpIntoPhi(SI))
9582 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00009583
Chris Lattnera1df33c2005-04-24 07:30:14 +00009584 if (BinaryOperator::isNot(CondVal)) {
9585 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9586 SI.setOperand(1, FalseVal);
9587 SI.setOperand(2, TrueVal);
9588 return &SI;
9589 }
9590
Chris Lattner3d69f462004-03-12 05:52:32 +00009591 return 0;
9592}
9593
Dan Gohmaneee962e2008-04-10 18:43:06 +00009594/// EnforceKnownAlignment - If the specified pointer points to an object that
9595/// we control, modify the object's alignment to PrefAlign. This isn't
9596/// often possible though. If alignment is important, a more reliable approach
9597/// is to simply align all global variables and allocation instructions to
9598/// their preferred alignment from the beginning.
9599///
9600static unsigned EnforceKnownAlignment(Value *V,
9601 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009602
Dan Gohmaneee962e2008-04-10 18:43:06 +00009603 User *U = dyn_cast<User>(V);
9604 if (!U) return Align;
9605
Dan Gohmanca178902009-07-17 20:47:02 +00009606 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009607 default: break;
9608 case Instruction::BitCast:
9609 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9610 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009611 // If all indexes are zero, it is just the alignment of the base pointer.
9612 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009613 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009614 if (!isa<Constant>(*i) ||
9615 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009616 AllZeroOperands = false;
9617 break;
9618 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009619
9620 if (AllZeroOperands) {
9621 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009622 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009623 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009624 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009625 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009626 }
9627
9628 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9629 // If there is a large requested alignment and we can, bump up the alignment
9630 // of the global.
9631 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009632 if (GV->getAlignment() >= PrefAlign)
9633 Align = GV->getAlignment();
9634 else {
9635 GV->setAlignment(PrefAlign);
9636 Align = PrefAlign;
9637 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009638 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009639 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9640 // If there is a requested alignment and if this is an alloca, round up.
9641 if (AI->getAlignment() >= PrefAlign)
9642 Align = AI->getAlignment();
9643 else {
9644 AI->setAlignment(PrefAlign);
9645 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009646 }
9647 }
9648
9649 return Align;
9650}
9651
9652/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9653/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9654/// and it is more than the alignment of the ultimate object, see if we can
9655/// increase the alignment of the ultimate object, making this check succeed.
9656unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9657 unsigned PrefAlign) {
9658 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9659 sizeof(PrefAlign) * CHAR_BIT;
9660 APInt Mask = APInt::getAllOnesValue(BitWidth);
9661 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9662 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9663 unsigned TrailZ = KnownZero.countTrailingOnes();
9664 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9665
9666 if (PrefAlign > Align)
9667 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9668
9669 // We don't need to make any adjustment.
9670 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009671}
9672
Chris Lattnerf497b022008-01-13 23:50:23 +00009673Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009674 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009675 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009676 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009677 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009678
9679 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009680 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009681 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009682 return MI;
9683 }
9684
9685 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9686 // load/store.
9687 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9688 if (MemOpLength == 0) return 0;
9689
Chris Lattner37ac6082008-01-14 00:28:35 +00009690 // Source and destination pointer types are always "i8*" for intrinsic. See
9691 // if the size is something we can handle with a single primitive load/store.
9692 // A single load+store correctly handles overlapping memory in the memmove
9693 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009694 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009695 if (Size == 0) return MI; // Delete this mem transfer.
9696
9697 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009698 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009699
Chris Lattner37ac6082008-01-14 00:28:35 +00009700 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009701 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009702 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009703
9704 // Memcpy forces the use of i8* for the source and destination. That means
9705 // that if you're using memcpy to move one double around, you'll get a cast
9706 // from double* to i8*. We'd much rather use a double load+store rather than
9707 // an i64 load+store, here because this improves the odds that the source or
9708 // dest address will be promotable. See if we can find a better type than the
9709 // integer datatype.
9710 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9711 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009712 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009713 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9714 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009715 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009716 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9717 if (STy->getNumElements() == 1)
9718 SrcETy = STy->getElementType(0);
9719 else
9720 break;
9721 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9722 if (ATy->getNumElements() == 1)
9723 SrcETy = ATy->getElementType();
9724 else
9725 break;
9726 } else
9727 break;
9728 }
9729
Dan Gohman8f8e2692008-05-23 01:52:21 +00009730 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009731 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009732 }
9733 }
9734
9735
Chris Lattnerf497b022008-01-13 23:50:23 +00009736 // If the memcpy/memmove provides better alignment info than we can
9737 // infer, use it.
9738 SrcAlign = std::max(SrcAlign, CopyAlign);
9739 DstAlign = std::max(DstAlign, CopyAlign);
9740
Chris Lattner08142f22009-08-30 19:47:22 +00009741 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9742 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009743 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9744 InsertNewInstBefore(L, *MI);
9745 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9746
9747 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009748 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009749 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009750}
Chris Lattner3d69f462004-03-12 05:52:32 +00009751
Chris Lattner69ea9d22008-04-30 06:39:11 +00009752Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9753 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009754 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009755 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009756 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009757 return MI;
9758 }
9759
9760 // Extract the length and alignment and fill if they are constant.
9761 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9762 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009763 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009764 return 0;
9765 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009766 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009767
9768 // If the length is zero, this is a no-op
9769 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9770
9771 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9772 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009773 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009774
9775 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009776 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009777
9778 // Alignment 0 is identity for alignment 1 for memset, but not store.
9779 if (Alignment == 0) Alignment = 1;
9780
9781 // Extract the fill value and store.
9782 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009783 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009784 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009785
9786 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009787 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009788 return MI;
9789 }
9790
9791 return 0;
9792}
9793
9794
Chris Lattner8b0ea312006-01-13 20:11:04 +00009795/// visitCallInst - CallInst simplification. This mostly only handles folding
9796/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9797/// the heavy lifting.
9798///
Chris Lattner9fe38862003-06-19 17:00:31 +00009799Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00009800 if (isFreeCall(&CI))
9801 return visitFree(CI);
9802
Chris Lattneraab6ec42009-05-13 17:39:14 +00009803 // If the caller function is nounwind, mark the call as nounwind, even if the
9804 // callee isn't.
9805 if (CI.getParent()->getParent()->doesNotThrow() &&
9806 !CI.doesNotThrow()) {
9807 CI.setDoesNotThrow();
9808 return &CI;
9809 }
9810
Chris Lattner8b0ea312006-01-13 20:11:04 +00009811 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9812 if (!II) return visitCallSite(&CI);
9813
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009814 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9815 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009816 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009817 bool Changed = false;
9818
9819 // memmove/cpy/set of zero bytes is a noop.
9820 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9821 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9822
Chris Lattner35b9e482004-10-12 04:52:52 +00009823 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009824 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009825 // Replace the instruction with just byte operations. We would
9826 // transform other cases to loads/stores, but we don't know if
9827 // alignment is sufficient.
9828 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009829 }
9830
Chris Lattner35b9e482004-10-12 04:52:52 +00009831 // If we have a memmove and the source operation is a constant global,
9832 // then the source and dest pointers can't alias, so we can change this
9833 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009834 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009835 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9836 if (GVSrc->isConstant()) {
9837 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009838 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9839 const Type *Tys[1];
9840 Tys[0] = CI.getOperand(3)->getType();
9841 CI.setOperand(0,
9842 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009843 Changed = true;
9844 }
Chris Lattnera935db82008-05-28 05:30:41 +00009845
9846 // memmove(x,x,size) -> noop.
9847 if (MMI->getSource() == MMI->getDest())
9848 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009849 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009850
Chris Lattner95a959d2006-03-06 20:18:44 +00009851 // If we can determine a pointer alignment that is bigger than currently
9852 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009853 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009854 if (Instruction *I = SimplifyMemTransfer(MI))
9855 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009856 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9857 if (Instruction *I = SimplifyMemSet(MSI))
9858 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009859 }
9860
Chris Lattner8b0ea312006-01-13 20:11:04 +00009861 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009862 }
9863
9864 switch (II->getIntrinsicID()) {
9865 default: break;
9866 case Intrinsic::bswap:
9867 // bswap(bswap(x)) -> x
9868 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9869 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9870 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9871 break;
9872 case Intrinsic::ppc_altivec_lvx:
9873 case Intrinsic::ppc_altivec_lvxl:
9874 case Intrinsic::x86_sse_loadu_ps:
9875 case Intrinsic::x86_sse2_loadu_pd:
9876 case Intrinsic::x86_sse2_loadu_dq:
9877 // Turn PPC lvx -> load if the pointer is known aligned.
9878 // Turn X86 loadups -> load if the pointer is known aligned.
9879 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009880 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9881 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009882 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009883 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009884 break;
9885 case Intrinsic::ppc_altivec_stvx:
9886 case Intrinsic::ppc_altivec_stvxl:
9887 // Turn stvx -> store if the pointer is known aligned.
9888 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9889 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009890 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009891 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009892 return new StoreInst(II->getOperand(1), Ptr);
9893 }
9894 break;
9895 case Intrinsic::x86_sse_storeu_ps:
9896 case Intrinsic::x86_sse2_storeu_pd:
9897 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009898 // Turn X86 storeu -> store if the pointer is known aligned.
9899 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9900 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009901 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009902 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009903 return new StoreInst(II->getOperand(2), Ptr);
9904 }
9905 break;
9906
9907 case Intrinsic::x86_sse_cvttss2si: {
9908 // These intrinsics only demands the 0th element of its input vector. If
9909 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009910 unsigned VWidth =
9911 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9912 APInt DemandedElts(VWidth, 1);
9913 APInt UndefElts(VWidth, 0);
9914 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009915 UndefElts)) {
9916 II->setOperand(1, V);
9917 return II;
9918 }
9919 break;
9920 }
9921
9922 case Intrinsic::ppc_altivec_vperm:
9923 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9924 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9925 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009926
Chris Lattner0521e3c2008-06-18 04:33:20 +00009927 // Check that all of the elements are integer constants or undefs.
9928 bool AllEltsOk = true;
9929 for (unsigned i = 0; i != 16; ++i) {
9930 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9931 !isa<UndefValue>(Mask->getOperand(i))) {
9932 AllEltsOk = false;
9933 break;
9934 }
9935 }
9936
9937 if (AllEltsOk) {
9938 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009939 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9940 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009941 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009942
Chris Lattner0521e3c2008-06-18 04:33:20 +00009943 // Only extract each element once.
9944 Value *ExtractedElts[32];
9945 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9946
Chris Lattnere2ed0572006-04-06 19:19:17 +00009947 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009948 if (isa<UndefValue>(Mask->getOperand(i)))
9949 continue;
9950 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9951 Idx &= 31; // Match the hardware behavior.
9952
9953 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009954 ExtractedElts[Idx] =
9955 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9956 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9957 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009958 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009959
Chris Lattner0521e3c2008-06-18 04:33:20 +00009960 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009961 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9962 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9963 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009964 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009965 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009966 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009967 }
9968 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009969
Chris Lattner0521e3c2008-06-18 04:33:20 +00009970 case Intrinsic::stackrestore: {
9971 // If the save is right next to the restore, remove the restore. This can
9972 // happen when variable allocas are DCE'd.
9973 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9974 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9975 BasicBlock::iterator BI = SS;
9976 if (&*++BI == II)
9977 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009978 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009979 }
9980
9981 // Scan down this block to see if there is another stack restore in the
9982 // same block without an intervening call/alloca.
9983 BasicBlock::iterator BI = II;
9984 TerminatorInst *TI = II->getParent()->getTerminator();
9985 bool CannotRemove = false;
9986 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009987 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009988 CannotRemove = true;
9989 break;
9990 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009991 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9992 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9993 // If there is a stackrestore below this one, remove this one.
9994 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9995 return EraseInstFromFunction(CI);
9996 // Otherwise, ignore the intrinsic.
9997 } else {
9998 // If we found a non-intrinsic call, we can't remove the stack
9999 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010000 CannotRemove = true;
10001 break;
10002 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010003 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010004 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010005
10006 // If the stack restore is in a return/unwind block and if there are no
10007 // allocas or calls between the restore and the return, nuke the restore.
10008 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10009 return EraseInstFromFunction(CI);
10010 break;
10011 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010012 }
10013
Chris Lattner8b0ea312006-01-13 20:11:04 +000010014 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010015}
10016
10017// InvokeInst simplification
10018//
10019Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010020 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010021}
10022
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010023/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10024/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010025static bool isSafeToEliminateVarargsCast(const CallSite CS,
10026 const CastInst * const CI,
10027 const TargetData * const TD,
10028 const int ix) {
10029 if (!CI->isLosslessCast())
10030 return false;
10031
10032 // The size of ByVal arguments is derived from the type, so we
10033 // can't change to a type with a different size. If the size were
10034 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010035 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010036 return true;
10037
10038 const Type* SrcTy =
10039 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10040 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10041 if (!SrcTy->isSized() || !DstTy->isSized())
10042 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010043 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010044 return false;
10045 return true;
10046}
10047
Chris Lattnera44d8a22003-10-07 22:32:43 +000010048// visitCallSite - Improvements for call and invoke instructions.
10049//
10050Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010051 bool Changed = false;
10052
10053 // If the callee is a constexpr cast of a function, attempt to move the cast
10054 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010055 if (transformConstExprCastCall(CS)) return 0;
10056
Chris Lattner6c266db2003-10-07 22:54:13 +000010057 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010058
Chris Lattner08b22ec2005-05-13 07:09:09 +000010059 if (Function *CalleeF = dyn_cast<Function>(Callee))
10060 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10061 Instruction *OldCall = CS.getInstruction();
10062 // If the call and callee calling conventions don't match, this call must
10063 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010064 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010065 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010066 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010067 // If OldCall dues not return void then replaceAllUsesWith undef.
10068 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010069 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010070 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010071 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10072 return EraseInstFromFunction(*OldCall);
10073 return 0;
10074 }
10075
Chris Lattner17be6352004-10-18 02:59:09 +000010076 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10077 // This instruction is not reachable, just remove it. We insert a store to
10078 // undef so that we know that this code is not reachable, despite the fact
10079 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010080 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010081 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010082 CS.getInstruction());
10083
Devang Patel228ebd02009-10-13 22:56:32 +000010084 // If CS dues not return void then replaceAllUsesWith undef.
10085 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010086 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010087 CS.getInstruction()->
10088 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010089
10090 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10091 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010092 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010093 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010094 }
Chris Lattner17be6352004-10-18 02:59:09 +000010095 return EraseInstFromFunction(*CS.getInstruction());
10096 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010097
Duncan Sandscdb6d922007-09-17 10:26:40 +000010098 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10099 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10100 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10101 return transformCallThroughTrampoline(CS);
10102
Chris Lattner6c266db2003-10-07 22:54:13 +000010103 const PointerType *PTy = cast<PointerType>(Callee->getType());
10104 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10105 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010106 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010107 // See if we can optimize any arguments passed through the varargs area of
10108 // the call.
10109 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010110 E = CS.arg_end(); I != E; ++I, ++ix) {
10111 CastInst *CI = dyn_cast<CastInst>(*I);
10112 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10113 *I = CI->getOperand(0);
10114 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010115 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010116 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010117 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010118
Duncan Sandsf0c33542007-12-19 21:13:37 +000010119 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010120 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010121 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010122 Changed = true;
10123 }
10124
Chris Lattner6c266db2003-10-07 22:54:13 +000010125 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010126}
10127
Chris Lattner9fe38862003-06-19 17:00:31 +000010128// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10129// attempt to move the cast to the arguments of the call/invoke.
10130//
10131bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10132 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10133 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010134 if (CE->getOpcode() != Instruction::BitCast ||
10135 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010136 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010137 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010138 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010139 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010140
10141 // Okay, this is a cast from a function to a different type. Unless doing so
10142 // would cause a type conversion of one of our arguments, change this call to
10143 // be a direct call with arguments casted to the appropriate types.
10144 //
10145 const FunctionType *FT = Callee->getFunctionType();
10146 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010147 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010148
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010149 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010150 return false; // TODO: Handle multiple return values.
10151
Chris Lattnerf78616b2004-01-14 06:06:08 +000010152 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010153 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010154 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010155 // Conversion is ok if changing from one pointer type to another or from
10156 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010157 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010158 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010159 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010160 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010161 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010162
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010163 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010164 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010165 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010166 return false; // Cannot transform this return value.
10167
Chris Lattner58d74912008-03-12 17:45:29 +000010168 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010169 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010170 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010171 return false; // Attribute not compatible with transformed value.
10172 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010173
Chris Lattnerf78616b2004-01-14 06:06:08 +000010174 // If the callsite is an invoke instruction, and the return value is used by
10175 // a PHI node in a successor, we cannot change the return type of the call
10176 // because there is no place to put the cast instruction (without breaking
10177 // the critical edge). Bail out in this case.
10178 if (!Caller->use_empty())
10179 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10180 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10181 UI != E; ++UI)
10182 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10183 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010184 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010185 return false;
10186 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010187
10188 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10189 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010190
Chris Lattner9fe38862003-06-19 17:00:31 +000010191 CallSite::arg_iterator AI = CS.arg_begin();
10192 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10193 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010194 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010195
10196 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010197 return false; // Cannot transform this parameter value.
10198
Devang Patel19c87462008-09-26 22:53:05 +000010199 if (CallerPAL.getParamAttributes(i + 1)
10200 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010201 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010202
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010203 // Converting from one pointer type to another or between a pointer and an
10204 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010205 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010206 (TD && ((isa<PointerType>(ParamTy) ||
10207 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10208 (isa<PointerType>(ActTy) ||
10209 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010210 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010211 }
10212
10213 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010214 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010215 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010216
Chris Lattner58d74912008-03-12 17:45:29 +000010217 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10218 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010219 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010220 // won't be dropping them. Check that these extra arguments have attributes
10221 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010222 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10223 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010224 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010225 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010226 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010227 return false;
10228 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010229
Chris Lattner9fe38862003-06-19 17:00:31 +000010230 // Okay, we decided that this is a safe thing to do: go ahead and start
10231 // inserting cast instructions as necessary...
10232 std::vector<Value*> Args;
10233 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010234 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010235 attrVec.reserve(NumCommonArgs);
10236
10237 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010238 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010239
10240 // If the return value is not being used, the type may not be compatible
10241 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010242 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010243
10244 // Add the new return attributes.
10245 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010246 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010247
10248 AI = CS.arg_begin();
10249 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10250 const Type *ParamTy = FT->getParamType(i);
10251 if ((*AI)->getType() == ParamTy) {
10252 Args.push_back(*AI);
10253 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010254 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010255 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010256 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010257 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010258
10259 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010260 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010261 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010262 }
10263
10264 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010265 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010266 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010267 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010268
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010269 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010270 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010271 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010272 errs() << "WARNING: While resolving call to function '"
10273 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010274 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010275 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010276 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10277 const Type *PTy = getPromotedType((*AI)->getType());
10278 if (PTy != (*AI)->getType()) {
10279 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010280 Instruction::CastOps opcode =
10281 CastInst::getCastOpcode(*AI, false, PTy, false);
10282 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010283 } else {
10284 Args.push_back(*AI);
10285 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010286
Duncan Sandse1e520f2008-01-13 08:02:44 +000010287 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010288 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010289 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010290 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010291 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010292 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010293
Devang Patel19c87462008-09-26 22:53:05 +000010294 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10295 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10296
Devang Patel9674d152009-10-14 17:29:00 +000010297 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010298 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010299
Eric Christophera66297a2009-07-25 02:45:27 +000010300 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10301 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010302
Chris Lattner9fe38862003-06-19 17:00:31 +000010303 Instruction *NC;
10304 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010305 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010306 Args.begin(), Args.end(),
10307 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010308 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010309 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010310 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010311 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10312 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010313 CallInst *CI = cast<CallInst>(Caller);
10314 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010315 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010316 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010317 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010318 }
10319
Chris Lattner6934a042007-02-11 01:23:03 +000010320 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010321 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010322 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010323 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010324 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010325 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010326 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010327
10328 // If this is an invoke instruction, we should insert it after the first
10329 // non-phi, instruction in the normal successor block.
10330 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010331 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010332 InsertNewInstBefore(NC, *I);
10333 } else {
10334 // Otherwise, it's a call, just insert cast right after the call instr
10335 InsertNewInstBefore(NC, *Caller);
10336 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010337 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010338 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010339 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010340 }
10341 }
10342
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010343
Chris Lattner931f8f32009-08-31 05:17:58 +000010344 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010345 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010346
10347 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010348 return true;
10349}
10350
Duncan Sandscdb6d922007-09-17 10:26:40 +000010351// transformCallThroughTrampoline - Turn a call to a function created by the
10352// init_trampoline intrinsic into a direct call to the underlying function.
10353//
10354Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10355 Value *Callee = CS.getCalledValue();
10356 const PointerType *PTy = cast<PointerType>(Callee->getType());
10357 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010358 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010359
10360 // If the call already has the 'nest' attribute somewhere then give up -
10361 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010362 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010363 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010364
10365 IntrinsicInst *Tramp =
10366 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10367
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010368 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010369 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10370 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10371
Devang Patel05988662008-09-25 21:00:45 +000010372 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010373 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010374 unsigned NestIdx = 1;
10375 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010376 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010377
10378 // Look for a parameter marked with the 'nest' attribute.
10379 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10380 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010381 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010382 // Record the parameter type and any other attributes.
10383 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010384 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010385 break;
10386 }
10387
10388 if (NestTy) {
10389 Instruction *Caller = CS.getInstruction();
10390 std::vector<Value*> NewArgs;
10391 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10392
Devang Patel05988662008-09-25 21:00:45 +000010393 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010394 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010395
Duncan Sandscdb6d922007-09-17 10:26:40 +000010396 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010397 // mean appending it. Likewise for attributes.
10398
Devang Patel19c87462008-09-26 22:53:05 +000010399 // Add any result attributes.
10400 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010401 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010402
Duncan Sandscdb6d922007-09-17 10:26:40 +000010403 {
10404 unsigned Idx = 1;
10405 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10406 do {
10407 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010408 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010409 Value *NestVal = Tramp->getOperand(3);
10410 if (NestVal->getType() != NestTy)
10411 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10412 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010413 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010414 }
10415
10416 if (I == E)
10417 break;
10418
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010419 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010420 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010421 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010422 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010423 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010424
10425 ++Idx, ++I;
10426 } while (1);
10427 }
10428
Devang Patel19c87462008-09-26 22:53:05 +000010429 // Add any function attributes.
10430 if (Attributes Attr = Attrs.getFnAttributes())
10431 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10432
Duncan Sandscdb6d922007-09-17 10:26:40 +000010433 // The trampoline may have been bitcast to a bogus type (FTy).
10434 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010435 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010436
Duncan Sandscdb6d922007-09-17 10:26:40 +000010437 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010438 NewTypes.reserve(FTy->getNumParams()+1);
10439
Duncan Sandscdb6d922007-09-17 10:26:40 +000010440 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010441 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010442 {
10443 unsigned Idx = 1;
10444 FunctionType::param_iterator I = FTy->param_begin(),
10445 E = FTy->param_end();
10446
10447 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010448 if (Idx == NestIdx)
10449 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010450 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010451
10452 if (I == E)
10453 break;
10454
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010455 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010456 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010457
10458 ++Idx, ++I;
10459 } while (1);
10460 }
10461
10462 // Replace the trampoline call with a direct call. Let the generic
10463 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010464 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010465 FTy->isVarArg());
10466 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010467 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010468 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010469 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010470 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10471 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010472
10473 Instruction *NewCaller;
10474 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010475 NewCaller = InvokeInst::Create(NewCallee,
10476 II->getNormalDest(), II->getUnwindDest(),
10477 NewArgs.begin(), NewArgs.end(),
10478 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010479 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010480 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010481 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010482 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10483 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010484 if (cast<CallInst>(Caller)->isTailCall())
10485 cast<CallInst>(NewCaller)->setTailCall();
10486 cast<CallInst>(NewCaller)->
10487 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010488 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010489 }
Devang Patel9674d152009-10-14 17:29:00 +000010490 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010491 Caller->replaceAllUsesWith(NewCaller);
10492 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010493 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010494 return 0;
10495 }
10496 }
10497
10498 // Replace the trampoline call with a direct call. Since there is no 'nest'
10499 // parameter, there is no need to adjust the argument list. Let the generic
10500 // code sort out any function type mismatches.
10501 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010502 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010503 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010504 CS.setCalledFunction(NewCallee);
10505 return CS.getInstruction();
10506}
10507
Dan Gohman9ad29202009-09-16 16:50:24 +000010508/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10509/// and if a/b/c and the add's all have a single use, turn this into a phi
Chris Lattner7da52b22006-11-01 04:51:18 +000010510/// and a single binop.
10511Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10512 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010513 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010514 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010515 Value *LHSVal = FirstInst->getOperand(0);
10516 Value *RHSVal = FirstInst->getOperand(1);
10517
10518 const Type *LHSType = LHSVal->getType();
10519 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010520
Dan Gohman9ad29202009-09-16 16:50:24 +000010521 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010522 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010523 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010524 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010525 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010526 // types or GEP's with different index types.
10527 I->getOperand(0)->getType() != LHSType ||
10528 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010529 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010530
10531 // If they are CmpInst instructions, check their predicates
10532 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10533 if (cast<CmpInst>(I)->getPredicate() !=
10534 cast<CmpInst>(FirstInst)->getPredicate())
10535 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010536
10537 // Keep track of which operand needs a phi node.
10538 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10539 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010540 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010541
10542 // If both LHS and RHS would need a PHI, don't do this transformation,
10543 // because it would increase the number of PHIs entering the block,
10544 // which leads to higher register pressure. This is especially
10545 // bad when the PHIs are in the header of a loop.
10546 if (!LHSVal && !RHSVal)
10547 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010548
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010549 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010550
Chris Lattner7da52b22006-11-01 04:51:18 +000010551 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010552 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010553 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010554 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010555 NewLHS = PHINode::Create(LHSType,
10556 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010557 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10558 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010559 InsertNewInstBefore(NewLHS, PN);
10560 LHSVal = NewLHS;
10561 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010562
10563 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010564 NewRHS = PHINode::Create(RHSType,
10565 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010566 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10567 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010568 InsertNewInstBefore(NewRHS, PN);
10569 RHSVal = NewRHS;
10570 }
10571
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010572 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010573 if (NewLHS || NewRHS) {
10574 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10575 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10576 if (NewLHS) {
10577 Value *NewInLHS = InInst->getOperand(0);
10578 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10579 }
10580 if (NewRHS) {
10581 Value *NewInRHS = InInst->getOperand(1);
10582 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10583 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010584 }
10585 }
10586
Chris Lattner7da52b22006-11-01 04:51:18 +000010587 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010588 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010589 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010590 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010591 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010592}
10593
Chris Lattner05f18922008-12-01 02:34:36 +000010594Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10595 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10596
10597 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10598 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010599 // This is true if all GEP bases are allocas and if all indices into them are
10600 // constants.
10601 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010602
10603 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010604 // more than one phi, which leads to higher register pressure. This is
10605 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010606 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010607
Dan Gohman9ad29202009-09-16 16:50:24 +000010608 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010609 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10610 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10611 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10612 GEP->getNumOperands() != FirstInst->getNumOperands())
10613 return 0;
10614
Chris Lattner36d3e322009-02-21 00:46:50 +000010615 // Keep track of whether or not all GEPs are of alloca pointers.
10616 if (AllBasePointersAreAllocas &&
10617 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10618 !GEP->hasAllConstantIndices()))
10619 AllBasePointersAreAllocas = false;
10620
Chris Lattner05f18922008-12-01 02:34:36 +000010621 // Compare the operand lists.
10622 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10623 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10624 continue;
10625
10626 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10627 // if one of the PHIs has a constant for the index. The index may be
10628 // substantially cheaper to compute for the constants, so making it a
10629 // variable index could pessimize the path. This also handles the case
10630 // for struct indices, which must always be constant.
10631 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10632 isa<ConstantInt>(GEP->getOperand(op)))
10633 return 0;
10634
10635 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10636 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010637
10638 // If we already needed a PHI for an earlier operand, and another operand
10639 // also requires a PHI, we'd be introducing more PHIs than we're
10640 // eliminating, which increases register pressure on entry to the PHI's
10641 // block.
10642 if (NeededPhi)
10643 return 0;
10644
Chris Lattner05f18922008-12-01 02:34:36 +000010645 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010646 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010647 }
10648 }
10649
Chris Lattner36d3e322009-02-21 00:46:50 +000010650 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010651 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010652 // offset calculation, but all the predecessors will have to materialize the
10653 // stack address into a register anyway. We'd actually rather *clone* the
10654 // load up into the predecessors so that we have a load of a gep of an alloca,
10655 // which can usually all be folded into the load.
10656 if (AllBasePointersAreAllocas)
10657 return 0;
10658
Chris Lattner05f18922008-12-01 02:34:36 +000010659 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10660 // that is variable.
10661 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10662
10663 bool HasAnyPHIs = false;
10664 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10665 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10666 Value *FirstOp = FirstInst->getOperand(i);
10667 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10668 FirstOp->getName()+".pn");
10669 InsertNewInstBefore(NewPN, PN);
10670
10671 NewPN->reserveOperandSpace(e);
10672 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10673 OperandPhis[i] = NewPN;
10674 FixedOperands[i] = NewPN;
10675 HasAnyPHIs = true;
10676 }
10677
10678
10679 // Add all operands to the new PHIs.
10680 if (HasAnyPHIs) {
10681 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10682 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10683 BasicBlock *InBB = PN.getIncomingBlock(i);
10684
10685 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10686 if (PHINode *OpPhi = OperandPhis[op])
10687 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10688 }
10689 }
10690
10691 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010692 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10693 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10694 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010695 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10696 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010697}
10698
10699
Chris Lattner21550882009-02-23 05:56:17 +000010700/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10701/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010702/// obvious the value of the load is not changed from the point of the load to
10703/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010704///
10705/// Finally, it is safe, but not profitable, to sink a load targetting a
10706/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10707/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010708static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010709 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10710
10711 for (++BBI; BBI != E; ++BBI)
10712 if (BBI->mayWriteToMemory())
10713 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010714
10715 // Check for non-address taken alloca. If not address-taken already, it isn't
10716 // profitable to do this xform.
10717 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10718 bool isAddressTaken = false;
10719 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10720 UI != E; ++UI) {
10721 if (isa<LoadInst>(UI)) continue;
10722 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10723 // If storing TO the alloca, then the address isn't taken.
10724 if (SI->getOperand(1) == AI) continue;
10725 }
10726 isAddressTaken = true;
10727 break;
10728 }
10729
Chris Lattner36d3e322009-02-21 00:46:50 +000010730 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010731 return false;
10732 }
10733
Chris Lattner36d3e322009-02-21 00:46:50 +000010734 // If this load is a load from a GEP with a constant offset from an alloca,
10735 // then we don't want to sink it. In its present form, it will be
10736 // load [constant stack offset]. Sinking it will cause us to have to
10737 // materialize the stack addresses in each predecessor in a register only to
10738 // do a shared load from register in the successor.
10739 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10740 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10741 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10742 return false;
10743
Chris Lattner76c73142006-11-01 07:13:54 +000010744 return true;
10745}
10746
Chris Lattner751a3622009-11-01 20:04:24 +000010747Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10748 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10749
10750 // When processing loads, we need to propagate two bits of information to the
10751 // sunk load: whether it is volatile, and what its alignment is. We currently
10752 // don't sink loads when some have their alignment specified and some don't.
10753 // visitLoadInst will propagate an alignment onto the load when TD is around,
10754 // and if TD isn't around, we can't handle the mixed case.
10755 bool isVolatile = FirstLI->isVolatile();
10756 unsigned LoadAlignment = FirstLI->getAlignment();
10757
10758 // We can't sink the load if the loaded value could be modified between the
10759 // load and the PHI.
10760 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10761 !isSafeAndProfitableToSinkLoad(FirstLI))
10762 return 0;
10763
10764 // If the PHI is of volatile loads and the load block has multiple
10765 // successors, sinking it would remove a load of the volatile value from
10766 // the path through the other successor.
10767 if (isVolatile &&
10768 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10769 return 0;
10770
10771 // Check to see if all arguments are the same operation.
10772 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10773 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10774 if (!LI || !LI->hasOneUse())
10775 return 0;
10776
10777 // We can't sink the load if the loaded value could be modified between
10778 // the load and the PHI.
10779 if (LI->isVolatile() != isVolatile ||
10780 LI->getParent() != PN.getIncomingBlock(i) ||
10781 !isSafeAndProfitableToSinkLoad(LI))
10782 return 0;
10783
10784 // If some of the loads have an alignment specified but not all of them,
10785 // we can't do the transformation.
10786 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10787 return 0;
10788
Chris Lattnera664bb72009-11-01 20:07:07 +000010789 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000010790
10791 // If the PHI is of volatile loads and the load block has multiple
10792 // successors, sinking it would remove a load of the volatile value from
10793 // the path through the other successor.
10794 if (isVolatile &&
10795 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10796 return 0;
10797 }
10798
10799 // Okay, they are all the same operation. Create a new PHI node of the
10800 // correct type, and PHI together all of the LHS's of the instructions.
10801 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10802 PN.getName()+".in");
10803 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10804
10805 Value *InVal = FirstLI->getOperand(0);
10806 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10807
10808 // Add all operands to the new PHI.
10809 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10810 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10811 if (NewInVal != InVal)
10812 InVal = 0;
10813 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10814 }
10815
10816 Value *PhiVal;
10817 if (InVal) {
10818 // The new PHI unions all of the same values together. This is really
10819 // common, so we handle it intelligently here for compile-time speed.
10820 PhiVal = InVal;
10821 delete NewPN;
10822 } else {
10823 InsertNewInstBefore(NewPN, PN);
10824 PhiVal = NewPN;
10825 }
10826
10827 // If this was a volatile load that we are merging, make sure to loop through
10828 // and mark all the input loads as non-volatile. If we don't do this, we will
10829 // insert a new volatile load and the old ones will not be deletable.
10830 if (isVolatile)
10831 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10832 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10833
10834 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
10835}
10836
Chris Lattner9fe38862003-06-19 17:00:31 +000010837
Chris Lattnerbac32862004-11-14 19:13:23 +000010838// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10839// operator and they all are only used by the PHI, PHI together their
10840// inputs, and do the operation once, to the result of the PHI.
10841Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10842 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10843
Chris Lattner751a3622009-11-01 20:04:24 +000010844 if (isa<GetElementPtrInst>(FirstInst))
10845 return FoldPHIArgGEPIntoPHI(PN);
10846 if (isa<LoadInst>(FirstInst))
10847 return FoldPHIArgLoadIntoPHI(PN);
10848
Chris Lattnerbac32862004-11-14 19:13:23 +000010849 // Scan the instruction, looking for input operations that can be folded away.
10850 // If all input operands to the phi are the same instruction (e.g. a cast from
10851 // the same type or "+42") we can pull the operation through the PHI, reducing
10852 // code size and simplifying code.
10853 Constant *ConstantOp = 0;
10854 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000010855
Chris Lattnerbac32862004-11-14 19:13:23 +000010856 if (isa<CastInst>(FirstInst)) {
10857 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000010858
10859 // Be careful about transforming integer PHIs. We don't want to pessimize
10860 // the code by turning an i32 into an i1293.
10861 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
10862 // If we don't have TD, we don't know if the original PHI was legal.
10863 if (!TD) return 0;
10864
10865 unsigned PHIWidth = PN.getType()->getPrimitiveSizeInBits();
10866 unsigned NewWidth = CastSrcTy->getPrimitiveSizeInBits();
10867 bool PHILegal = TD->isLegalInteger(PHIWidth);
10868 bool NewLegal = TD->isLegalInteger(NewWidth);
Chris Lattner9956c052009-11-08 19:23:30 +000010869
Chris Lattnerbf382b52009-11-08 21:20:06 +000010870 // If this is a legal integer PHI node, and pulling the operation through
10871 // would cause it to be an illegal integer PHI, don't do the
10872 // transformation.
10873 if (PHILegal && !NewLegal)
10874 return 0;
10875
10876 // Otherwise, if both are illegal, do not increase the size of the PHI. We
10877 // do allow things like i160 -> i64, but not i64 -> i160.
10878 if (!PHILegal && !NewLegal && NewWidth > PHIWidth)
10879 return 0;
10880 }
Reid Spencer832254e2007-02-02 02:16:23 +000010881 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010882 // Can fold binop, compare or shift here if the RHS is a constant,
10883 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010884 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010885 if (ConstantOp == 0)
10886 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010887 } else {
10888 return 0; // Cannot fold this operation.
10889 }
10890
10891 // Check to see if all arguments are the same operation.
10892 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000010893 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10894 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010895 return 0;
10896 if (CastSrcTy) {
10897 if (I->getOperand(0)->getType() != CastSrcTy)
10898 return 0; // Cast operation must match.
10899 } else if (I->getOperand(1) != ConstantOp) {
10900 return 0;
10901 }
10902 }
10903
10904 // Okay, they are all the same operation. Create a new PHI node of the
10905 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010906 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10907 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010908 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010909
10910 Value *InVal = FirstInst->getOperand(0);
10911 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010912
10913 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010914 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10915 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10916 if (NewInVal != InVal)
10917 InVal = 0;
10918 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10919 }
10920
10921 Value *PhiVal;
10922 if (InVal) {
10923 // The new PHI unions all of the same values together. This is really
10924 // common, so we handle it intelligently here for compile-time speed.
10925 PhiVal = InVal;
10926 delete NewPN;
10927 } else {
10928 InsertNewInstBefore(NewPN, PN);
10929 PhiVal = NewPN;
10930 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010931
Chris Lattnerbac32862004-11-14 19:13:23 +000010932 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000010933 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010934 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000010935
Chris Lattner54545ac2008-04-29 17:13:43 +000010936 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010937 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000010938
Chris Lattner751a3622009-11-01 20:04:24 +000010939 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10940 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10941 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000010942}
Chris Lattnera1be5662002-05-02 17:06:02 +000010943
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010944/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10945/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010946static bool DeadPHICycle(PHINode *PN,
10947 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010948 if (PN->use_empty()) return true;
10949 if (!PN->hasOneUse()) return false;
10950
10951 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010952 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010953 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010954
10955 // Don't scan crazily complex things.
10956 if (PotentiallyDeadPHIs.size() == 16)
10957 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010958
10959 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10960 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010961
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010962 return false;
10963}
10964
Chris Lattnercf5008a2007-11-06 21:52:06 +000010965/// PHIsEqualValue - Return true if this phi node is always equal to
10966/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10967/// z = some value; x = phi (y, z); y = phi (x, z)
10968static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10969 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10970 // See if we already saw this PHI node.
10971 if (!ValueEqualPHIs.insert(PN))
10972 return true;
10973
10974 // Don't scan crazily complex things.
10975 if (ValueEqualPHIs.size() == 16)
10976 return false;
10977
10978 // Scan the operands to see if they are either phi nodes or are equal to
10979 // the value.
10980 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10981 Value *Op = PN->getIncomingValue(i);
10982 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10983 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10984 return false;
10985 } else if (Op != NonPhiInVal)
10986 return false;
10987 }
10988
10989 return true;
10990}
10991
10992
Chris Lattner9956c052009-11-08 19:23:30 +000010993namespace {
10994struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010995 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000010996 unsigned Shift; // The amount shifted.
10997 Instruction *Inst; // The trunc instruction.
10998
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010999 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11000 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000011001
11002 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011003 if (PHIId < RHS.PHIId) return true;
11004 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000011005 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011006 if (Shift > RHS.Shift) return false;
11007 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000011008 RHS.Inst->getType()->getPrimitiveSizeInBits();
11009 }
11010};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011011
11012struct LoweredPHIRecord {
11013 PHINode *PN; // The PHI that was lowered.
11014 unsigned Shift; // The amount shifted.
11015 unsigned Width; // The width extracted.
11016
11017 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11018 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11019
11020 // Ctor form used by DenseMap.
11021 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11022 : PN(pn), Shift(Sh), Width(0) {}
11023};
11024}
11025
11026namespace llvm {
11027 template<>
11028 struct DenseMapInfo<LoweredPHIRecord> {
11029 static inline LoweredPHIRecord getEmptyKey() {
11030 return LoweredPHIRecord(0, 0);
11031 }
11032 static inline LoweredPHIRecord getTombstoneKey() {
11033 return LoweredPHIRecord(0, 1);
11034 }
11035 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11036 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11037 (Val.Width>>3);
11038 }
11039 static bool isEqual(const LoweredPHIRecord &LHS,
11040 const LoweredPHIRecord &RHS) {
11041 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11042 LHS.Width == RHS.Width;
11043 }
11044 static bool isPod() { return true; }
11045 };
Chris Lattner9956c052009-11-08 19:23:30 +000011046}
11047
11048
11049/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11050/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11051/// so, we split the PHI into the various pieces being extracted. This sort of
11052/// thing is introduced when SROA promotes an aggregate to large integer values.
11053///
11054/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11055/// inttoptr. We should produce new PHIs in the right type.
11056///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011057Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11058 // PHIUsers - Keep track of all of the truncated values extracted from a set
11059 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000011060 SmallVector<PHIUsageRecord, 16> PHIUsers;
11061
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011062 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11063 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11064 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11065 // check the uses of (to ensure they are all extracts).
11066 SmallVector<PHINode*, 8> PHIsToSlice;
11067 SmallPtrSet<PHINode*, 8> PHIsInspected;
11068
11069 PHIsToSlice.push_back(&FirstPhi);
11070 PHIsInspected.insert(&FirstPhi);
11071
11072 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11073 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011074
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011075 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11076 UI != E; ++UI) {
11077 Instruction *User = cast<Instruction>(*UI);
11078
11079 // If the user is a PHI, inspect its uses recursively.
11080 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11081 if (PHIsInspected.insert(UserPN))
11082 PHIsToSlice.push_back(UserPN);
11083 continue;
11084 }
11085
11086 // Truncates are always ok.
11087 if (isa<TruncInst>(User)) {
11088 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11089 continue;
11090 }
11091
11092 // Otherwise it must be a lshr which can only be used by one trunc.
11093 if (User->getOpcode() != Instruction::LShr ||
11094 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11095 !isa<ConstantInt>(User->getOperand(1)))
11096 return 0;
11097
11098 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11099 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000011100 }
Chris Lattner9956c052009-11-08 19:23:30 +000011101 }
11102
11103 // If we have no users, they must be all self uses, just nuke the PHI.
11104 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011105 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000011106
11107 // If this phi node is transformable, create new PHIs for all the pieces
11108 // extracted out of it. First, sort the users by their offset and size.
11109 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11110
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011111 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11112 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11113 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11114 );
Chris Lattner9956c052009-11-08 19:23:30 +000011115
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011116 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11117 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000011118 DenseMap<BasicBlock*, Value*> PredValues;
11119
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011120 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11121 // introduce redundant PHIs.
11122 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11123
11124 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11125 unsigned PHIId = PHIUsers[UserI].PHIId;
11126 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011127 unsigned Offset = PHIUsers[UserI].Shift;
11128 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000011129
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011130 PHINode *EltPHI;
11131
11132 // If we've already lowered a user like this, reuse the previously lowered
11133 // value.
11134 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000011135
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011136 // Otherwise, Create the new PHI node for this user.
11137 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11138 assert(EltPHI->getType() != PN->getType() &&
11139 "Truncate didn't shrink phi?");
11140
11141 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11142 BasicBlock *Pred = PN->getIncomingBlock(i);
11143 Value *&PredVal = PredValues[Pred];
11144
11145 // If we already have a value for this predecessor, reuse it.
11146 if (PredVal) {
11147 EltPHI->addIncoming(PredVal, Pred);
11148 continue;
11149 }
Chris Lattner9956c052009-11-08 19:23:30 +000011150
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011151 // Handle the PHI self-reuse case.
11152 Value *InVal = PN->getIncomingValue(i);
11153 if (InVal == PN) {
11154 PredVal = EltPHI;
11155 EltPHI->addIncoming(PredVal, Pred);
11156 continue;
11157 } else if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
11158 // If the incoming value was a PHI, and if it was one of the PHIs we
11159 // already rewrote it, just use the lowered value.
11160 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11161 PredVal = Res;
11162 EltPHI->addIncoming(PredVal, Pred);
11163 continue;
11164 }
11165 }
11166
11167 // Otherwise, do an extract in the predecessor.
11168 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11169 Value *Res = InVal;
11170 if (Offset)
11171 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11172 Offset), "extract");
11173 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11174 PredVal = Res;
11175 EltPHI->addIncoming(Res, Pred);
11176
11177 // If the incoming value was a PHI, and if it was one of the PHIs we are
11178 // rewriting, we will ultimately delete the code we inserted. This
11179 // means we need to revisit that PHI to make sure we extract out the
11180 // needed piece.
11181 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11182 if (PHIsInspected.count(OldInVal)) {
11183 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11184 OldInVal)-PHIsToSlice.begin();
11185 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11186 cast<Instruction>(Res)));
11187 ++UserE;
11188 }
Chris Lattner9956c052009-11-08 19:23:30 +000011189 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011190 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000011191
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011192 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11193 << *EltPHI << '\n');
11194 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000011195 }
Chris Lattner9956c052009-11-08 19:23:30 +000011196
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011197 // Replace the use of this piece with the PHI node.
11198 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000011199 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011200
11201 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11202 // with undefs.
11203 Value *Undef = UndefValue::get(FirstPhi.getType());
11204 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11205 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11206 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000011207}
11208
Chris Lattner473945d2002-05-06 18:06:38 +000011209// PHINode simplification
11210//
Chris Lattner7e708292002-06-25 16:13:24 +000011211Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011212 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011213 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011214
Owen Anderson7e057142006-07-10 22:03:18 +000011215 if (Value *V = PN.hasConstantValue())
11216 return ReplaceInstUsesWith(PN, V);
11217
Owen Anderson7e057142006-07-10 22:03:18 +000011218 // If all PHI operands are the same operation, pull them through the PHI,
11219 // reducing code size.
11220 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011221 isa<Instruction>(PN.getIncomingValue(1)) &&
11222 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11223 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11224 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11225 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011226 PN.getIncomingValue(0)->hasOneUse())
11227 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11228 return Result;
11229
11230 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11231 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11232 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011233 if (PN.hasOneUse()) {
11234 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11235 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011236 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011237 PotentiallyDeadPHIs.insert(&PN);
11238 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011239 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000011240 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011241
11242 // If this phi has a single use, and if that use just computes a value for
11243 // the next iteration of a loop, delete the phi. This occurs with unused
11244 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11245 // common case here is good because the only other things that catch this
11246 // are induction variable analysis (sometimes) and ADCE, which is only run
11247 // late.
11248 if (PHIUser->hasOneUse() &&
11249 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11250 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011251 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011252 }
11253 }
Owen Anderson7e057142006-07-10 22:03:18 +000011254
Chris Lattnercf5008a2007-11-06 21:52:06 +000011255 // We sometimes end up with phi cycles that non-obviously end up being the
11256 // same value, for example:
11257 // z = some value; x = phi (y, z); y = phi (x, z)
11258 // where the phi nodes don't necessarily need to be in the same block. Do a
11259 // quick check to see if the PHI node only contains a single non-phi value, if
11260 // so, scan to see if the phi cycle is actually equal to that value.
11261 {
11262 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11263 // Scan for the first non-phi operand.
11264 while (InValNo != NumOperandVals &&
11265 isa<PHINode>(PN.getIncomingValue(InValNo)))
11266 ++InValNo;
11267
11268 if (InValNo != NumOperandVals) {
11269 Value *NonPhiInVal = PN.getOperand(InValNo);
11270
11271 // Scan the rest of the operands to see if there are any conflicts, if so
11272 // there is no need to recursively scan other phis.
11273 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11274 Value *OpVal = PN.getIncomingValue(InValNo);
11275 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11276 break;
11277 }
11278
11279 // If we scanned over all operands, then we have one unique value plus
11280 // phi values. Scan PHI nodes to see if they all merge in each other or
11281 // the value.
11282 if (InValNo == NumOperandVals) {
11283 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11284 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11285 return ReplaceInstUsesWith(PN, NonPhiInVal);
11286 }
11287 }
11288 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011289
Dan Gohman5b097012009-10-31 14:22:52 +000011290 // If there are multiple PHIs, sort their operands so that they all list
11291 // the blocks in the same order. This will help identical PHIs be eliminated
11292 // by other passes. Other passes shouldn't depend on this for correctness
11293 // however.
11294 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11295 if (&PN != FirstPN)
11296 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011297 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000011298 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11299 if (BBA != BBB) {
11300 Value *VA = PN.getIncomingValue(i);
11301 unsigned j = PN.getBasicBlockIndex(BBB);
11302 Value *VB = PN.getIncomingValue(j);
11303 PN.setIncomingBlock(i, BBB);
11304 PN.setIncomingValue(i, VB);
11305 PN.setIncomingBlock(j, BBA);
11306 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000011307 // NOTE: Instcombine normally would want us to "return &PN" if we
11308 // modified any of the operands of an instruction. However, since we
11309 // aren't adding or removing uses (just rearranging them) we don't do
11310 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000011311 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011312 }
11313
Chris Lattner9956c052009-11-08 19:23:30 +000011314 // If this is an integer PHI and we know that it has an illegal type, see if
11315 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11316 // PHI into the various pieces being extracted. This sort of thing is
11317 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000011318 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000011319 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11320 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11321 return Res;
11322
Chris Lattner60921c92003-12-19 05:58:40 +000011323 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011324}
11325
Chris Lattner7e708292002-06-25 16:13:24 +000011326Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000011327 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000011328 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011329 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011330 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011331
Chris Lattnere87597f2004-10-16 18:11:37 +000011332 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011333 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011334
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011335 bool HasZeroPointerIndex = false;
11336 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11337 HasZeroPointerIndex = C->isNullValue();
11338
11339 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011340 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011341
Chris Lattner28977af2004-04-05 01:30:19 +000011342 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011343 if (TD) {
11344 bool MadeChange = false;
11345 unsigned PtrSize = TD->getPointerSizeInBits();
11346
11347 gep_type_iterator GTI = gep_type_begin(GEP);
11348 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11349 I != E; ++I, ++GTI) {
11350 if (!isa<SequentialType>(*GTI)) continue;
11351
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011352 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011353 // to what we need. If narrower, sign-extend it to what we need. This
11354 // explicit cast can make subsequent optimizations more obvious.
11355 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000011356 if (OpBits == PtrSize)
11357 continue;
11358
Chris Lattner2345d1d2009-08-30 20:01:10 +000011359 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011360 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011361 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011362 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011363 }
Chris Lattner28977af2004-04-05 01:30:19 +000011364
Chris Lattner90ac28c2002-08-02 19:29:35 +000011365 // Combine Indices - If the source pointer to this getelementptr instruction
11366 // is a getelementptr instruction, combine the indices of the two
11367 // getelementptr instructions into a single instruction.
11368 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011369 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011370 // Note that if our source is a gep chain itself that we wait for that
11371 // chain to be resolved before we perform this transformation. This
11372 // avoids us creating a TON of code in some cases.
11373 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011374 if (GetElementPtrInst *SrcGEP =
11375 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11376 if (SrcGEP->getNumOperands() == 2)
11377 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011378
Chris Lattner72588fc2007-02-15 22:48:32 +000011379 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011380
11381 // Find out whether the last index in the source GEP is a sequential idx.
11382 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011383 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11384 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011385 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011386
Chris Lattner90ac28c2002-08-02 19:29:35 +000011387 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011388 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011389 // Replace: gep (gep %P, long B), long A, ...
11390 // With: T = long A+B; gep %P, T, ...
11391 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011392 Value *Sum;
11393 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11394 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011395 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011396 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011397 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011398 Sum = SO1;
11399 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011400 // If they aren't the same type, then the input hasn't been processed
11401 // by the loop above yet (which canonicalizes sequential index types to
11402 // intptr_t). Just avoid transforming this until the input has been
11403 // normalized.
11404 if (SO1->getType() != GO1->getType())
11405 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011406 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000011407 }
Chris Lattner620ce142004-05-07 22:09:22 +000011408
Chris Lattnerab984842009-08-30 05:30:55 +000011409 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011410 if (Src->getNumOperands() == 2) {
11411 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011412 GEP.setOperand(1, Sum);
11413 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011414 }
Chris Lattnerab984842009-08-30 05:30:55 +000011415 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011416 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011417 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011418 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011419 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011420 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011421 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011422 Indices.append(Src->op_begin()+1, Src->op_end());
11423 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011424 }
11425
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011426 if (!Indices.empty())
11427 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11428 Src->isInBounds()) ?
11429 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11430 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011431 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011432 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011433 }
11434
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011435 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11436 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011437 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011438
Chris Lattner2de23192009-08-30 20:38:21 +000011439 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11440 // want to change the gep until the bitcasts are eliminated.
11441 if (getBitCastOperand(X)) {
11442 Worklist.AddValue(PtrOp);
11443 return 0;
11444 }
11445
Chris Lattner963f4ba2009-08-30 20:36:46 +000011446 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11447 // into : GEP [10 x i8]* X, i32 0, ...
11448 //
11449 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11450 // into : GEP i8* X, ...
11451 //
11452 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011453 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011454 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11455 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011456 if (const ArrayType *CATy =
11457 dyn_cast<ArrayType>(CPTy->getElementType())) {
11458 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11459 if (CATy->getElementType() == XTy->getElementType()) {
11460 // -> GEP i8* X, ...
11461 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011462 return cast<GEPOperator>(&GEP)->isInBounds() ?
11463 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11464 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011465 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11466 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011467 }
11468
11469 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011470 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011471 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011472 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011473 // At this point, we know that the cast source type is a pointer
11474 // to an array of the same type as the destination pointer
11475 // array. Because the array type is never stepped over (there
11476 // is a leading zero) we can fold the cast into this GEP.
11477 GEP.setOperand(0, X);
11478 return &GEP;
11479 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011480 }
11481 }
Chris Lattnereed48272005-09-13 00:40:14 +000011482 } else if (GEP.getNumOperands() == 2) {
11483 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011484 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11485 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011486 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11487 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011488 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011489 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11490 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011491 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011492 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011493 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011494 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11495 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011496 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011497 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011498 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011499 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011500
11501 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011502 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011503 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011504 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011505
Owen Anderson1d0be152009-08-13 21:58:54 +000011506 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011507 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011508 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011509
11510 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11511 // allow either a mul, shift, or constant here.
11512 Value *NewIdx = 0;
11513 ConstantInt *Scale = 0;
11514 if (ArrayEltSize == 1) {
11515 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011516 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011517 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011518 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011519 Scale = CI;
11520 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11521 if (Inst->getOpcode() == Instruction::Shl &&
11522 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011523 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11524 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011525 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011526 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011527 NewIdx = Inst->getOperand(0);
11528 } else if (Inst->getOpcode() == Instruction::Mul &&
11529 isa<ConstantInt>(Inst->getOperand(1))) {
11530 Scale = cast<ConstantInt>(Inst->getOperand(1));
11531 NewIdx = Inst->getOperand(0);
11532 }
11533 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011534
Chris Lattner7835cdd2005-09-13 18:36:04 +000011535 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011536 // out, perform the transformation. Note, we don't know whether Scale is
11537 // signed or not. We'll use unsigned version of division/modulo
11538 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011539 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011540 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011541 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011542 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011543 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011544 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11545 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011546 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011547 }
11548
11549 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011550 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011551 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011552 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011553 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11554 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11555 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011556 // The NewGEP must be pointer typed, so must the old one -> BitCast
11557 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011558 }
11559 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011560 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011561 }
Chris Lattner58407792009-01-09 04:53:57 +000011562
Chris Lattner46cd5a12009-01-09 05:44:56 +000011563 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011564 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011565 /// Y = gep X, <...constant indices...>
11566 /// into a gep of the original struct. This is important for SROA and alias
11567 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011568 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011569 if (TD &&
11570 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011571 // Determine how much the GEP moves the pointer. We are guaranteed to get
11572 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000011573 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011574 int64_t Offset = OffsetV->getSExtValue();
11575
11576 // If this GEP instruction doesn't move the pointer, just replace the GEP
11577 // with a bitcast of the real input to the dest type.
11578 if (Offset == 0) {
11579 // If the bitcast is of an allocation, and the allocation will be
11580 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000011581 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000011582 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011583 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11584 if (Instruction *I = visitBitCast(*BCI)) {
11585 if (I != BCI) {
11586 I->takeName(BCI);
11587 BCI->getParent()->getInstList().insert(BCI, I);
11588 ReplaceInstUsesWith(*BCI, I);
11589 }
11590 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011591 }
Chris Lattner58407792009-01-09 04:53:57 +000011592 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011593 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011594 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011595
11596 // Otherwise, if the offset is non-zero, we need to find out if there is a
11597 // field at Offset in 'A's type. If so, we can pull the cast through the
11598 // GEP.
11599 SmallVector<Value*, 8> NewIndices;
11600 const Type *InTy =
11601 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011602 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011603 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11604 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11605 NewIndices.end()) :
11606 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11607 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011608
11609 if (NGEP->getType() == GEP.getType())
11610 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011611 NGEP->takeName(&GEP);
11612 return new BitCastInst(NGEP, GEP.getType());
11613 }
Chris Lattner58407792009-01-09 04:53:57 +000011614 }
11615 }
11616
Chris Lattner8a2a3112001-12-14 16:52:21 +000011617 return 0;
11618}
11619
Victor Hernandez7b929da2009-10-23 21:09:37 +000011620Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000011621 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011622 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011623 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11624 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011625 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000011626 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000011627 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011628 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011629
Chris Lattner0864acf2002-11-04 16:18:53 +000011630 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011631 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011632 //
11633 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000011634 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011635
11636 // Now that I is pointing to the first non-allocation-inst in the block,
11637 // insert our getelementptr instruction...
11638 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011639 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011640 Value *Idx[2];
11641 Idx[0] = NullIdx;
11642 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011643 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11644 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011645
11646 // Now make everything use the getelementptr instead of the original
11647 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011648 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011649 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011650 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011651 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011652 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011653
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011654 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011655 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011656 // Note that we only do this for alloca's, because malloc should allocate
11657 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011658 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011659 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011660
11661 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11662 if (AI.getAlignment() == 0)
11663 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11664 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011665
Chris Lattner0864acf2002-11-04 16:18:53 +000011666 return 0;
11667}
11668
Victor Hernandez66284e02009-10-24 04:23:03 +000011669Instruction *InstCombiner::visitFree(Instruction &FI) {
11670 Value *Op = FI.getOperand(1);
11671
11672 // free undef -> unreachable.
11673 if (isa<UndefValue>(Op)) {
11674 // Insert a new store to null because we cannot modify the CFG here.
11675 new StoreInst(ConstantInt::getTrue(*Context),
11676 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11677 return EraseInstFromFunction(FI);
11678 }
11679
11680 // If we have 'free null' delete the instruction. This can happen in stl code
11681 // when lots of inlining happens.
11682 if (isa<ConstantPointerNull>(Op))
11683 return EraseInstFromFunction(FI);
11684
Victor Hernandez046e78c2009-10-26 23:43:48 +000011685 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000011686 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000011687 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11688 if (Op->hasOneUse() && CI->hasOneUse()) {
11689 EraseInstFromFunction(FI);
11690 EraseInstFromFunction(*CI);
11691 return EraseInstFromFunction(*cast<Instruction>(Op));
11692 }
11693 } else {
11694 // Op is a call to malloc
11695 if (Op->hasOneUse()) {
11696 EraseInstFromFunction(FI);
11697 return EraseInstFromFunction(*cast<Instruction>(Op));
11698 }
11699 }
Dan Gohman7f712a12009-10-27 00:11:02 +000011700 }
Victor Hernandez66284e02009-10-24 04:23:03 +000011701
11702 return 0;
11703}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011704
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011705/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011706static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011707 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011708 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011709 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011710 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011711
Mon P Wang6753f952009-02-07 22:19:29 +000011712 const PointerType *DestTy = cast<PointerType>(CI->getType());
11713 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011714 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011715
11716 // If the address spaces don't match, don't eliminate the cast.
11717 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11718 return 0;
11719
Chris Lattnerb89e0712004-07-13 01:49:43 +000011720 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011721
Reid Spencer42230162007-01-22 05:51:25 +000011722 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011723 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011724 // If the source is an array, the code below will not succeed. Check to
11725 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11726 // constants.
11727 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11728 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11729 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011730 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000011731 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11732 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000011733 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011734 SrcTy = cast<PointerType>(CastOp->getType());
11735 SrcPTy = SrcTy->getElementType();
11736 }
11737
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011738 if (IC.getTargetData() &&
11739 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011740 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011741 // Do not allow turning this into a load of an integer, which is then
11742 // casted to a pointer, this pessimizes pointer analysis a lot.
11743 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011744 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11745 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011746
Chris Lattnerf9527852005-01-31 04:50:46 +000011747 // Okay, we are casting from one integer or pointer type to another of
11748 // the same size. Instead of casting the pointer before the load, cast
11749 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011750 Value *NewLoad =
11751 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011752 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011753 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011754 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011755 }
11756 }
11757 return 0;
11758}
11759
Chris Lattner833b8a42003-06-26 05:06:25 +000011760Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11761 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011762
Dan Gohman9941f742007-07-20 16:34:21 +000011763 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011764 if (TD) {
11765 unsigned KnownAlign =
11766 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11767 if (KnownAlign >
11768 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11769 LI.getAlignment()))
11770 LI.setAlignment(KnownAlign);
11771 }
Dan Gohman9941f742007-07-20 16:34:21 +000011772
Chris Lattner963f4ba2009-08-30 20:36:46 +000011773 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011774 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011775 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011776 return Res;
11777
11778 // None of the following transforms are legal for volatile loads.
11779 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011780
Dan Gohman2276a7b2008-10-15 23:19:35 +000011781 // Do really simple store-to-load forwarding and load CSE, to catch cases
11782 // where there are several consequtive memory accesses to the same location,
11783 // separated by a few arithmetic operations.
11784 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011785 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11786 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011787
Chris Lattner878e4942009-10-22 06:25:11 +000011788 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000011789 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11790 const Value *GEPI0 = GEPI->getOperand(0);
11791 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011792 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011793 // Insert a new store to null instruction before the load to indicate
11794 // that this code is not reachable. We do this instead of inserting
11795 // an unreachable instruction directly because we cannot modify the
11796 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011797 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011798 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011799 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011800 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011801 }
Chris Lattner37366c12005-05-01 04:24:53 +000011802
Chris Lattner878e4942009-10-22 06:25:11 +000011803 // load null/undef -> unreachable
11804 // TODO: Consider a target hook for valid address spaces for this xform.
11805 if (isa<UndefValue>(Op) ||
11806 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11807 // Insert a new store to null instruction before the load to indicate that
11808 // this code is not reachable. We do this instead of inserting an
11809 // unreachable instruction directly because we cannot modify the CFG.
11810 new StoreInst(UndefValue::get(LI.getType()),
11811 Constant::getNullValue(Op->getType()), &LI);
11812 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011813 }
Chris Lattner878e4942009-10-22 06:25:11 +000011814
11815 // Instcombine load (constantexpr_cast global) -> cast (load global)
11816 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11817 if (CE->isCast())
11818 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11819 return Res;
11820
Chris Lattner37366c12005-05-01 04:24:53 +000011821 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011822 // Change select and PHI nodes to select values instead of addresses: this
11823 // helps alias analysis out a lot, allows many others simplifications, and
11824 // exposes redundancy in the code.
11825 //
11826 // Note that we cannot do the transformation unless we know that the
11827 // introduced loads cannot trap! Something like this is valid as long as
11828 // the condition is always false: load (select bool %C, int* null, int* %G),
11829 // but it would not be valid if we transformed it to load from null
11830 // unconditionally.
11831 //
11832 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11833 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011834 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11835 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011836 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11837 SI->getOperand(1)->getName()+".val");
11838 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11839 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011840 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011841 }
11842
Chris Lattner684fe212004-09-23 15:46:00 +000011843 // load (select (cond, null, P)) -> load P
11844 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11845 if (C->isNullValue()) {
11846 LI.setOperand(0, SI->getOperand(2));
11847 return &LI;
11848 }
11849
11850 // load (select (cond, P, null)) -> load P
11851 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11852 if (C->isNullValue()) {
11853 LI.setOperand(0, SI->getOperand(1));
11854 return &LI;
11855 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011856 }
11857 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011858 return 0;
11859}
11860
Reid Spencer55af2b52007-01-19 21:20:31 +000011861/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011862/// when possible. This makes it generally easy to do alias analysis and/or
11863/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011864static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11865 User *CI = cast<User>(SI.getOperand(1));
11866 Value *CastOp = CI->getOperand(0);
11867
11868 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011869 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11870 if (SrcTy == 0) return 0;
11871
11872 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011873
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011874 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11875 return 0;
11876
Chris Lattner3914f722009-01-24 01:00:13 +000011877 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11878 /// to its first element. This allows us to handle things like:
11879 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11880 /// on 32-bit hosts.
11881 SmallVector<Value*, 4> NewGEPIndices;
11882
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011883 // If the source is an array, the code below will not succeed. Check to
11884 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11885 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011886 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11887 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011888 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011889 NewGEPIndices.push_back(Zero);
11890
11891 while (1) {
11892 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011893 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011894 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011895 NewGEPIndices.push_back(Zero);
11896 SrcPTy = STy->getElementType(0);
11897 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11898 NewGEPIndices.push_back(Zero);
11899 SrcPTy = ATy->getElementType();
11900 } else {
11901 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011902 }
Chris Lattner3914f722009-01-24 01:00:13 +000011903 }
11904
Owen Andersondebcb012009-07-29 22:17:13 +000011905 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011906 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011907
11908 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11909 return 0;
11910
Chris Lattner71759c42009-01-16 20:12:52 +000011911 // If the pointers point into different address spaces or if they point to
11912 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011913 if (!IC.getTargetData() ||
11914 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011915 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011916 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11917 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011918 return 0;
11919
11920 // Okay, we are casting from one integer or pointer type to another of
11921 // the same size. Instead of casting the pointer before
11922 // the store, cast the value to be stored.
11923 Value *NewCast;
11924 Value *SIOp0 = SI.getOperand(0);
11925 Instruction::CastOps opcode = Instruction::BitCast;
11926 const Type* CastSrcTy = SIOp0->getType();
11927 const Type* CastDstTy = SrcPTy;
11928 if (isa<PointerType>(CastDstTy)) {
11929 if (CastSrcTy->isInteger())
11930 opcode = Instruction::IntToPtr;
11931 } else if (isa<IntegerType>(CastDstTy)) {
11932 if (isa<PointerType>(SIOp0->getType()))
11933 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011934 }
Chris Lattner3914f722009-01-24 01:00:13 +000011935
11936 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11937 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011938 if (!NewGEPIndices.empty())
11939 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11940 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011941
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011942 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11943 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011944 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011945}
11946
Chris Lattner4aebaee2008-11-27 08:56:30 +000011947/// equivalentAddressValues - Test if A and B will obviously have the same
11948/// value. This includes recognizing that %t0 and %t1 will have the same
11949/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011950/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011951/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011952/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011953/// %t2 = load i32* %t1
11954///
11955static bool equivalentAddressValues(Value *A, Value *B) {
11956 // Test if the values are trivially equivalent.
11957 if (A == B) return true;
11958
11959 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011960 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11961 // its only used to compare two uses within the same basic block, which
11962 // means that they'll always either have the same value or one of them
11963 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011964 if (isa<BinaryOperator>(A) ||
11965 isa<CastInst>(A) ||
11966 isa<PHINode>(A) ||
11967 isa<GetElementPtrInst>(A))
11968 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011969 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011970 return true;
11971
11972 // Otherwise they may not be equivalent.
11973 return false;
11974}
11975
Dale Johannesen4945c652009-03-03 21:26:39 +000011976// If this instruction has two uses, one of which is a llvm.dbg.declare,
11977// return the llvm.dbg.declare.
11978DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11979 if (!V->hasNUses(2))
11980 return 0;
11981 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11982 UI != E; ++UI) {
11983 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11984 return DI;
11985 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11986 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11987 return DI;
11988 }
11989 }
11990 return 0;
11991}
11992
Chris Lattner2f503e62005-01-31 05:36:43 +000011993Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11994 Value *Val = SI.getOperand(0);
11995 Value *Ptr = SI.getOperand(1);
11996
11997 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011998 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011999 ++NumCombined;
12000 return 0;
12001 }
Chris Lattner836692d2007-01-15 06:51:56 +000012002
12003 // If the RHS is an alloca with a single use, zapify the store, making the
12004 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000012005 // If the RHS is an alloca with a two uses, the other one being a
12006 // llvm.dbg.declare, zapify the store and the declare, making the
12007 // alloca dead. We must do this to prevent declare's from affecting
12008 // codegen.
12009 if (!SI.isVolatile()) {
12010 if (Ptr->hasOneUse()) {
12011 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000012012 EraseInstFromFunction(SI);
12013 ++NumCombined;
12014 return 0;
12015 }
Dale Johannesen4945c652009-03-03 21:26:39 +000012016 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12017 if (isa<AllocaInst>(GEP->getOperand(0))) {
12018 if (GEP->getOperand(0)->hasOneUse()) {
12019 EraseInstFromFunction(SI);
12020 ++NumCombined;
12021 return 0;
12022 }
12023 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12024 EraseInstFromFunction(*DI);
12025 EraseInstFromFunction(SI);
12026 ++NumCombined;
12027 return 0;
12028 }
12029 }
12030 }
12031 }
12032 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12033 EraseInstFromFunction(*DI);
12034 EraseInstFromFunction(SI);
12035 ++NumCombined;
12036 return 0;
12037 }
Chris Lattner836692d2007-01-15 06:51:56 +000012038 }
Chris Lattner2f503e62005-01-31 05:36:43 +000012039
Dan Gohman9941f742007-07-20 16:34:21 +000012040 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012041 if (TD) {
12042 unsigned KnownAlign =
12043 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12044 if (KnownAlign >
12045 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12046 SI.getAlignment()))
12047 SI.setAlignment(KnownAlign);
12048 }
Dan Gohman9941f742007-07-20 16:34:21 +000012049
Dale Johannesenacb51a32009-03-03 01:43:03 +000012050 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000012051 // stores to the same location, separated by a few arithmetic operations. This
12052 // situation often occurs with bitfield accesses.
12053 BasicBlock::iterator BBI = &SI;
12054 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12055 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000012056 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012057 // Don't count debug info directives, lest they affect codegen,
12058 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12059 // It is necessary for correctness to skip those that feed into a
12060 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000012061 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012062 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000012063 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000012064 continue;
12065 }
Chris Lattner9ca96412006-02-08 03:25:32 +000012066
12067 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12068 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000012069 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12070 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012071 ++NumDeadStore;
12072 ++BBI;
12073 EraseInstFromFunction(*PrevSI);
12074 continue;
12075 }
12076 break;
12077 }
12078
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012079 // If this is a load, we have to stop. However, if the loaded value is from
12080 // the pointer we're loading and is producing the pointer we're storing,
12081 // then *this* store is dead (X = load P; store X -> P).
12082 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000012083 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12084 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012085 EraseInstFromFunction(SI);
12086 ++NumCombined;
12087 return 0;
12088 }
12089 // Otherwise, this is a load from some other location. Stores before it
12090 // may not be dead.
12091 break;
12092 }
12093
Chris Lattner9ca96412006-02-08 03:25:32 +000012094 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000012095 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000012096 break;
12097 }
12098
12099
12100 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000012101
12102 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000012103 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000012104 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012105 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000012106 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000012107 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000012108 ++NumCombined;
12109 }
12110 return 0; // Do not modify these!
12111 }
12112
12113 // store undef, Ptr -> noop
12114 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012115 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012116 ++NumCombined;
12117 return 0;
12118 }
12119
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012120 // If the pointer destination is a cast, see if we can fold the cast into the
12121 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012122 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012123 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12124 return Res;
12125 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000012126 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012127 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12128 return Res;
12129
Chris Lattner408902b2005-09-12 23:23:25 +000012130
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012131 // If this store is the last instruction in the basic block (possibly
12132 // excepting debug info instructions and the pointer bitcasts that feed
12133 // into them), and if the block ends with an unconditional branch, try
12134 // to move it to the successor block.
12135 BBI = &SI;
12136 do {
12137 ++BBI;
12138 } while (isa<DbgInfoIntrinsic>(BBI) ||
12139 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000012140 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012141 if (BI->isUnconditional())
12142 if (SimplifyStoreAtEndOfBlock(SI))
12143 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000012144
Chris Lattner2f503e62005-01-31 05:36:43 +000012145 return 0;
12146}
12147
Chris Lattner3284d1f2007-04-15 00:07:55 +000012148/// SimplifyStoreAtEndOfBlock - Turn things like:
12149/// if () { *P = v1; } else { *P = v2 }
12150/// into a phi node with a store in the successor.
12151///
Chris Lattner31755a02007-04-15 01:02:18 +000012152/// Simplify things like:
12153/// *P = v1; if () { *P = v2; }
12154/// into a phi node with a store in the successor.
12155///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012156bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12157 BasicBlock *StoreBB = SI.getParent();
12158
12159 // Check to see if the successor block has exactly two incoming edges. If
12160 // so, see if the other predecessor contains a store to the same location.
12161 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012162 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012163
12164 // Determine whether Dest has exactly two predecessors and, if so, compute
12165 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012166 pred_iterator PI = pred_begin(DestBB);
12167 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012168 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012169 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012170 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012171 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012172 return false;
12173
12174 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012175 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012176 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012177 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012178 }
Chris Lattner31755a02007-04-15 01:02:18 +000012179 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012180 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012181
12182 // Bail out if all the relevant blocks aren't distinct (this can happen,
12183 // for example, if SI is in an infinite loop)
12184 if (StoreBB == DestBB || OtherBB == DestBB)
12185 return false;
12186
Chris Lattner31755a02007-04-15 01:02:18 +000012187 // Verify that the other block ends in a branch and is not otherwise empty.
12188 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012189 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012190 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012191 return false;
12192
Chris Lattner31755a02007-04-15 01:02:18 +000012193 // If the other block ends in an unconditional branch, check for the 'if then
12194 // else' case. there is an instruction before the branch.
12195 StoreInst *OtherStore = 0;
12196 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012197 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012198 // Skip over debugging info.
12199 while (isa<DbgInfoIntrinsic>(BBI) ||
12200 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12201 if (BBI==OtherBB->begin())
12202 return false;
12203 --BBI;
12204 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012205 // If this isn't a store, isn't a store to the same location, or if the
12206 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012207 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012208 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12209 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012210 return false;
12211 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012212 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012213 // destinations is StoreBB, then we have the if/then case.
12214 if (OtherBr->getSuccessor(0) != StoreBB &&
12215 OtherBr->getSuccessor(1) != StoreBB)
12216 return false;
12217
12218 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012219 // if/then triangle. See if there is a store to the same ptr as SI that
12220 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012221 for (;; --BBI) {
12222 // Check to see if we find the matching store.
12223 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012224 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12225 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012226 return false;
12227 break;
12228 }
Eli Friedman6903a242008-06-13 22:02:12 +000012229 // If we find something that may be using or overwriting the stored
12230 // value, or if we run out of instructions, we can't do the xform.
12231 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012232 BBI == OtherBB->begin())
12233 return false;
12234 }
12235
12236 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012237 // make sure nothing reads or overwrites the stored value in
12238 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012239 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12240 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012241 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012242 return false;
12243 }
12244 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012245
Chris Lattner31755a02007-04-15 01:02:18 +000012246 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012247 Value *MergedVal = OtherStore->getOperand(0);
12248 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012249 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012250 PN->reserveOperandSpace(2);
12251 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012252 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12253 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012254 }
12255
12256 // Advance to a place where it is safe to insert the new store and
12257 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012258 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012259 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012260 OtherStore->isVolatile(),
12261 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012262
12263 // Nuke the old stores.
12264 EraseInstFromFunction(SI);
12265 EraseInstFromFunction(*OtherStore);
12266 ++NumCombined;
12267 return true;
12268}
12269
Chris Lattner2f503e62005-01-31 05:36:43 +000012270
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012271Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12272 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012273 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012274 BasicBlock *TrueDest;
12275 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012276 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012277 !isa<Constant>(X)) {
12278 // Swap Destinations and condition...
12279 BI.setCondition(X);
12280 BI.setSuccessor(0, FalseDest);
12281 BI.setSuccessor(1, TrueDest);
12282 return &BI;
12283 }
12284
Reid Spencere4d87aa2006-12-23 06:05:41 +000012285 // Cannonicalize fcmp_one -> fcmp_oeq
12286 FCmpInst::Predicate FPred; Value *Y;
12287 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012288 TrueDest, FalseDest)) &&
12289 BI.getCondition()->hasOneUse())
12290 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12291 FPred == FCmpInst::FCMP_OGE) {
12292 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12293 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12294
12295 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012296 BI.setSuccessor(0, FalseDest);
12297 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012298 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012299 return &BI;
12300 }
12301
12302 // Cannonicalize icmp_ne -> icmp_eq
12303 ICmpInst::Predicate IPred;
12304 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012305 TrueDest, FalseDest)) &&
12306 BI.getCondition()->hasOneUse())
12307 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12308 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12309 IPred == ICmpInst::ICMP_SGE) {
12310 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12311 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12312 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012313 BI.setSuccessor(0, FalseDest);
12314 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012315 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012316 return &BI;
12317 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012318
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012319 return 0;
12320}
Chris Lattner0864acf2002-11-04 16:18:53 +000012321
Chris Lattner46238a62004-07-03 00:26:11 +000012322Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12323 Value *Cond = SI.getCondition();
12324 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12325 if (I->getOpcode() == Instruction::Add)
12326 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12327 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12328 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012329 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012330 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012331 AddRHS));
12332 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012333 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012334 return &SI;
12335 }
12336 }
12337 return 0;
12338}
12339
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012340Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012341 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012342
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012343 if (!EV.hasIndices())
12344 return ReplaceInstUsesWith(EV, Agg);
12345
12346 if (Constant *C = dyn_cast<Constant>(Agg)) {
12347 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012348 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012349
12350 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012351 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012352
12353 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12354 // Extract the element indexed by the first index out of the constant
12355 Value *V = C->getOperand(*EV.idx_begin());
12356 if (EV.getNumIndices() > 1)
12357 // Extract the remaining indices out of the constant indexed by the
12358 // first index
12359 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12360 else
12361 return ReplaceInstUsesWith(EV, V);
12362 }
12363 return 0; // Can't handle other constants
12364 }
12365 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12366 // We're extracting from an insertvalue instruction, compare the indices
12367 const unsigned *exti, *exte, *insi, *inse;
12368 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12369 exte = EV.idx_end(), inse = IV->idx_end();
12370 exti != exte && insi != inse;
12371 ++exti, ++insi) {
12372 if (*insi != *exti)
12373 // The insert and extract both reference distinctly different elements.
12374 // This means the extract is not influenced by the insert, and we can
12375 // replace the aggregate operand of the extract with the aggregate
12376 // operand of the insert. i.e., replace
12377 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12378 // %E = extractvalue { i32, { i32 } } %I, 0
12379 // with
12380 // %E = extractvalue { i32, { i32 } } %A, 0
12381 return ExtractValueInst::Create(IV->getAggregateOperand(),
12382 EV.idx_begin(), EV.idx_end());
12383 }
12384 if (exti == exte && insi == inse)
12385 // Both iterators are at the end: Index lists are identical. Replace
12386 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12387 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12388 // with "i32 42"
12389 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12390 if (exti == exte) {
12391 // The extract list is a prefix of the insert list. i.e. replace
12392 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12393 // %E = extractvalue { i32, { i32 } } %I, 1
12394 // with
12395 // %X = extractvalue { i32, { i32 } } %A, 1
12396 // %E = insertvalue { i32 } %X, i32 42, 0
12397 // by switching the order of the insert and extract (though the
12398 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012399 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12400 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012401 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12402 insi, inse);
12403 }
12404 if (insi == inse)
12405 // The insert list is a prefix of the extract list
12406 // We can simply remove the common indices from the extract and make it
12407 // operate on the inserted value instead of the insertvalue result.
12408 // i.e., replace
12409 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12410 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12411 // with
12412 // %E extractvalue { i32 } { i32 42 }, 0
12413 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12414 exti, exte);
12415 }
Chris Lattner7e606e22009-11-09 07:07:56 +000012416 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12417 // We're extracting from an intrinsic, see if we're the only user, which
12418 // allows us to simplify multiple result intrinsics to simpler things that
12419 // just get one value..
12420 if (II->hasOneUse()) {
12421 // Check if we're grabbing the overflow bit or the result of a 'with
12422 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12423 // and replace it with a traditional binary instruction.
12424 switch (II->getIntrinsicID()) {
12425 case Intrinsic::uadd_with_overflow:
12426 case Intrinsic::sadd_with_overflow:
12427 if (*EV.idx_begin() == 0) { // Normal result.
12428 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12429 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12430 EraseInstFromFunction(*II);
12431 return BinaryOperator::CreateAdd(LHS, RHS);
12432 }
12433 break;
12434 case Intrinsic::usub_with_overflow:
12435 case Intrinsic::ssub_with_overflow:
12436 if (*EV.idx_begin() == 0) { // Normal result.
12437 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12438 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12439 EraseInstFromFunction(*II);
12440 return BinaryOperator::CreateSub(LHS, RHS);
12441 }
12442 break;
12443 case Intrinsic::umul_with_overflow:
12444 case Intrinsic::smul_with_overflow:
12445 if (*EV.idx_begin() == 0) { // Normal result.
12446 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12447 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12448 EraseInstFromFunction(*II);
12449 return BinaryOperator::CreateMul(LHS, RHS);
12450 }
12451 break;
12452 default:
12453 break;
12454 }
12455 }
12456 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012457 // Can't simplify extracts from other values. Note that nested extracts are
12458 // already simplified implicitely by the above (extract ( extract (insert) )
12459 // will be translated into extract ( insert ( extract ) ) first and then just
12460 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012461 return 0;
12462}
12463
Chris Lattner220b0cf2006-03-05 00:22:33 +000012464/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12465/// is to leave as a vector operation.
12466static bool CheapToScalarize(Value *V, bool isConstant) {
12467 if (isa<ConstantAggregateZero>(V))
12468 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012469 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012470 if (isConstant) return true;
12471 // If all elts are the same, we can extract.
12472 Constant *Op0 = C->getOperand(0);
12473 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12474 if (C->getOperand(i) != Op0)
12475 return false;
12476 return true;
12477 }
12478 Instruction *I = dyn_cast<Instruction>(V);
12479 if (!I) return false;
12480
12481 // Insert element gets simplified to the inserted element or is deleted if
12482 // this is constant idx extract element and its a constant idx insertelt.
12483 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12484 isa<ConstantInt>(I->getOperand(2)))
12485 return true;
12486 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12487 return true;
12488 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12489 if (BO->hasOneUse() &&
12490 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12491 CheapToScalarize(BO->getOperand(1), isConstant)))
12492 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012493 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12494 if (CI->hasOneUse() &&
12495 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12496 CheapToScalarize(CI->getOperand(1), isConstant)))
12497 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012498
12499 return false;
12500}
12501
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012502/// Read and decode a shufflevector mask.
12503///
12504/// It turns undef elements into values that are larger than the number of
12505/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012506static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12507 unsigned NElts = SVI->getType()->getNumElements();
12508 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12509 return std::vector<unsigned>(NElts, 0);
12510 if (isa<UndefValue>(SVI->getOperand(2)))
12511 return std::vector<unsigned>(NElts, 2*NElts);
12512
12513 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012514 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012515 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12516 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012517 Result.push_back(NElts*2); // undef -> 8
12518 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012519 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012520 return Result;
12521}
12522
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012523/// FindScalarElement - Given a vector and an element number, see if the scalar
12524/// value is already around as a register, for example if it were inserted then
12525/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012526static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012527 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012528 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12529 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012530 unsigned Width = PTy->getNumElements();
12531 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012532 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012533
12534 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012535 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012536 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012537 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012538 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012539 return CP->getOperand(EltNo);
12540 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12541 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012542 if (!isa<ConstantInt>(III->getOperand(2)))
12543 return 0;
12544 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012545
12546 // If this is an insert to the element we are looking for, return the
12547 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012548 if (EltNo == IIElt)
12549 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012550
12551 // Otherwise, the insertelement doesn't modify the value, recurse on its
12552 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012553 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012554 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012555 unsigned LHSWidth =
12556 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012557 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012558 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012559 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012560 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012561 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012562 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012563 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012564 }
12565
12566 // Otherwise, we don't know.
12567 return 0;
12568}
12569
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012570Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012571 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012572 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012573 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012574
Dan Gohman07a96762007-07-16 14:29:03 +000012575 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012576 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012577 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012578
Reid Spencer9d6565a2007-02-15 02:26:10 +000012579 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012580 // If vector val is constant with all elements the same, replace EI with
12581 // that element. When the elements are not identical, we cannot replace yet
12582 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012583 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012584 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012585 if (C->getOperand(i) != op0) {
12586 op0 = 0;
12587 break;
12588 }
12589 if (op0)
12590 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012591 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012592
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012593 // If extracting a specified index from the vector, see if we can recursively
12594 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012595 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012596 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012597 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012598
12599 // If this is extracting an invalid index, turn this into undef, to avoid
12600 // crashing the code below.
12601 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012602 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012603
Chris Lattner867b99f2006-10-05 06:55:50 +000012604 // This instruction only demands the single element from the input vector.
12605 // If the input vector has a single use, simplify it based on this use
12606 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012607 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012608 APInt UndefElts(VectorWidth, 0);
12609 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012610 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012611 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012612 EI.setOperand(0, V);
12613 return &EI;
12614 }
12615 }
12616
Owen Andersond672ecb2009-07-03 00:17:18 +000012617 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012618 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012619
12620 // If the this extractelement is directly using a bitcast from a vector of
12621 // the same number of elements, see if we can find the source element from
12622 // it. In this case, we will end up needing to bitcast the scalars.
12623 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12624 if (const VectorType *VT =
12625 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12626 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012627 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12628 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012629 return new BitCastInst(Elt, EI.getType());
12630 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012631 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012632
Chris Lattner73fa49d2006-05-25 22:53:38 +000012633 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012634 // Push extractelement into predecessor operation if legal and
12635 // profitable to do so
12636 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12637 if (I->hasOneUse() &&
12638 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12639 Value *newEI0 =
12640 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12641 EI.getName()+".lhs");
12642 Value *newEI1 =
12643 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12644 EI.getName()+".rhs");
12645 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012646 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012647 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012648 // Extracting the inserted element?
12649 if (IE->getOperand(2) == EI.getOperand(1))
12650 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12651 // If the inserted and extracted elements are constants, they must not
12652 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012653 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012654 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012655 EI.setOperand(0, IE->getOperand(0));
12656 return &EI;
12657 }
12658 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12659 // If this is extracting an element from a shufflevector, figure out where
12660 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012661 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12662 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012663 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012664 unsigned LHSWidth =
12665 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12666
12667 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012668 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012669 else if (SrcIdx < LHSWidth*2) {
12670 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012671 Src = SVI->getOperand(1);
12672 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012673 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012674 }
Eric Christophera3500da2009-07-25 02:28:41 +000012675 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012676 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12677 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012678 }
12679 }
Eli Friedman2451a642009-07-18 23:06:53 +000012680 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012681 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012682 return 0;
12683}
12684
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012685/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12686/// elements from either LHS or RHS, return the shuffle mask and true.
12687/// Otherwise, return false.
12688static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012689 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012690 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012691 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12692 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012693 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012694
12695 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012696 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012697 return true;
12698 } else if (V == LHS) {
12699 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012700 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012701 return true;
12702 } else if (V == RHS) {
12703 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012704 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012705 return true;
12706 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12707 // If this is an insert of an extract from some other vector, include it.
12708 Value *VecOp = IEI->getOperand(0);
12709 Value *ScalarOp = IEI->getOperand(1);
12710 Value *IdxOp = IEI->getOperand(2);
12711
Chris Lattnerd929f062006-04-27 21:14:21 +000012712 if (!isa<ConstantInt>(IdxOp))
12713 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012714 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012715
12716 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12717 // Okay, we can handle this if the vector we are insertinting into is
12718 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012719 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012720 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012721 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012722 return true;
12723 }
12724 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12725 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012726 EI->getOperand(0)->getType() == V->getType()) {
12727 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012728 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012729
12730 // This must be extracting from either LHS or RHS.
12731 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12732 // Okay, we can handle this if the vector we are insertinting into is
12733 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012734 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012735 // If so, update the mask to reflect the inserted value.
12736 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012737 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012738 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012739 } else {
12740 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012741 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012742 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012743
12744 }
12745 return true;
12746 }
12747 }
12748 }
12749 }
12750 }
12751 // TODO: Handle shufflevector here!
12752
12753 return false;
12754}
12755
12756/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12757/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12758/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012759static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012760 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012761 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012762 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012763 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012764 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012765
12766 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012767 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012768 return V;
12769 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012770 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012771 return V;
12772 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12773 // If this is an insert of an extract from some other vector, include it.
12774 Value *VecOp = IEI->getOperand(0);
12775 Value *ScalarOp = IEI->getOperand(1);
12776 Value *IdxOp = IEI->getOperand(2);
12777
12778 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12779 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12780 EI->getOperand(0)->getType() == V->getType()) {
12781 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012782 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12783 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012784
12785 // Either the extracted from or inserted into vector must be RHSVec,
12786 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012787 if (EI->getOperand(0) == RHS || RHS == 0) {
12788 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012789 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012790 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012791 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012792 return V;
12793 }
12794
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012795 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012796 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12797 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012798 // Everything but the extracted element is replaced with the RHS.
12799 for (unsigned i = 0; i != NumElts; ++i) {
12800 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012801 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012802 }
12803 return V;
12804 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012805
12806 // If this insertelement is a chain that comes from exactly these two
12807 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012808 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12809 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012810 return EI->getOperand(0);
12811
Chris Lattnerefb47352006-04-15 01:39:45 +000012812 }
12813 }
12814 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012815 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012816
12817 // Otherwise, can't do anything fancy. Return an identity vector.
12818 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012819 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012820 return V;
12821}
12822
12823Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12824 Value *VecOp = IE.getOperand(0);
12825 Value *ScalarOp = IE.getOperand(1);
12826 Value *IdxOp = IE.getOperand(2);
12827
Chris Lattner599ded12007-04-09 01:11:16 +000012828 // Inserting an undef or into an undefined place, remove this.
12829 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12830 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012831
Chris Lattnerefb47352006-04-15 01:39:45 +000012832 // If the inserted element was extracted from some other vector, and if the
12833 // indexes are constant, try to turn this into a shufflevector operation.
12834 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12835 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12836 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012837 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012838 unsigned ExtractedIdx =
12839 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012840 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012841
12842 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12843 return ReplaceInstUsesWith(IE, VecOp);
12844
12845 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012846 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012847
12848 // If we are extracting a value from a vector, then inserting it right
12849 // back into the same place, just use the input vector.
12850 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12851 return ReplaceInstUsesWith(IE, VecOp);
12852
Chris Lattnerefb47352006-04-15 01:39:45 +000012853 // If this insertelement isn't used by some other insertelement, turn it
12854 // (and any insertelements it points to), into one big shuffle.
12855 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12856 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012857 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012858 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012859 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012860 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012861 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012862 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012863 }
12864 }
12865 }
12866
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012867 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12868 APInt UndefElts(VWidth, 0);
12869 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12870 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12871 return &IE;
12872
Chris Lattnerefb47352006-04-15 01:39:45 +000012873 return 0;
12874}
12875
12876
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012877Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12878 Value *LHS = SVI.getOperand(0);
12879 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012880 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012881
12882 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012883
Chris Lattner867b99f2006-10-05 06:55:50 +000012884 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012885 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012886 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012887
Dan Gohman488fbfc2008-09-09 18:11:14 +000012888 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012889
12890 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12891 return 0;
12892
Evan Cheng388df622009-02-03 10:05:09 +000012893 APInt UndefElts(VWidth, 0);
12894 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12895 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012896 LHS = SVI.getOperand(0);
12897 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012898 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012899 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012900
Chris Lattner863bcff2006-05-25 23:48:38 +000012901 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12902 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12903 if (LHS == RHS || isa<UndefValue>(LHS)) {
12904 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012905 // shuffle(undef,undef,mask) -> undef.
12906 return ReplaceInstUsesWith(SVI, LHS);
12907 }
12908
Chris Lattner863bcff2006-05-25 23:48:38 +000012909 // Remap any references to RHS to use LHS.
12910 std::vector<Constant*> Elts;
12911 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012912 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012913 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012914 else {
12915 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012916 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012917 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012918 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012919 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012920 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012921 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012922 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012923 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012924 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012925 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012926 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012927 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012928 LHS = SVI.getOperand(0);
12929 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012930 MadeChange = true;
12931 }
12932
Chris Lattner7b2e27922006-05-26 00:29:06 +000012933 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012934 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012935
Chris Lattner863bcff2006-05-25 23:48:38 +000012936 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12937 if (Mask[i] >= e*2) continue; // Ignore undef values.
12938 // Is this an identity shuffle of the LHS value?
12939 isLHSID &= (Mask[i] == i);
12940
12941 // Is this an identity shuffle of the RHS value?
12942 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012943 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012944
Chris Lattner863bcff2006-05-25 23:48:38 +000012945 // Eliminate identity shuffles.
12946 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12947 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012948
Chris Lattner7b2e27922006-05-26 00:29:06 +000012949 // If the LHS is a shufflevector itself, see if we can combine it with this
12950 // one without producing an unusual shuffle. Here we are really conservative:
12951 // we are absolutely afraid of producing a shuffle mask not in the input
12952 // program, because the code gen may not be smart enough to turn a merged
12953 // shuffle into two specific shuffles: it may produce worse code. As such,
12954 // we only merge two shuffles if the result is one of the two input shuffle
12955 // masks. In this case, merging the shuffles just removes one instruction,
12956 // which we know is safe. This is good for things like turning:
12957 // (splat(splat)) -> splat.
12958 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12959 if (isa<UndefValue>(RHS)) {
12960 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12961
12962 std::vector<unsigned> NewMask;
12963 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12964 if (Mask[i] >= 2*e)
12965 NewMask.push_back(2*e);
12966 else
12967 NewMask.push_back(LHSMask[Mask[i]]);
12968
12969 // If the result mask is equal to the src shuffle or this shuffle mask, do
12970 // the replacement.
12971 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012972 unsigned LHSInNElts =
12973 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012974 std::vector<Constant*> Elts;
12975 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012976 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012977 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012978 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012979 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012980 }
12981 }
12982 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12983 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012984 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012985 }
12986 }
12987 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012988
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012989 return MadeChange ? &SVI : 0;
12990}
12991
12992
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012993
Chris Lattnerea1c4542004-12-08 23:43:58 +000012994
12995/// TryToSinkInstruction - Try to move the specified instruction from its
12996/// current block into the beginning of DestBlock, which can only happen if it's
12997/// safe to move the instruction past all of the instructions between it and the
12998/// end of its block.
12999static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13000 assert(I->hasOneUse() && "Invariants didn't hold!");
13001
Chris Lattner108e9022005-10-27 17:13:11 +000013002 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000013003 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000013004 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000013005
Chris Lattnerea1c4542004-12-08 23:43:58 +000013006 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000013007 if (isa<AllocaInst>(I) && I->getParent() ==
13008 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013009 return false;
13010
Chris Lattner96a52a62004-12-09 07:14:34 +000013011 // We can only sink load instructions if there is nothing between the load and
13012 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000013013 if (I->mayReadFromMemory()) {
13014 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000013015 Scan != E; ++Scan)
13016 if (Scan->mayWriteToMemory())
13017 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000013018 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000013019
Dan Gohman02dea8b2008-05-23 21:05:58 +000013020 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000013021
Dale Johannesenbd8e6502009-03-03 01:09:07 +000013022 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000013023 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013024 ++NumSunkInst;
13025 return true;
13026}
13027
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013028
13029/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13030/// all reachable code to the worklist.
13031///
13032/// This has a couple of tricks to make the code faster and more powerful. In
13033/// particular, we constant fold and DCE instructions as we go, to avoid adding
13034/// them to the worklist (this significantly speeds up instcombine on code where
13035/// many instructions are dead or constant). Additionally, if we find a branch
13036/// whose condition is a known constant, we only visit the reachable successors.
13037///
Chris Lattner2ee743b2009-10-15 04:59:28 +000013038static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000013039 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000013040 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013041 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000013042 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000013043 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000013044 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000013045
13046 std::vector<Instruction*> InstrsForInstCombineWorklist;
13047 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013048
Chris Lattner2ee743b2009-10-15 04:59:28 +000013049 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13050
Chris Lattner2c7718a2007-03-23 19:17:18 +000013051 while (!Worklist.empty()) {
13052 BB = Worklist.back();
13053 Worklist.pop_back();
13054
13055 // We have now visited this block! If we've already been here, ignore it.
13056 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000013057
Chris Lattner2c7718a2007-03-23 19:17:18 +000013058 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13059 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013060
Chris Lattner2c7718a2007-03-23 19:17:18 +000013061 // DCE instruction if trivially dead.
13062 if (isInstructionTriviallyDead(Inst)) {
13063 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000013064 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000013065 Inst->eraseFromParent();
13066 continue;
13067 }
13068
13069 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013070 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013071 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013072 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13073 << *Inst << '\n');
13074 Inst->replaceAllUsesWith(C);
13075 ++NumConstProp;
13076 Inst->eraseFromParent();
13077 continue;
13078 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000013079
13080
13081
13082 if (TD) {
13083 // See if we can constant fold its operands.
13084 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13085 i != e; ++i) {
13086 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13087 if (CE == 0) continue;
13088
13089 // If we already folded this constant, don't try again.
13090 if (!FoldedConstants.insert(CE))
13091 continue;
13092
Chris Lattner7b550cc2009-11-06 04:27:31 +000013093 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000013094 if (NewC && NewC != CE) {
13095 *i = NewC;
13096 MadeIRChange = true;
13097 }
13098 }
13099 }
13100
Devang Patel7fe1dec2008-11-19 18:56:50 +000013101
Chris Lattner67f7d542009-10-12 03:58:40 +000013102 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013103 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000013104
13105 // Recursively visit successors. If this is a branch or switch on a
13106 // constant, only visit the reachable successor.
13107 TerminatorInst *TI = BB->getTerminator();
13108 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13109 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13110 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000013111 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013112 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013113 continue;
13114 }
13115 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13116 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13117 // See if this is an explicit destination.
13118 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13119 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000013120 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013121 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013122 continue;
13123 }
13124
13125 // Otherwise it is the default destination.
13126 Worklist.push_back(SI->getSuccessor(0));
13127 continue;
13128 }
13129 }
13130
13131 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13132 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013133 }
Chris Lattner67f7d542009-10-12 03:58:40 +000013134
13135 // Once we've found all of the instructions to add to instcombine's worklist,
13136 // add them in reverse order. This way instcombine will visit from the top
13137 // of the function down. This jives well with the way that it adds all uses
13138 // of instructions to the worklist after doing a transformation, thus avoiding
13139 // some N^2 behavior in pathological cases.
13140 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13141 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000013142
13143 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013144}
13145
Chris Lattnerec9c3582007-03-03 02:04:50 +000013146bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013147 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013148
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000013149 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13150 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000013151
Chris Lattnerb3d59702005-07-07 20:40:38 +000013152 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013153 // Do a depth-first traversal of the function, populate the worklist with
13154 // the reachable instructions. Ignore blocks that are not reachable. Keep
13155 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000013156 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000013157 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000013158
Chris Lattnerb3d59702005-07-07 20:40:38 +000013159 // Do a quick scan over the function. If we find any blocks that are
13160 // unreachable, remove any instructions inside of them. This prevents
13161 // the instcombine code from having to deal with some bad special cases.
13162 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13163 if (!Visited.count(BB)) {
13164 Instruction *Term = BB->getTerminator();
13165 while (Term != BB->begin()) { // Remove instrs bottom-up
13166 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000013167
Chris Lattnerbdff5482009-08-23 04:37:46 +000013168 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000013169 // A debug intrinsic shouldn't force another iteration if we weren't
13170 // going to do one without it.
13171 if (!isa<DbgInfoIntrinsic>(I)) {
13172 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013173 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000013174 }
Devang Patel228ebd02009-10-13 22:56:32 +000013175
Devang Patel228ebd02009-10-13 22:56:32 +000013176 // If I is not void type then replaceAllUsesWith undef.
13177 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000013178 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000013179 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013180 I->eraseFromParent();
13181 }
13182 }
13183 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013184
Chris Lattner873ff012009-08-30 05:55:36 +000013185 while (!Worklist.isEmpty()) {
13186 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013187 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013188
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013189 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013190 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013191 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000013192 EraseInstFromFunction(*I);
13193 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013194 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013195 continue;
13196 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013197
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013198 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013199 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013200 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013201 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000013202
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013203 // Add operands to the worklist.
13204 ReplaceInstUsesWith(*I, C);
13205 ++NumConstProp;
13206 EraseInstFromFunction(*I);
13207 MadeIRChange = true;
13208 continue;
13209 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013210
Chris Lattnerea1c4542004-12-08 23:43:58 +000013211 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013212 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013213 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000013214 Instruction *UserInst = cast<Instruction>(I->use_back());
13215 BasicBlock *UserParent;
13216
13217 // Get the block the use occurs in.
13218 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13219 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13220 else
13221 UserParent = UserInst->getParent();
13222
Chris Lattnerea1c4542004-12-08 23:43:58 +000013223 if (UserParent != BB) {
13224 bool UserIsSuccessor = false;
13225 // See if the user is one of our successors.
13226 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13227 if (*SI == UserParent) {
13228 UserIsSuccessor = true;
13229 break;
13230 }
13231
13232 // If the user is one of our immediate successors, and if that successor
13233 // only has us as a predecessors (we'd have to split the critical edge
13234 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000013235 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013236 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013237 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013238 }
13239 }
13240
Chris Lattner74381062009-08-30 07:44:24 +000013241 // Now that we have an instruction, try combining it to simplify it.
13242 Builder->SetInsertPoint(I->getParent(), I);
13243
Reid Spencera9b81012007-03-26 17:44:01 +000013244#ifndef NDEBUG
13245 std::string OrigI;
13246#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013247 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000013248 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13249
Chris Lattner90ac28c2002-08-02 19:29:35 +000013250 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013251 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013252 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013253 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013254 DEBUG(errs() << "IC: Old = " << *I << '\n'
13255 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013256
Chris Lattnerf523d062004-06-09 05:08:07 +000013257 // Everything uses the new instruction now.
13258 I->replaceAllUsesWith(Result);
13259
13260 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013261 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013262 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013263
Chris Lattner6934a042007-02-11 01:23:03 +000013264 // Move the name to the new instruction first.
13265 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013266
13267 // Insert the new instruction into the basic block...
13268 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013269 BasicBlock::iterator InsertPos = I;
13270
13271 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13272 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13273 ++InsertPos;
13274
13275 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013276
Chris Lattner7a1e9242009-08-30 06:13:40 +000013277 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013278 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013279#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013280 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13281 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013282#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013283
Chris Lattner90ac28c2002-08-02 19:29:35 +000013284 // If the instruction was modified, it's possible that it is now dead.
13285 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013286 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013287 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013288 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013289 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013290 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013291 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013292 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013293 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013294 }
13295 }
13296
Chris Lattner873ff012009-08-30 05:55:36 +000013297 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013298 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013299}
13300
Chris Lattnerec9c3582007-03-03 02:04:50 +000013301
13302bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013303 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013304 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013305 TD = getAnalysisIfAvailable<TargetData>();
13306
Chris Lattner74381062009-08-30 07:44:24 +000013307
13308 /// Builder - This is an IRBuilder that automatically inserts new
13309 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013310 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000013311 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000013312 InstCombineIRInserter(Worklist));
13313 Builder = &TheBuilder;
13314
Chris Lattnerec9c3582007-03-03 02:04:50 +000013315 bool EverMadeChange = false;
13316
13317 // Iterate while there is work to do.
13318 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013319 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013320 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000013321
13322 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013323 return EverMadeChange;
13324}
13325
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013326FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013327 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013328}